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, 2015, 2016 Free
9 * Software Foundation, Inc.
11 * Enhancements Copyright 2005 Alessandro Scotti
13 * The following terms apply to Digital Equipment Corporation's copyright
15 * ------------------------------------------------------------------------
18 * Permission to use, copy, modify, and distribute this software and its
19 * documentation for any purpose and without fee is hereby granted,
20 * provided that the above copyright notice appear in all copies and that
21 * both that copyright notice and this permission notice appear in
22 * supporting documentation, and that the name of Digital not be
23 * used in advertising or publicity pertaining to distribution of the
24 * software without specific, written prior permission.
26 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
27 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
28 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
29 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
30 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
31 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
33 * ------------------------------------------------------------------------
35 * The following terms apply to the enhanced version of XBoard
36 * distributed by the Free Software Foundation:
37 * ------------------------------------------------------------------------
39 * GNU XBoard is free software: you can redistribute it and/or modify
40 * it under the terms of the GNU General Public License as published by
41 * the Free Software Foundation, either version 3 of the License, or (at
42 * your option) any later version.
44 * GNU XBoard is distributed in the hope that it will be useful, but
45 * WITHOUT ANY WARRANTY; without even the implied warranty of
46 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
47 * General Public License for more details.
49 * You should have received a copy of the GNU General Public License
50 * along with this program. If not, see http://www.gnu.org/licenses/. *
52 *------------------------------------------------------------------------
53 ** See the file ChangeLog for a revision history. */
55 /* [AS] Also useful here for debugging */
59 int flock(int f, int code);
64 # define EGBB_NAME "egbbdll64.dll"
66 # define EGBB_NAME "egbbdll.dll"
71 # include <sys/file.h>
76 # define EGBB_NAME "egbbso64.so"
78 # define EGBB_NAME "egbbso.so"
80 // kludge to allow Windows code in back-end by converting it to corresponding Linux code
82 # define HMODULE void *
83 # define LoadLibrary(x) dlopen(x, RTLD_LAZY)
84 # define GetProcAddress dlsym
94 #include <sys/types.h>
103 #else /* not STDC_HEADERS */
106 # else /* not HAVE_STRING_H */
107 # include <strings.h>
108 # endif /* not HAVE_STRING_H */
109 #endif /* not STDC_HEADERS */
112 # include <sys/fcntl.h>
113 #else /* not HAVE_SYS_FCNTL_H */
116 # endif /* HAVE_FCNTL_H */
117 #endif /* not HAVE_SYS_FCNTL_H */
119 #if TIME_WITH_SYS_TIME
120 # include <sys/time.h>
124 # include <sys/time.h>
130 #if defined(_amigados) && !defined(__GNUC__)
135 extern int gettimeofday(struct timeval *, struct timezone *);
143 #include "frontend.h"
150 #include "backendz.h"
151 #include "evalgraph.h"
152 #include "engineoutput.h"
156 # define _(s) gettext (s)
157 # define N_(s) gettext_noop (s)
158 # define T_(s) gettext(s)
171 int establish P((void));
172 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
173 char *buf, int count, int error));
174 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
175 char *buf, int count, int error));
176 void SendToICS P((char *s));
177 void SendToICSDelayed P((char *s, long msdelay));
178 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
179 void HandleMachineMove P((char *message, ChessProgramState *cps));
180 int AutoPlayOneMove P((void));
181 int LoadGameOneMove P((ChessMove readAhead));
182 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
183 int LoadPositionFromFile P((char *filename, int n, char *title));
184 int SavePositionToFile P((char *filename));
185 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
186 void ShowMove P((int fromX, int fromY, int toX, int toY));
187 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
188 /*char*/int promoChar));
189 void BackwardInner P((int target));
190 void ForwardInner P((int target));
191 int Adjudicate P((ChessProgramState *cps));
192 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
193 void EditPositionDone P((Boolean fakeRights));
194 void PrintOpponents P((FILE *fp));
195 void PrintPosition P((FILE *fp, int move));
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 */
264 int deadRanks, handSize, handOffsets;
266 extern int tinyLayout, smallLayout;
267 ChessProgramStats programStats;
268 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
270 static int exiting = 0; /* [HGM] moved to top */
271 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
272 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
273 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
274 int partnerHighlight[2];
275 Boolean partnerBoardValid = 0;
276 char partnerStatus[MSG_SIZ];
278 Boolean originalFlip;
279 Boolean twoBoards = 0;
280 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
281 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
282 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
283 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
284 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
285 int opponentKibitzes;
286 int lastSavedGame; /* [HGM] save: ID of game */
287 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
288 extern int chatCount;
290 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
291 char legal[BOARD_RANKS][BOARD_FILES]; /* [HGM] legal target squares */
292 char lastMsg[MSG_SIZ];
293 char lastTalker[MSG_SIZ];
294 ChessSquare pieceSweep = EmptySquare;
295 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
296 int promoDefaultAltered;
297 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
298 static int initPing = -1;
299 int border; /* [HGM] width of board rim, needed to size seek graph */
300 char bestMove[MSG_SIZ], avoidMove[MSG_SIZ];
301 int solvingTime, totalTime;
303 /* States for ics_getting_history */
305 #define H_REQUESTED 1
306 #define H_GOT_REQ_HEADER 2
307 #define H_GOT_UNREQ_HEADER 3
308 #define H_GETTING_MOVES 4
309 #define H_GOT_UNWANTED_HEADER 5
311 /* whosays values for GameEnds */
320 /* Maximum number of games in a cmail message */
321 #define CMAIL_MAX_GAMES 20
323 /* Different types of move when calling RegisterMove */
325 #define CMAIL_RESIGN 1
327 #define CMAIL_ACCEPT 3
329 /* Different types of result to remember for each game */
330 #define CMAIL_NOT_RESULT 0
331 #define CMAIL_OLD_RESULT 1
332 #define CMAIL_NEW_RESULT 2
334 /* Telnet protocol constants */
345 safeStrCpy (char *dst, const char *src, size_t count)
348 assert( dst != NULL );
349 assert( src != NULL );
352 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
353 if( i == count && dst[count-1] != NULLCHAR)
355 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
356 if(appData.debugMode)
357 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
363 /* Some compiler can't cast u64 to double
364 * This function do the job for us:
366 * We use the highest bit for cast, this only
367 * works if the highest bit is not
368 * in use (This should not happen)
370 * We used this for all compiler
373 u64ToDouble (u64 value)
376 u64 tmp = value & u64Const(0x7fffffffffffffff);
377 r = (double)(s64)tmp;
378 if (value & u64Const(0x8000000000000000))
379 r += 9.2233720368547758080e18; /* 2^63 */
383 /* Fake up flags for now, as we aren't keeping track of castling
384 availability yet. [HGM] Change of logic: the flag now only
385 indicates the type of castlings allowed by the rule of the game.
386 The actual rights themselves are maintained in the array
387 castlingRights, as part of the game history, and are not probed
393 int flags = F_ALL_CASTLE_OK;
394 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
395 switch (gameInfo.variant) {
397 flags &= ~F_ALL_CASTLE_OK;
398 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
399 flags |= F_IGNORE_CHECK;
401 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
404 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
406 case VariantKriegspiel:
407 flags |= F_KRIEGSPIEL_CAPTURE;
409 case VariantCapaRandom:
410 case VariantFischeRandom:
411 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
412 case VariantNoCastle:
413 case VariantShatranj:
418 flags &= ~F_ALL_CASTLE_OK;
421 case VariantChuChess:
423 flags |= F_NULL_MOVE;
428 if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
432 FILE *gameFileFP, *debugFP, *serverFP;
433 char *currentDebugFile; // [HGM] debug split: to remember name
436 [AS] Note: sometimes, the sscanf() function is used to parse the input
437 into a fixed-size buffer. Because of this, we must be prepared to
438 receive strings as long as the size of the input buffer, which is currently
439 set to 4K for Windows and 8K for the rest.
440 So, we must either allocate sufficiently large buffers here, or
441 reduce the size of the input buffer in the input reading part.
444 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
445 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
446 char thinkOutput1[MSG_SIZ*10];
447 char promoRestrict[MSG_SIZ];
449 ChessProgramState first, second, pairing;
451 /* premove variables */
454 int premoveFromX = 0;
455 int premoveFromY = 0;
456 int premovePromoChar = 0;
458 Boolean alarmSounded;
459 /* end premove variables */
461 char *ics_prefix = "$";
462 enum ICS_TYPE ics_type = ICS_GENERIC;
464 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
465 int pauseExamForwardMostMove = 0;
466 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
467 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
468 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
469 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
470 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
471 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
472 int whiteFlag = FALSE, blackFlag = FALSE;
473 int userOfferedDraw = FALSE;
474 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
475 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
476 int cmailMoveType[CMAIL_MAX_GAMES];
477 long ics_clock_paused = 0;
478 ProcRef icsPR = NoProc, cmailPR = NoProc;
479 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
480 GameMode gameMode = BeginningOfGame;
481 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
482 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
483 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
484 int hiddenThinkOutputState = 0; /* [AS] */
485 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
486 int adjudicateLossPlies = 6;
487 char white_holding[64], black_holding[64];
488 TimeMark lastNodeCountTime;
489 long lastNodeCount=0;
490 int shiftKey, controlKey; // [HGM] set by mouse handler
492 int have_sent_ICS_logon = 0;
494 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
495 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
496 Boolean adjustedClock;
497 long timeControl_2; /* [AS] Allow separate time controls */
498 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
499 long timeRemaining[2][MAX_MOVES];
500 int matchGame = 0, nextGame = 0, roundNr = 0;
501 Boolean waitingForGame = FALSE, startingEngine = FALSE;
502 TimeMark programStartTime, pauseStart;
503 char ics_handle[MSG_SIZ];
504 int have_set_title = 0;
506 /* animateTraining preserves the state of appData.animate
507 * when Training mode is activated. This allows the
508 * response to be animated when appData.animate == TRUE and
509 * appData.animateDragging == TRUE.
511 Boolean animateTraining;
517 Board boards[MAX_MOVES];
518 /* [HGM] Following 7 needed for accurate legality tests: */
519 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
520 unsigned char initialRights[BOARD_FILES];
521 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
522 int initialRulePlies, FENrulePlies;
523 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
525 Boolean shuffleOpenings;
526 int mute; // mute all sounds
528 // [HGM] vari: next 12 to save and restore variations
529 #define MAX_VARIATIONS 10
530 int framePtr = MAX_MOVES-1; // points to free stack entry
532 int savedFirst[MAX_VARIATIONS];
533 int savedLast[MAX_VARIATIONS];
534 int savedFramePtr[MAX_VARIATIONS];
535 char *savedDetails[MAX_VARIATIONS];
536 ChessMove savedResult[MAX_VARIATIONS];
538 void PushTail P((int firstMove, int lastMove));
539 Boolean PopTail P((Boolean annotate));
540 void PushInner P((int firstMove, int lastMove));
541 void PopInner P((Boolean annotate));
542 void CleanupTail P((void));
544 ChessSquare FIDEArray[2][BOARD_FILES] = {
545 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
546 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
547 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
548 BlackKing, BlackBishop, BlackKnight, BlackRook }
551 ChessSquare twoKingsArray[2][BOARD_FILES] = {
552 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
553 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
554 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
555 BlackKing, BlackKing, BlackKnight, BlackRook }
558 ChessSquare KnightmateArray[2][BOARD_FILES] = {
559 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
560 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
561 { BlackRook, BlackMan, BlackBishop, BlackQueen,
562 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
565 ChessSquare SpartanArray[2][BOARD_FILES] = {
566 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
567 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
568 { BlackAlfil, BlackDragon, BlackKing, BlackTower,
569 BlackTower, BlackKing, BlackAngel, BlackAlfil }
572 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
573 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
574 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
575 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
576 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
579 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
580 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
581 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
582 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
583 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
586 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
587 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
588 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
589 { BlackRook, BlackKnight, BlackMan, BlackFerz,
590 BlackKing, BlackMan, BlackKnight, BlackRook }
593 ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
594 { WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
595 WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
596 { BlackRook, BlackKnight, BlackMan, BlackFerz,
597 BlackKing, BlackMan, BlackKnight, BlackRook }
600 ChessSquare lionArray[2][BOARD_FILES] = {
601 { WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
602 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
603 { BlackRook, BlackLion, BlackBishop, BlackQueen,
604 BlackKing, BlackBishop, BlackKnight, BlackRook }
608 #if (BOARD_FILES>=10)
609 ChessSquare ShogiArray[2][BOARD_FILES] = {
610 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
611 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
612 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
613 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
616 ChessSquare XiangqiArray[2][BOARD_FILES] = {
617 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
618 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
619 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
620 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
623 ChessSquare CapablancaArray[2][BOARD_FILES] = {
624 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
625 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
626 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
627 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
630 ChessSquare GreatArray[2][BOARD_FILES] = {
631 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
632 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
633 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
634 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
637 ChessSquare JanusArray[2][BOARD_FILES] = {
638 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
639 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
640 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
641 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
644 ChessSquare GrandArray[2][BOARD_FILES] = {
645 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
646 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
647 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
648 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
651 ChessSquare ChuChessArray[2][BOARD_FILES] = {
652 { WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
653 WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
654 { BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
655 BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
659 ChessSquare GothicArray[2][BOARD_FILES] = {
660 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
661 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
662 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
663 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
666 #define GothicArray CapablancaArray
670 ChessSquare FalconArray[2][BOARD_FILES] = {
671 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
672 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
673 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
674 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
677 #define FalconArray CapablancaArray
680 #else // !(BOARD_FILES>=10)
681 #define XiangqiPosition FIDEArray
682 #define CapablancaArray FIDEArray
683 #define GothicArray FIDEArray
684 #define GreatArray FIDEArray
685 #endif // !(BOARD_FILES>=10)
687 #if (BOARD_FILES>=12)
688 ChessSquare CourierArray[2][BOARD_FILES] = {
689 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
690 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
691 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
692 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
694 ChessSquare ChuArray[6][BOARD_FILES] = {
695 { WhiteLance, WhiteCat, WhiteCopper, WhiteFerz, WhiteWazir, WhiteKing,
696 WhiteAlfil, WhiteWazir, WhiteFerz, WhiteCopper, WhiteCat, WhiteLance },
697 { BlackLance, BlackCat, BlackCopper, BlackFerz, BlackWazir, BlackAlfil,
698 BlackKing, BlackWazir, BlackFerz, BlackCopper, BlackCat, BlackLance },
699 { WhiteAxe, EmptySquare, WhiteBishop, EmptySquare, WhiteClaw, WhiteMarshall,
700 WhiteAngel, WhiteClaw, EmptySquare, WhiteBishop, EmptySquare, WhiteAxe },
701 { BlackAxe, EmptySquare, BlackBishop, EmptySquare, BlackClaw, BlackAngel,
702 BlackMarshall, BlackClaw, EmptySquare, BlackBishop, EmptySquare, BlackAxe },
703 { WhiteDagger, WhiteSword, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
704 WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSword, WhiteDagger },
705 { BlackDagger, BlackSword, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
706 BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSword, BlackDagger }
708 #else // !(BOARD_FILES>=12)
709 #define CourierArray CapablancaArray
710 #define ChuArray CapablancaArray
711 #endif // !(BOARD_FILES>=12)
714 Board initialPosition;
717 /* Convert str to a rating. Checks for special cases of "----",
719 "++++", etc. Also strips ()'s */
721 string_to_rating (char *str)
723 while(*str && !isdigit(*str)) ++str;
725 return 0; /* One of the special "no rating" cases */
733 /* Init programStats */
734 programStats.movelist[0] = 0;
735 programStats.depth = 0;
736 programStats.nr_moves = 0;
737 programStats.moves_left = 0;
738 programStats.nodes = 0;
739 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
740 programStats.score = 0;
741 programStats.got_only_move = 0;
742 programStats.got_fail = 0;
743 programStats.line_is_book = 0;
748 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
749 if (appData.firstPlaysBlack) {
750 first.twoMachinesColor = "black\n";
751 second.twoMachinesColor = "white\n";
753 first.twoMachinesColor = "white\n";
754 second.twoMachinesColor = "black\n";
757 first.other = &second;
758 second.other = &first;
761 if(appData.timeOddsMode) {
762 norm = appData.timeOdds[0];
763 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
765 first.timeOdds = appData.timeOdds[0]/norm;
766 second.timeOdds = appData.timeOdds[1]/norm;
769 if(programVersion) free(programVersion);
770 if (appData.noChessProgram) {
771 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
772 sprintf(programVersion, "%s", PACKAGE_STRING);
774 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
775 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
776 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
781 UnloadEngine (ChessProgramState *cps)
783 /* Kill off first chess program */
784 if (cps->isr != NULL)
785 RemoveInputSource(cps->isr);
788 if (cps->pr != NoProc) {
790 DoSleep( appData.delayBeforeQuit );
791 SendToProgram("quit\n", cps);
792 DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
795 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
799 ClearOptions (ChessProgramState *cps)
802 cps->nrOptions = cps->comboCnt = 0;
803 for(i=0; i<MAX_OPTIONS; i++) {
804 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
805 cps->option[i].textValue = 0;
809 char *engineNames[] = {
810 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
811 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
813 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
814 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
819 InitEngine (ChessProgramState *cps, int n)
820 { // [HGM] all engine initialiation put in a function that does one engine
824 cps->which = engineNames[n];
825 cps->maybeThinking = FALSE;
829 cps->sendDrawOffers = 1;
831 cps->program = appData.chessProgram[n];
832 cps->host = appData.host[n];
833 cps->dir = appData.directory[n];
834 cps->initString = appData.engInitString[n];
835 cps->computerString = appData.computerString[n];
836 cps->useSigint = TRUE;
837 cps->useSigterm = TRUE;
838 cps->reuse = appData.reuse[n];
839 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
840 cps->useSetboard = FALSE;
842 cps->usePing = FALSE;
845 cps->usePlayother = FALSE;
846 cps->useColors = TRUE;
847 cps->useUsermove = FALSE;
848 cps->sendICS = FALSE;
849 cps->sendName = appData.icsActive;
850 cps->sdKludge = FALSE;
851 cps->stKludge = FALSE;
852 if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
853 TidyProgramName(cps->program, cps->host, cps->tidy);
855 ASSIGN(cps->variants, appData.noChessProgram ? "" : appData.variant);
856 cps->analysisSupport = 2; /* detect */
857 cps->analyzing = FALSE;
858 cps->initDone = FALSE;
860 cps->pseudo = appData.pseudo[n];
862 /* New features added by Tord: */
863 cps->useFEN960 = FALSE;
864 cps->useOOCastle = TRUE;
865 /* End of new features added by Tord. */
866 cps->fenOverride = appData.fenOverride[n];
868 /* [HGM] time odds: set factor for each machine */
869 cps->timeOdds = appData.timeOdds[n];
871 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
872 cps->accumulateTC = appData.accumulateTC[n];
873 cps->maxNrOfSessions = 1;
878 cps->drawDepth = appData.drawDepth[n];
879 cps->supportsNPS = UNKNOWN;
880 cps->memSize = FALSE;
881 cps->maxCores = FALSE;
882 ASSIGN(cps->egtFormats, "");
885 cps->optionSettings = appData.engOptions[n];
887 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
888 cps->isUCI = appData.isUCI[n]; /* [AS] */
889 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
892 if (appData.protocolVersion[n] > PROTOVER
893 || appData.protocolVersion[n] < 1)
898 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
899 appData.protocolVersion[n]);
900 if( (len >= MSG_SIZ) && appData.debugMode )
901 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
903 DisplayFatalError(buf, 0, 2);
907 cps->protocolVersion = appData.protocolVersion[n];
910 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
911 ParseFeatures(appData.featureDefaults, cps);
914 ChessProgramState *savCps;
916 GameMode oldMode, tryNr;
918 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
919 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
920 char *insert, *wbOptions, *currentEngine[2]; // point in ChessProgramNames were we should insert new engine
921 static char newEngineCommand[MSG_SIZ];
924 FloatToFront(char **list, char *engineLine)
926 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
928 if(appData.recentEngines <= 0) return;
929 TidyProgramName(engineLine, "localhost", tidy+1);
930 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
931 strncpy(buf+1, *list, MSG_SIZ-50);
932 if(p = strstr(buf, tidy)) { // tidy name appears in list
933 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
934 while(*p++ = *++q); // squeeze out
936 strcat(tidy, buf+1); // put list behind tidy name
937 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
938 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
939 ASSIGN(*list, tidy+1);
946 if(*engineListFile && (f = fopen(engineListFile, "w"))) {
947 fprintf(f, "-firstChessProgramNames {%s}\n", firstChessProgramNames);
953 AddToEngineList (int i)
956 char quote, buf[MSG_SIZ];
957 char *q = firstChessProgramNames, *p = newEngineCommand;
958 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
959 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
960 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s",
961 quote, p, quote, appData.directory[i],
962 useNick ? " -fn \"" : "",
963 useNick ? nickName : "",
965 v1 ? " -firstProtocolVersion 1" : "",
966 hasBook ? "" : " -fNoOwnBookUCI",
967 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
968 storeVariant ? " -variant " : "",
969 storeVariant ? VariantName(gameInfo.variant) : "");
970 if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " %s", wbOptions);
971 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 2);
972 if(insert != q) insert[-1] = NULLCHAR;
973 snprintf(firstChessProgramNames, len, "%s\n%s\n%s", q, buf, insert);
976 FloatToFront(&appData.recentEngineList, buf);
977 ASSIGN(currentEngine[i], buf);
984 if(WaitForEngine(savCps, LoadEngine)) return;
985 if(tryNr == 1 && !isUCI) { SendToProgram("uci\n", savCps); tryNr = 2; ScheduleDelayedEvent(LoadEngine, FEATURE_TIMEOUT); return; }
986 if(tryNr) v1 = (tryNr == 2), tryNr = 0, AddToEngineList(0); // deferred to after protocol determination
987 CommonEngineInit(); // recalculate time odds
988 if(gameInfo.variant != StringToVariant(appData.variant)) {
989 // we changed variant when loading the engine; this forces us to reset
990 Reset(TRUE, savCps != &first);
991 oldMode = BeginningOfGame; // to prevent restoring old mode
993 InitChessProgram(savCps, FALSE);
994 if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
995 DisplayMessage("", "");
996 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
997 for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
1000 if(oldMode == AnalyzeMode) AnalyzeModeEvent();
1004 ReplaceEngine (ChessProgramState *cps, int n)
1006 oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
1008 if(oldMode != BeginningOfGame) EditGameEvent();
1011 appData.noChessProgram = FALSE;
1012 appData.clockMode = TRUE;
1015 if(n) return; // only startup first engine immediately; second can wait
1016 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
1020 static char resetOptions[] =
1021 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
1022 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
1023 "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
1024 "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
1027 Load (ChessProgramState *cps, int i)
1029 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
1030 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
1031 ASSIGN(currentEngine[i], engineLine);
1032 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
1033 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
1034 ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
1035 FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
1036 appData.firstProtocolVersion = PROTOVER;
1037 ParseArgsFromString(buf);
1039 ReplaceEngine(cps, i);
1040 FloatToFront(&appData.recentEngineList, engineLine);
1041 if(gameMode == BeginningOfGame) Reset(TRUE, TRUE);
1045 while(q = strchr(p, SLASH)) p = q+1;
1046 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
1047 if(engineDir[0] != NULLCHAR) {
1048 ASSIGN(appData.directory[i], engineDir); p = engineName;
1049 } else if(p != engineName) { // derive directory from engine path, when not given
1051 ASSIGN(appData.directory[i], engineName);
1053 if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
1054 } else { ASSIGN(appData.directory[i], "."); }
1055 jar = (strstr(p, ".jar") == p + strlen(p) - 4);
1057 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
1058 snprintf(command, MSG_SIZ, "%s %s", p, params);
1061 if(jar) { snprintf(buf3, MSG_SIZ, "java -jar %s", p); p = buf3; }
1062 ASSIGN(appData.chessProgram[i], p);
1063 appData.isUCI[i] = isUCI;
1064 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
1065 appData.hasOwnBookUCI[i] = hasBook;
1066 if(!nickName[0]) useNick = FALSE;
1067 if(useNick) ASSIGN(appData.pgnName[i], nickName);
1068 safeStrCpy(newEngineCommand, p, MSG_SIZ);
1070 ReplaceEngine(cps, i);
1076 int matched, min, sec;
1078 * Parse timeControl resource
1080 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
1081 appData.movesPerSession)) {
1083 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
1084 DisplayFatalError(buf, 0, 2);
1088 * Parse searchTime resource
1090 if (*appData.searchTime != NULLCHAR) {
1091 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
1093 searchTime = min * 60;
1094 } else if (matched == 2) {
1095 searchTime = min * 60 + sec;
1098 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1099 DisplayFatalError(buf, 0, 2);
1108 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1109 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1111 GetTimeMark(&programStartTime);
1112 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1113 appData.seedBase = random() + (random()<<15);
1114 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1116 ClearProgramStats();
1117 programStats.ok_to_send = 1;
1118 programStats.seen_stat = 0;
1121 * Initialize game list
1127 * Internet chess server status
1129 if (appData.icsActive) {
1130 appData.matchMode = FALSE;
1131 appData.matchGames = 0;
1133 appData.noChessProgram = !appData.zippyPlay;
1135 appData.zippyPlay = FALSE;
1136 appData.zippyTalk = FALSE;
1137 appData.noChessProgram = TRUE;
1139 if (*appData.icsHelper != NULLCHAR) {
1140 appData.useTelnet = TRUE;
1141 appData.telnetProgram = appData.icsHelper;
1144 appData.zippyTalk = appData.zippyPlay = FALSE;
1147 /* [AS] Initialize pv info list [HGM] and game state */
1151 for( i=0; i<=framePtr; i++ ) {
1152 pvInfoList[i].depth = -1;
1153 boards[i][EP_STATUS] = EP_NONE;
1154 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1160 /* [AS] Adjudication threshold */
1161 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1163 InitEngine(&first, 0);
1164 InitEngine(&second, 1);
1167 pairing.which = "pairing"; // pairing engine
1168 pairing.pr = NoProc;
1170 pairing.program = appData.pairingEngine;
1171 pairing.host = "localhost";
1174 if (appData.icsActive) {
1175 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1176 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1177 appData.clockMode = FALSE;
1178 first.sendTime = second.sendTime = 0;
1182 /* Override some settings from environment variables, for backward
1183 compatibility. Unfortunately it's not feasible to have the env
1184 vars just set defaults, at least in xboard. Ugh.
1186 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1191 if (!appData.icsActive) {
1195 /* Check for variants that are supported only in ICS mode,
1196 or not at all. Some that are accepted here nevertheless
1197 have bugs; see comments below.
1199 VariantClass variant = StringToVariant(appData.variant);
1201 case VariantBughouse: /* need four players and two boards */
1202 case VariantKriegspiel: /* need to hide pieces and move details */
1203 /* case VariantFischeRandom: (Fabien: moved below) */
1204 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1205 if( (len >= MSG_SIZ) && appData.debugMode )
1206 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1208 DisplayFatalError(buf, 0, 2);
1211 case VariantUnknown:
1212 case VariantLoadable:
1222 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1223 if( (len >= MSG_SIZ) && appData.debugMode )
1224 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1226 DisplayFatalError(buf, 0, 2);
1229 case VariantNormal: /* definitely works! */
1230 if(strcmp(appData.variant, "normal") && !appData.noChessProgram) { // [HGM] hope this is an engine-defined variant
1231 safeStrCpy(engineVariant, appData.variant, MSG_SIZ);
1234 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1235 case VariantFairy: /* [HGM] TestLegality definitely off! */
1236 case VariantGothic: /* [HGM] should work */
1237 case VariantCapablanca: /* [HGM] should work */
1238 case VariantCourier: /* [HGM] initial forced moves not implemented */
1239 case VariantShogi: /* [HGM] could still mate with pawn drop */
1240 case VariantChu: /* [HGM] experimental */
1241 case VariantKnightmate: /* [HGM] should work */
1242 case VariantCylinder: /* [HGM] untested */
1243 case VariantFalcon: /* [HGM] untested */
1244 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1245 offboard interposition not understood */
1246 case VariantWildCastle: /* pieces not automatically shuffled */
1247 case VariantNoCastle: /* pieces not automatically shuffled */
1248 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1249 case VariantLosers: /* should work except for win condition,
1250 and doesn't know captures are mandatory */
1251 case VariantSuicide: /* should work except for win condition,
1252 and doesn't know captures are mandatory */
1253 case VariantGiveaway: /* should work except for win condition,
1254 and doesn't know captures are mandatory */
1255 case VariantTwoKings: /* should work */
1256 case VariantAtomic: /* should work except for win condition */
1257 case Variant3Check: /* should work except for win condition */
1258 case VariantShatranj: /* should work except for all win conditions */
1259 case VariantMakruk: /* should work except for draw countdown */
1260 case VariantASEAN : /* should work except for draw countdown */
1261 case VariantBerolina: /* might work if TestLegality is off */
1262 case VariantCapaRandom: /* should work */
1263 case VariantJanus: /* should work */
1264 case VariantSuper: /* experimental */
1265 case VariantGreat: /* experimental, requires legality testing to be off */
1266 case VariantSChess: /* S-Chess, should work */
1267 case VariantGrand: /* should work */
1268 case VariantSpartan: /* should work */
1269 case VariantLion: /* should work */
1270 case VariantChuChess: /* should work */
1278 NextIntegerFromString (char ** str, long * value)
1283 while( *s == ' ' || *s == '\t' ) {
1289 if( *s >= '0' && *s <= '9' ) {
1290 while( *s >= '0' && *s <= '9' ) {
1291 *value = *value * 10 + (*s - '0');
1304 NextTimeControlFromString (char ** str, long * value)
1307 int result = NextIntegerFromString( str, &temp );
1310 *value = temp * 60; /* Minutes */
1311 if( **str == ':' ) {
1313 result = NextIntegerFromString( str, &temp );
1314 *value += temp; /* Seconds */
1322 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1323 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1324 int result = -1, type = 0; long temp, temp2;
1326 if(**str != ':') return -1; // old params remain in force!
1328 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1329 if( NextIntegerFromString( str, &temp ) ) return -1;
1330 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1333 /* time only: incremental or sudden-death time control */
1334 if(**str == '+') { /* increment follows; read it */
1336 if(**str == '!') type = *(*str)++; // Bronstein TC
1337 if(result = NextIntegerFromString( str, &temp2)) return -1;
1338 *inc = temp2 * 1000;
1339 if(**str == '.') { // read fraction of increment
1340 char *start = ++(*str);
1341 if(result = NextIntegerFromString( str, &temp2)) return -1;
1343 while(start++ < *str) temp2 /= 10;
1347 *moves = 0; *tc = temp * 1000; *incType = type;
1351 (*str)++; /* classical time control */
1352 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1364 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1365 { /* [HGM] get time to add from the multi-session time-control string */
1366 int incType, moves=1; /* kludge to force reading of first session */
1367 long time, increment;
1370 if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1372 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1373 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1374 if(movenr == -1) return time; /* last move before new session */
1375 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1376 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1377 if(!moves) return increment; /* current session is incremental */
1378 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1379 } while(movenr >= -1); /* try again for next session */
1381 return 0; // no new time quota on this move
1385 ParseTimeControl (char *tc, float ti, int mps)
1389 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1392 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1393 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1394 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1398 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1400 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1403 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1405 snprintf(buf, MSG_SIZ, ":%s", mytc);
1407 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1409 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1414 /* Parse second time control */
1417 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1425 timeControl_2 = tc2 * 1000;
1435 timeControl = tc1 * 1000;
1438 timeIncrement = ti * 1000; /* convert to ms */
1439 movesPerSession = 0;
1442 movesPerSession = mps;
1450 if (appData.debugMode) {
1451 # ifdef __GIT_VERSION
1452 fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1454 fprintf(debugFP, "Version: %s\n", programVersion);
1457 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1459 set_cont_sequence(appData.wrapContSeq);
1460 if (appData.matchGames > 0) {
1461 appData.matchMode = TRUE;
1462 } else if (appData.matchMode) {
1463 appData.matchGames = 1;
1465 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1466 appData.matchGames = appData.sameColorGames;
1467 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1468 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1469 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1472 if (appData.noChessProgram || first.protocolVersion == 1) {
1475 /* kludge: allow timeout for initial "feature" commands */
1477 DisplayMessage("", _("Starting chess program"));
1478 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1483 CalculateIndex (int index, int gameNr)
1484 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1486 if(index > 0) return index; // fixed nmber
1487 if(index == 0) return 1;
1488 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1489 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1494 LoadGameOrPosition (int gameNr)
1495 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1496 if (*appData.loadGameFile != NULLCHAR) {
1497 if (!LoadGameFromFile(appData.loadGameFile,
1498 CalculateIndex(appData.loadGameIndex, gameNr),
1499 appData.loadGameFile, FALSE)) {
1500 DisplayFatalError(_("Bad game file"), 0, 1);
1503 } else if (*appData.loadPositionFile != NULLCHAR) {
1504 if (!LoadPositionFromFile(appData.loadPositionFile,
1505 CalculateIndex(appData.loadPositionIndex, gameNr),
1506 appData.loadPositionFile)) {
1507 DisplayFatalError(_("Bad position file"), 0, 1);
1515 ReserveGame (int gameNr, char resChar)
1517 FILE *tf = fopen(appData.tourneyFile, "r+");
1518 char *p, *q, c, buf[MSG_SIZ];
1519 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1520 safeStrCpy(buf, lastMsg, MSG_SIZ);
1521 DisplayMessage(_("Pick new game"), "");
1522 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1523 ParseArgsFromFile(tf);
1524 p = q = appData.results;
1525 if(appData.debugMode) {
1526 char *r = appData.participants;
1527 fprintf(debugFP, "results = '%s'\n", p);
1528 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1529 fprintf(debugFP, "\n");
1531 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1533 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1534 safeStrCpy(q, p, strlen(p) + 2);
1535 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1536 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1537 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1538 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1541 fseek(tf, -(strlen(p)+4), SEEK_END);
1543 if(c != '"') // depending on DOS or Unix line endings we can be one off
1544 fseek(tf, -(strlen(p)+2), SEEK_END);
1545 else fseek(tf, -(strlen(p)+3), SEEK_END);
1546 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1547 DisplayMessage(buf, "");
1548 free(p); appData.results = q;
1549 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1550 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1551 int round = appData.defaultMatchGames * appData.tourneyType;
1552 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1553 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1554 UnloadEngine(&first); // next game belongs to other pairing;
1555 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1557 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1561 MatchEvent (int mode)
1562 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1564 if(matchMode) { // already in match mode: switch it off
1566 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1569 // if(gameMode != BeginningOfGame) {
1570 // DisplayError(_("You can only start a match from the initial position."), 0);
1574 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1575 /* Set up machine vs. machine match */
1577 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1578 if(appData.tourneyFile[0]) {
1580 if(nextGame > appData.matchGames) {
1582 if(strchr(appData.results, '*') == NULL) {
1584 appData.tourneyCycles++;
1585 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1587 NextTourneyGame(-1, &dummy);
1589 if(nextGame <= appData.matchGames) {
1590 DisplayNote(_("You restarted an already completed tourney.\nOne more cycle will now be added to it.\nGames commence in 10 sec."));
1592 ScheduleDelayedEvent(NextMatchGame, 10000);
1597 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1598 DisplayError(buf, 0);
1599 appData.tourneyFile[0] = 0;
1603 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1604 DisplayFatalError(_("Can't have a match with no chess programs"),
1609 matchGame = roundNr = 1;
1610 first.matchWins = second.matchWins = totalTime = 0; // [HGM] match: needed in later matches
1615 InitBackEnd3 P((void))
1617 GameMode initialMode;
1621 ParseFeatures(appData.features[0], &first);
1622 if(!appData.icsActive && !appData.noChessProgram && !appData.matchMode && // mode involves only first engine
1623 !strcmp(appData.variant, "normal") && // no explicit variant request
1624 appData.NrRanks == -1 && appData.NrFiles == -1 && appData.holdingsSize == -1 && // no size overrides requested
1625 !SupportedVariant(first.variants, VariantNormal, 8, 8, 0, first.protocolVersion, "") && // but 'normal' won't work with engine
1626 !SupportedVariant(first.variants, VariantFischeRandom, 8, 8, 0, first.protocolVersion, "") ) { // nor will Chess960
1627 char c, *q = first.variants, *p = strchr(q, ',');
1628 if(p) *p = NULLCHAR;
1629 if(StringToVariant(q) != VariantUnknown) { // the engine can play a recognized variant, however
1631 if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
1632 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
1633 ASSIGN(appData.variant, q); // fake user requested the first variant played by the engine
1634 Reset(TRUE, FALSE); // and re-initialize
1639 InitChessProgram(&first, startedFromSetupPosition);
1641 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1642 free(programVersion);
1643 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1644 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1645 FloatToFront(&appData.recentEngineList, currentEngine[0] ? currentEngine[0] : appData.firstChessProgram);
1648 if (appData.icsActive) {
1650 /* [DM] Make a console window if needed [HGM] merged ifs */
1656 if (*appData.icsCommPort != NULLCHAR)
1657 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1658 appData.icsCommPort);
1660 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1661 appData.icsHost, appData.icsPort);
1663 if( (len >= MSG_SIZ) && appData.debugMode )
1664 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1666 DisplayFatalError(buf, err, 1);
1671 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1673 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1674 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1675 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1676 } else if (appData.noChessProgram) {
1682 if (*appData.cmailGameName != NULLCHAR) {
1684 OpenLoopback(&cmailPR);
1686 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1690 DisplayMessage("", "");
1691 if (StrCaseCmp(appData.initialMode, "") == 0) {
1692 initialMode = BeginningOfGame;
1693 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1694 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1695 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1696 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1699 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1700 initialMode = TwoMachinesPlay;
1701 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1702 initialMode = AnalyzeFile;
1703 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1704 initialMode = AnalyzeMode;
1705 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1706 initialMode = MachinePlaysWhite;
1707 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1708 initialMode = MachinePlaysBlack;
1709 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1710 initialMode = EditGame;
1711 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1712 initialMode = EditPosition;
1713 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1714 initialMode = Training;
1716 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1717 if( (len >= MSG_SIZ) && appData.debugMode )
1718 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1720 DisplayFatalError(buf, 0, 2);
1724 if (appData.matchMode) {
1725 if(appData.tourneyFile[0]) { // start tourney from command line
1727 if(f = fopen(appData.tourneyFile, "r")) {
1728 ParseArgsFromFile(f); // make sure tourney parmeters re known
1730 appData.clockMode = TRUE;
1732 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1735 } else if (*appData.cmailGameName != NULLCHAR) {
1736 /* Set up cmail mode */
1737 ReloadCmailMsgEvent(TRUE);
1739 /* Set up other modes */
1740 if (initialMode == AnalyzeFile) {
1741 if (*appData.loadGameFile == NULLCHAR) {
1742 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1746 if (*appData.loadGameFile != NULLCHAR) {
1747 (void) LoadGameFromFile(appData.loadGameFile,
1748 appData.loadGameIndex,
1749 appData.loadGameFile, TRUE);
1750 } else if (*appData.loadPositionFile != NULLCHAR) {
1751 (void) LoadPositionFromFile(appData.loadPositionFile,
1752 appData.loadPositionIndex,
1753 appData.loadPositionFile);
1754 /* [HGM] try to make self-starting even after FEN load */
1755 /* to allow automatic setup of fairy variants with wtm */
1756 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1757 gameMode = BeginningOfGame;
1758 setboardSpoiledMachineBlack = 1;
1760 /* [HGM] loadPos: make that every new game uses the setup */
1761 /* from file as long as we do not switch variant */
1762 if(!blackPlaysFirst) {
1763 startedFromPositionFile = TRUE;
1764 CopyBoard(filePosition, boards[0]);
1765 CopyBoard(initialPosition, boards[0]);
1767 } else if(*appData.fen != NULLCHAR) {
1768 if(ParseFEN(filePosition, &blackPlaysFirst, appData.fen, TRUE) && !blackPlaysFirst) {
1769 startedFromPositionFile = TRUE;
1773 if (initialMode == AnalyzeMode) {
1774 if (appData.noChessProgram) {
1775 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1778 if (appData.icsActive) {
1779 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1783 } else if (initialMode == AnalyzeFile) {
1784 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1785 ShowThinkingEvent();
1787 AnalysisPeriodicEvent(1);
1788 } else if (initialMode == MachinePlaysWhite) {
1789 if (appData.noChessProgram) {
1790 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1794 if (appData.icsActive) {
1795 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1799 MachineWhiteEvent();
1800 } else if (initialMode == MachinePlaysBlack) {
1801 if (appData.noChessProgram) {
1802 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1806 if (appData.icsActive) {
1807 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1811 MachineBlackEvent();
1812 } else if (initialMode == TwoMachinesPlay) {
1813 if (appData.noChessProgram) {
1814 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1818 if (appData.icsActive) {
1819 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1824 } else if (initialMode == EditGame) {
1826 } else if (initialMode == EditPosition) {
1827 EditPositionEvent();
1828 } else if (initialMode == Training) {
1829 if (*appData.loadGameFile == NULLCHAR) {
1830 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1839 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1841 DisplayBook(current+1);
1843 MoveHistorySet( movelist, first, last, current, pvInfoList );
1845 EvalGraphSet( first, last, current, pvInfoList );
1847 MakeEngineOutputTitle();
1851 * Establish will establish a contact to a remote host.port.
1852 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1853 * used to talk to the host.
1854 * Returns 0 if okay, error code if not.
1861 if (*appData.icsCommPort != NULLCHAR) {
1862 /* Talk to the host through a serial comm port */
1863 return OpenCommPort(appData.icsCommPort, &icsPR);
1865 } else if (*appData.gateway != NULLCHAR) {
1866 if (*appData.remoteShell == NULLCHAR) {
1867 /* Use the rcmd protocol to run telnet program on a gateway host */
1868 snprintf(buf, sizeof(buf), "%s %s %s",
1869 appData.telnetProgram, appData.icsHost, appData.icsPort);
1870 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1873 /* Use the rsh program to run telnet program on a gateway host */
1874 if (*appData.remoteUser == NULLCHAR) {
1875 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1876 appData.gateway, appData.telnetProgram,
1877 appData.icsHost, appData.icsPort);
1879 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1880 appData.remoteShell, appData.gateway,
1881 appData.remoteUser, appData.telnetProgram,
1882 appData.icsHost, appData.icsPort);
1884 return StartChildProcess(buf, "", &icsPR);
1887 } else if (appData.useTelnet) {
1888 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1891 /* TCP socket interface differs somewhat between
1892 Unix and NT; handle details in the front end.
1894 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1899 EscapeExpand (char *p, char *q)
1900 { // [HGM] initstring: routine to shape up string arguments
1901 while(*p++ = *q++) if(p[-1] == '\\')
1903 case 'n': p[-1] = '\n'; break;
1904 case 'r': p[-1] = '\r'; break;
1905 case 't': p[-1] = '\t'; break;
1906 case '\\': p[-1] = '\\'; break;
1907 case 0: *p = 0; return;
1908 default: p[-1] = q[-1]; break;
1913 show_bytes (FILE *fp, char *buf, int count)
1916 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1917 fprintf(fp, "\\%03o", *buf & 0xff);
1926 /* Returns an errno value */
1928 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1930 char buf[8192], *p, *q, *buflim;
1931 int left, newcount, outcount;
1933 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1934 *appData.gateway != NULLCHAR) {
1935 if (appData.debugMode) {
1936 fprintf(debugFP, ">ICS: ");
1937 show_bytes(debugFP, message, count);
1938 fprintf(debugFP, "\n");
1940 return OutputToProcess(pr, message, count, outError);
1943 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1950 if (appData.debugMode) {
1951 fprintf(debugFP, ">ICS: ");
1952 show_bytes(debugFP, buf, newcount);
1953 fprintf(debugFP, "\n");
1955 outcount = OutputToProcess(pr, buf, newcount, outError);
1956 if (outcount < newcount) return -1; /* to be sure */
1963 } else if (((unsigned char) *p) == TN_IAC) {
1964 *q++ = (char) TN_IAC;
1971 if (appData.debugMode) {
1972 fprintf(debugFP, ">ICS: ");
1973 show_bytes(debugFP, buf, newcount);
1974 fprintf(debugFP, "\n");
1976 outcount = OutputToProcess(pr, buf, newcount, outError);
1977 if (outcount < newcount) return -1; /* to be sure */
1982 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1984 int outError, outCount;
1985 static int gotEof = 0;
1988 /* Pass data read from player on to ICS */
1991 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1992 if (outCount < count) {
1993 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1995 if(have_sent_ICS_logon == 2) {
1996 if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1997 fprintf(ini, "%s", message);
1998 have_sent_ICS_logon = 3;
2000 have_sent_ICS_logon = 1;
2001 } else if(have_sent_ICS_logon == 3) {
2002 fprintf(ini, "%s", message);
2004 have_sent_ICS_logon = 1;
2006 } else if (count < 0) {
2007 RemoveInputSource(isr);
2008 DisplayFatalError(_("Error reading from keyboard"), error, 1);
2009 } else if (gotEof++ > 0) {
2010 RemoveInputSource(isr);
2011 DisplayFatalError(_("Got end of file from keyboard"), 0, 666); // [HGM] 666 is kludge to alert front end
2017 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
2018 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
2019 connectionAlive = FALSE; // only sticks if no response to 'date' command.
2020 SendToICS("date\n");
2021 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
2024 /* added routine for printf style output to ics */
2026 ics_printf (char *format, ...)
2028 char buffer[MSG_SIZ];
2031 va_start(args, format);
2032 vsnprintf(buffer, sizeof(buffer), format, args);
2033 buffer[sizeof(buffer)-1] = '\0';
2041 int count, outCount, outError;
2043 if (icsPR == NoProc) return;
2046 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
2047 if (outCount < count) {
2048 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2052 /* This is used for sending logon scripts to the ICS. Sending
2053 without a delay causes problems when using timestamp on ICC
2054 (at least on my machine). */
2056 SendToICSDelayed (char *s, long msdelay)
2058 int count, outCount, outError;
2060 if (icsPR == NoProc) return;
2063 if (appData.debugMode) {
2064 fprintf(debugFP, ">ICS: ");
2065 show_bytes(debugFP, s, count);
2066 fprintf(debugFP, "\n");
2068 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
2070 if (outCount < count) {
2071 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2076 /* Remove all highlighting escape sequences in s
2077 Also deletes any suffix starting with '('
2080 StripHighlightAndTitle (char *s)
2082 static char retbuf[MSG_SIZ];
2085 while (*s != NULLCHAR) {
2086 while (*s == '\033') {
2087 while (*s != NULLCHAR && !isalpha(*s)) s++;
2088 if (*s != NULLCHAR) s++;
2090 while (*s != NULLCHAR && *s != '\033') {
2091 if (*s == '(' || *s == '[') {
2102 /* Remove all highlighting escape sequences in s */
2104 StripHighlight (char *s)
2106 static char retbuf[MSG_SIZ];
2109 while (*s != NULLCHAR) {
2110 while (*s == '\033') {
2111 while (*s != NULLCHAR && !isalpha(*s)) s++;
2112 if (*s != NULLCHAR) s++;
2114 while (*s != NULLCHAR && *s != '\033') {
2122 char engineVariant[MSG_SIZ];
2123 char *variantNames[] = VARIANT_NAMES;
2125 VariantName (VariantClass v)
2127 if(v == VariantUnknown || *engineVariant) return engineVariant;
2128 return variantNames[v];
2132 /* Identify a variant from the strings the chess servers use or the
2133 PGN Variant tag names we use. */
2135 StringToVariant (char *e)
2139 VariantClass v = VariantNormal;
2140 int i, found = FALSE;
2141 char buf[MSG_SIZ], c;
2146 /* [HGM] skip over optional board-size prefixes */
2147 if( sscanf(e, "%dx%d_%c", &i, &i, &c) == 3 ||
2148 sscanf(e, "%dx%d+%d_%c", &i, &i, &i, &c) == 4 ) {
2149 while( *e++ != '_');
2152 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2156 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2157 if (p = StrCaseStr(e, variantNames[i])) {
2158 if(p && i >= VariantShogi && (p != e && !appData.icsActive || isalpha(p[strlen(variantNames[i])]))) continue;
2159 v = (VariantClass) i;
2166 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2167 || StrCaseStr(e, "wild/fr")
2168 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2169 v = VariantFischeRandom;
2170 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2171 (i = 1, p = StrCaseStr(e, "w"))) {
2173 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2180 case 0: /* FICS only, actually */
2182 /* Castling legal even if K starts on d-file */
2183 v = VariantWildCastle;
2188 /* Castling illegal even if K & R happen to start in
2189 normal positions. */
2190 v = VariantNoCastle;
2203 /* Castling legal iff K & R start in normal positions */
2209 /* Special wilds for position setup; unclear what to do here */
2210 v = VariantLoadable;
2213 /* Bizarre ICC game */
2214 v = VariantTwoKings;
2217 v = VariantKriegspiel;
2223 v = VariantFischeRandom;
2226 v = VariantCrazyhouse;
2229 v = VariantBughouse;
2235 /* Not quite the same as FICS suicide! */
2236 v = VariantGiveaway;
2242 v = VariantShatranj;
2245 /* Temporary names for future ICC types. The name *will* change in
2246 the next xboard/WinBoard release after ICC defines it. */
2284 v = VariantCapablanca;
2287 v = VariantKnightmate;
2293 v = VariantCylinder;
2299 v = VariantCapaRandom;
2302 v = VariantBerolina;
2314 /* Found "wild" or "w" in the string but no number;
2315 must assume it's normal chess. */
2319 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2320 if( (len >= MSG_SIZ) && appData.debugMode )
2321 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2323 DisplayError(buf, 0);
2329 if (appData.debugMode) {
2330 fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2331 e, wnum, VariantName(v));
2336 static int leftover_start = 0, leftover_len = 0;
2337 char star_match[STAR_MATCH_N][MSG_SIZ];
2339 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2340 advance *index beyond it, and set leftover_start to the new value of
2341 *index; else return FALSE. If pattern contains the character '*', it
2342 matches any sequence of characters not containing '\r', '\n', or the
2343 character following the '*' (if any), and the matched sequence(s) are
2344 copied into star_match.
2347 looking_at ( char *buf, int *index, char *pattern)
2349 char *bufp = &buf[*index], *patternp = pattern;
2351 char *matchp = star_match[0];
2354 if (*patternp == NULLCHAR) {
2355 *index = leftover_start = bufp - buf;
2359 if (*bufp == NULLCHAR) return FALSE;
2360 if (*patternp == '*') {
2361 if (*bufp == *(patternp + 1)) {
2363 matchp = star_match[++star_count];
2367 } else if (*bufp == '\n' || *bufp == '\r') {
2369 if (*patternp == NULLCHAR)
2374 *matchp++ = *bufp++;
2378 if (*patternp != *bufp) return FALSE;
2385 SendToPlayer (char *data, int length)
2387 int error, outCount;
2388 outCount = OutputToProcess(NoProc, data, length, &error);
2389 if (outCount < length) {
2390 DisplayFatalError(_("Error writing to display"), error, 1);
2395 PackHolding (char packed[], char *holding)
2405 switch (runlength) {
2416 sprintf(q, "%d", runlength);
2428 /* Telnet protocol requests from the front end */
2430 TelnetRequest (unsigned char ddww, unsigned char option)
2432 unsigned char msg[3];
2433 int outCount, outError;
2435 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2437 if (appData.debugMode) {
2438 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2454 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2463 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2466 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2471 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2473 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2480 if (!appData.icsActive) return;
2481 TelnetRequest(TN_DO, TN_ECHO);
2487 if (!appData.icsActive) return;
2488 TelnetRequest(TN_DONT, TN_ECHO);
2492 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2494 /* put the holdings sent to us by the server on the board holdings area */
2495 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2499 if(gameInfo.holdingsWidth < 2) return;
2500 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2501 return; // prevent overwriting by pre-board holdings
2503 if( (int)lowestPiece >= BlackPawn ) {
2506 holdingsStartRow = handSize-1;
2509 holdingsColumn = BOARD_WIDTH-1;
2510 countsColumn = BOARD_WIDTH-2;
2511 holdingsStartRow = 0;
2515 for(i=0; i<BOARD_RANKS-1; i++) { /* clear holdings */
2516 board[i][holdingsColumn] = EmptySquare;
2517 board[i][countsColumn] = (ChessSquare) 0;
2519 while( (p=*holdings++) != NULLCHAR ) {
2520 piece = CharToPiece( ToUpper(p) );
2521 if(piece == EmptySquare) continue;
2522 /*j = (int) piece - (int) WhitePawn;*/
2523 j = PieceToNumber(piece);
2524 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2525 if(j < 0) continue; /* should not happen */
2526 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2527 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2528 board[holdingsStartRow+j*direction][countsColumn]++;
2534 VariantSwitch (Board board, VariantClass newVariant)
2536 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2537 static Board oldBoard;
2539 startedFromPositionFile = FALSE;
2540 if(gameInfo.variant == newVariant) return;
2542 /* [HGM] This routine is called each time an assignment is made to
2543 * gameInfo.variant during a game, to make sure the board sizes
2544 * are set to match the new variant. If that means adding or deleting
2545 * holdings, we shift the playing board accordingly
2546 * This kludge is needed because in ICS observe mode, we get boards
2547 * of an ongoing game without knowing the variant, and learn about the
2548 * latter only later. This can be because of the move list we requested,
2549 * in which case the game history is refilled from the beginning anyway,
2550 * but also when receiving holdings of a crazyhouse game. In the latter
2551 * case we want to add those holdings to the already received position.
2555 if (appData.debugMode) {
2556 fprintf(debugFP, "Switch board from %s to %s\n",
2557 VariantName(gameInfo.variant), VariantName(newVariant));
2558 setbuf(debugFP, NULL);
2560 shuffleOpenings = 0; /* [HGM] shuffle */
2561 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2565 newWidth = 9; newHeight = 9;
2566 gameInfo.holdingsSize = 7;
2567 case VariantBughouse:
2568 case VariantCrazyhouse:
2569 newHoldingsWidth = 2; break;
2573 newHoldingsWidth = 2;
2574 gameInfo.holdingsSize = 8;
2577 case VariantCapablanca:
2578 case VariantCapaRandom:
2581 newHoldingsWidth = gameInfo.holdingsSize = 0;
2584 if(newWidth != gameInfo.boardWidth ||
2585 newHeight != gameInfo.boardHeight ||
2586 newHoldingsWidth != gameInfo.holdingsWidth ) {
2588 /* shift position to new playing area, if needed */
2589 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2590 for(i=0; i<BOARD_HEIGHT; i++)
2591 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2592 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2594 for(i=0; i<newHeight; i++) {
2595 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2596 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2598 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2599 for(i=0; i<BOARD_HEIGHT; i++)
2600 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2601 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2604 board[HOLDINGS_SET] = 0;
2605 gameInfo.boardWidth = newWidth;
2606 gameInfo.boardHeight = newHeight;
2607 gameInfo.holdingsWidth = newHoldingsWidth;
2608 gameInfo.variant = newVariant;
2609 InitDrawingSizes(-2, 0);
2610 } else gameInfo.variant = newVariant;
2611 CopyBoard(oldBoard, board); // remember correctly formatted board
2612 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2613 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2616 static int loggedOn = FALSE;
2618 /*-- Game start info cache: --*/
2620 char gs_kind[MSG_SIZ];
2621 static char player1Name[128] = "";
2622 static char player2Name[128] = "";
2623 static char cont_seq[] = "\n\\ ";
2624 static int player1Rating = -1;
2625 static int player2Rating = -1;
2626 /*----------------------------*/
2628 ColorClass curColor = ColorNormal;
2629 int suppressKibitz = 0;
2632 Boolean soughtPending = FALSE;
2633 Boolean seekGraphUp;
2634 #define MAX_SEEK_ADS 200
2636 char *seekAdList[MAX_SEEK_ADS];
2637 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2638 float tcList[MAX_SEEK_ADS];
2639 char colorList[MAX_SEEK_ADS];
2640 int nrOfSeekAds = 0;
2641 int minRating = 1010, maxRating = 2800;
2642 int hMargin = 10, vMargin = 20, h, w;
2643 extern int squareSize, lineGap;
2648 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2649 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2650 if(r < minRating+100 && r >=0 ) r = minRating+100;
2651 if(r > maxRating) r = maxRating;
2652 if(tc < 1.f) tc = 1.f;
2653 if(tc > 95.f) tc = 95.f;
2654 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2655 y = ((double)r - minRating)/(maxRating - minRating)
2656 * (h-vMargin-squareSize/8-1) + vMargin;
2657 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2658 if(strstr(seekAdList[i], " u ")) color = 1;
2659 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2660 !strstr(seekAdList[i], "bullet") &&
2661 !strstr(seekAdList[i], "blitz") &&
2662 !strstr(seekAdList[i], "standard") ) color = 2;
2663 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2664 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2668 PlotSingleSeekAd (int i)
2674 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2676 char buf[MSG_SIZ], *ext = "";
2677 VariantClass v = StringToVariant(type);
2678 if(strstr(type, "wild")) {
2679 ext = type + 4; // append wild number
2680 if(v == VariantFischeRandom) type = "chess960"; else
2681 if(v == VariantLoadable) type = "setup"; else
2682 type = VariantName(v);
2684 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2685 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2686 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2687 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2688 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2689 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2690 seekNrList[nrOfSeekAds] = nr;
2691 zList[nrOfSeekAds] = 0;
2692 seekAdList[nrOfSeekAds++] = StrSave(buf);
2693 if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2698 EraseSeekDot (int i)
2700 int x = xList[i], y = yList[i], d=squareSize/4, k;
2701 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2702 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2703 // now replot every dot that overlapped
2704 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2705 int xx = xList[k], yy = yList[k];
2706 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2707 DrawSeekDot(xx, yy, colorList[k]);
2712 RemoveSeekAd (int nr)
2715 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2717 if(seekAdList[i]) free(seekAdList[i]);
2718 seekAdList[i] = seekAdList[--nrOfSeekAds];
2719 seekNrList[i] = seekNrList[nrOfSeekAds];
2720 ratingList[i] = ratingList[nrOfSeekAds];
2721 colorList[i] = colorList[nrOfSeekAds];
2722 tcList[i] = tcList[nrOfSeekAds];
2723 xList[i] = xList[nrOfSeekAds];
2724 yList[i] = yList[nrOfSeekAds];
2725 zList[i] = zList[nrOfSeekAds];
2726 seekAdList[nrOfSeekAds] = NULL;
2732 MatchSoughtLine (char *line)
2734 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2735 int nr, base, inc, u=0; char dummy;
2737 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2738 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2740 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2741 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2742 // match: compact and save the line
2743 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2753 if(!seekGraphUp) return FALSE;
2754 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap + 2*border;
2755 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap + 2*border;
2757 DrawSeekBackground(0, 0, w, h);
2758 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2759 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2760 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2761 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2763 DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2766 snprintf(buf, MSG_SIZ, "%d", i);
2767 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2770 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2771 for(i=1; i<100; i+=(i<10?1:5)) {
2772 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2773 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2774 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2776 snprintf(buf, MSG_SIZ, "%d", i);
2777 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2780 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2785 SeekGraphClick (ClickType click, int x, int y, int moving)
2787 static int lastDown = 0, displayed = 0, lastSecond;
2788 if(y < 0) return FALSE;
2789 if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2790 (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2791 if(!seekGraphUp) return FALSE;
2792 seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2793 DrawPosition(TRUE, NULL);
2796 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2797 if(click == Release || moving) return FALSE;
2799 soughtPending = TRUE;
2800 SendToICS(ics_prefix);
2801 SendToICS("sought\n"); // should this be "sought all"?
2802 } else { // issue challenge based on clicked ad
2803 int dist = 10000; int i, closest = 0, second = 0;
2804 for(i=0; i<nrOfSeekAds; i++) {
2805 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2806 if(d < dist) { dist = d; closest = i; }
2807 second += (d - zList[i] < 120); // count in-range ads
2808 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2812 second = (second > 1);
2813 if(displayed != closest || second != lastSecond) {
2814 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2815 lastSecond = second; displayed = closest;
2817 if(click == Press) {
2818 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2821 } // on press 'hit', only show info
2822 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2823 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2824 SendToICS(ics_prefix);
2826 return TRUE; // let incoming board of started game pop down the graph
2827 } else if(click == Release) { // release 'miss' is ignored
2828 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2829 if(moving == 2) { // right up-click
2830 nrOfSeekAds = 0; // refresh graph
2831 soughtPending = TRUE;
2832 SendToICS(ics_prefix);
2833 SendToICS("sought\n"); // should this be "sought all"?
2836 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2837 // press miss or release hit 'pop down' seek graph
2838 seekGraphUp = FALSE;
2839 DrawPosition(TRUE, NULL);
2845 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2847 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2848 #define STARTED_NONE 0
2849 #define STARTED_MOVES 1
2850 #define STARTED_BOARD 2
2851 #define STARTED_OBSERVE 3
2852 #define STARTED_HOLDINGS 4
2853 #define STARTED_CHATTER 5
2854 #define STARTED_COMMENT 6
2855 #define STARTED_MOVES_NOHIDE 7
2857 static int started = STARTED_NONE;
2858 static char parse[20000];
2859 static int parse_pos = 0;
2860 static char buf[BUF_SIZE + 1];
2861 static int firstTime = TRUE, intfSet = FALSE;
2862 static ColorClass prevColor = ColorNormal;
2863 static int savingComment = FALSE;
2864 static int cmatch = 0; // continuation sequence match
2871 int backup; /* [DM] For zippy color lines */
2873 char talker[MSG_SIZ]; // [HGM] chat
2874 int channel, collective=0;
2876 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2878 if (appData.debugMode) {
2880 fprintf(debugFP, "<ICS: ");
2881 show_bytes(debugFP, data, count);
2882 fprintf(debugFP, "\n");
2886 if (appData.debugMode) { int f = forwardMostMove;
2887 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2888 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2889 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2892 /* If last read ended with a partial line that we couldn't parse,
2893 prepend it to the new read and try again. */
2894 if (leftover_len > 0) {
2895 for (i=0; i<leftover_len; i++)
2896 buf[i] = buf[leftover_start + i];
2899 /* copy new characters into the buffer */
2900 bp = buf + leftover_len;
2901 buf_len=leftover_len;
2902 for (i=0; i<count; i++)
2905 if (data[i] == '\r')
2908 // join lines split by ICS?
2909 if (!appData.noJoin)
2912 Joining just consists of finding matches against the
2913 continuation sequence, and discarding that sequence
2914 if found instead of copying it. So, until a match
2915 fails, there's nothing to do since it might be the
2916 complete sequence, and thus, something we don't want
2919 if (data[i] == cont_seq[cmatch])
2922 if (cmatch == strlen(cont_seq))
2924 cmatch = 0; // complete match. just reset the counter
2927 it's possible for the ICS to not include the space
2928 at the end of the last word, making our [correct]
2929 join operation fuse two separate words. the server
2930 does this when the space occurs at the width setting.
2932 if (!buf_len || buf[buf_len-1] != ' ')
2943 match failed, so we have to copy what matched before
2944 falling through and copying this character. In reality,
2945 this will only ever be just the newline character, but
2946 it doesn't hurt to be precise.
2948 strncpy(bp, cont_seq, cmatch);
2960 buf[buf_len] = NULLCHAR;
2961 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2966 while (i < buf_len) {
2967 /* Deal with part of the TELNET option negotiation
2968 protocol. We refuse to do anything beyond the
2969 defaults, except that we allow the WILL ECHO option,
2970 which ICS uses to turn off password echoing when we are
2971 directly connected to it. We reject this option
2972 if localLineEditing mode is on (always on in xboard)
2973 and we are talking to port 23, which might be a real
2974 telnet server that will try to keep WILL ECHO on permanently.
2976 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2977 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2978 unsigned char option;
2980 switch ((unsigned char) buf[++i]) {
2982 if (appData.debugMode)
2983 fprintf(debugFP, "\n<WILL ");
2984 switch (option = (unsigned char) buf[++i]) {
2986 if (appData.debugMode)
2987 fprintf(debugFP, "ECHO ");
2988 /* Reply only if this is a change, according
2989 to the protocol rules. */
2990 if (remoteEchoOption) break;
2991 if (appData.localLineEditing &&
2992 atoi(appData.icsPort) == TN_PORT) {
2993 TelnetRequest(TN_DONT, TN_ECHO);
2996 TelnetRequest(TN_DO, TN_ECHO);
2997 remoteEchoOption = TRUE;
3001 if (appData.debugMode)
3002 fprintf(debugFP, "%d ", option);
3003 /* Whatever this is, we don't want it. */
3004 TelnetRequest(TN_DONT, option);
3009 if (appData.debugMode)
3010 fprintf(debugFP, "\n<WONT ");
3011 switch (option = (unsigned char) buf[++i]) {
3013 if (appData.debugMode)
3014 fprintf(debugFP, "ECHO ");
3015 /* Reply only if this is a change, according
3016 to the protocol rules. */
3017 if (!remoteEchoOption) break;
3019 TelnetRequest(TN_DONT, TN_ECHO);
3020 remoteEchoOption = FALSE;
3023 if (appData.debugMode)
3024 fprintf(debugFP, "%d ", (unsigned char) option);
3025 /* Whatever this is, it must already be turned
3026 off, because we never agree to turn on
3027 anything non-default, so according to the
3028 protocol rules, we don't reply. */
3033 if (appData.debugMode)
3034 fprintf(debugFP, "\n<DO ");
3035 switch (option = (unsigned char) buf[++i]) {
3037 /* Whatever this is, we refuse to do it. */
3038 if (appData.debugMode)
3039 fprintf(debugFP, "%d ", option);
3040 TelnetRequest(TN_WONT, option);
3045 if (appData.debugMode)
3046 fprintf(debugFP, "\n<DONT ");
3047 switch (option = (unsigned char) buf[++i]) {
3049 if (appData.debugMode)
3050 fprintf(debugFP, "%d ", option);
3051 /* Whatever this is, we are already not doing
3052 it, because we never agree to do anything
3053 non-default, so according to the protocol
3054 rules, we don't reply. */
3059 if (appData.debugMode)
3060 fprintf(debugFP, "\n<IAC ");
3061 /* Doubled IAC; pass it through */
3065 if (appData.debugMode)
3066 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
3067 /* Drop all other telnet commands on the floor */
3070 if (oldi > next_out)
3071 SendToPlayer(&buf[next_out], oldi - next_out);
3077 /* OK, this at least will *usually* work */
3078 if (!loggedOn && looking_at(buf, &i, "ics%")) {
3082 if (loggedOn && !intfSet) {
3083 if (ics_type == ICS_ICC) {
3084 snprintf(str, MSG_SIZ,
3085 "/set-quietly interface %s\n/set-quietly style 12\n",
3087 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3088 strcat(str, "/set-2 51 1\n/set seek 1\n");
3089 } else if (ics_type == ICS_CHESSNET) {
3090 snprintf(str, MSG_SIZ, "/style 12\n");
3092 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
3093 strcat(str, programVersion);
3094 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
3095 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3096 strcat(str, "$iset seekremove 1\n$set seek 1\n");
3098 strcat(str, "$iset nohighlight 1\n");
3100 strcat(str, "$iset lock 1\n$style 12\n");
3103 NotifyFrontendLogin();
3107 if (started == STARTED_COMMENT) {
3108 /* Accumulate characters in comment */
3109 parse[parse_pos++] = buf[i];
3110 if (buf[i] == '\n') {
3111 parse[parse_pos] = NULLCHAR;
3112 if(chattingPartner>=0) {
3114 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
3115 OutputChatMessage(chattingPartner, mess);
3116 if(collective == 1) { // broadcasted talk also goes to private chatbox of talker
3118 talker[strlen(talker+1)-1] = NULLCHAR; // strip closing delimiter
3119 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3120 snprintf(mess, MSG_SIZ, "%s: %s", chatPartner[chattingPartner], parse);
3121 OutputChatMessage(p, mess);
3125 chattingPartner = -1;
3126 if(collective != 3) next_out = i+1; // [HGM] suppress printing in ICS window
3129 if(!suppressKibitz) // [HGM] kibitz
3130 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
3131 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
3132 int nrDigit = 0, nrAlph = 0, j;
3133 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
3134 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
3135 parse[parse_pos] = NULLCHAR;
3136 // try to be smart: if it does not look like search info, it should go to
3137 // ICS interaction window after all, not to engine-output window.
3138 for(j=0; j<parse_pos; j++) { // count letters and digits
3139 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3140 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
3141 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
3143 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3144 int depth=0; float score;
3145 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3146 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3147 pvInfoList[forwardMostMove-1].depth = depth;
3148 pvInfoList[forwardMostMove-1].score = 100*score;
3150 OutputKibitz(suppressKibitz, parse);
3153 if(gameMode == IcsObserving) // restore original ICS messages
3154 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3155 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3157 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3158 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3159 SendToPlayer(tmp, strlen(tmp));
3161 next_out = i+1; // [HGM] suppress printing in ICS window
3163 started = STARTED_NONE;
3165 /* Don't match patterns against characters in comment */
3170 if (started == STARTED_CHATTER) {
3171 if (buf[i] != '\n') {
3172 /* Don't match patterns against characters in chatter */
3176 started = STARTED_NONE;
3177 if(suppressKibitz) next_out = i+1;
3180 /* Kludge to deal with rcmd protocol */
3181 if (firstTime && looking_at(buf, &i, "\001*")) {
3182 DisplayFatalError(&buf[1], 0, 1);
3188 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3191 if (appData.debugMode)
3192 fprintf(debugFP, "ics_type %d\n", ics_type);
3195 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3196 ics_type = ICS_FICS;
3198 if (appData.debugMode)
3199 fprintf(debugFP, "ics_type %d\n", ics_type);
3202 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3203 ics_type = ICS_CHESSNET;
3205 if (appData.debugMode)
3206 fprintf(debugFP, "ics_type %d\n", ics_type);
3211 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3212 looking_at(buf, &i, "Logging you in as \"*\"") ||
3213 looking_at(buf, &i, "will be \"*\""))) {
3214 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3218 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3220 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3221 DisplayIcsInteractionTitle(buf);
3222 have_set_title = TRUE;
3225 /* skip finger notes */
3226 if (started == STARTED_NONE &&
3227 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3228 (buf[i] == '1' && buf[i+1] == '0')) &&
3229 buf[i+2] == ':' && buf[i+3] == ' ') {
3230 started = STARTED_CHATTER;
3236 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3237 if(appData.seekGraph) {
3238 if(soughtPending && MatchSoughtLine(buf+i)) {
3239 i = strstr(buf+i, "rated") - buf;
3240 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3241 next_out = leftover_start = i;
3242 started = STARTED_CHATTER;
3243 suppressKibitz = TRUE;
3246 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3247 && looking_at(buf, &i, "* ads displayed")) {
3248 soughtPending = FALSE;
3253 if(appData.autoRefresh) {
3254 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3255 int s = (ics_type == ICS_ICC); // ICC format differs
3257 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3258 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3259 looking_at(buf, &i, "*% "); // eat prompt
3260 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3261 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3262 next_out = i; // suppress
3265 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3266 char *p = star_match[0];
3268 if(seekGraphUp) RemoveSeekAd(atoi(p));
3269 while(*p && *p++ != ' '); // next
3271 looking_at(buf, &i, "*% "); // eat prompt
3272 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3279 /* skip formula vars */
3280 if (started == STARTED_NONE &&
3281 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3282 started = STARTED_CHATTER;
3287 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3288 if (appData.autoKibitz && started == STARTED_NONE &&
3289 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3290 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3291 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3292 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3293 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3294 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3295 suppressKibitz = TRUE;
3296 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3298 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3299 && (gameMode == IcsPlayingWhite)) ||
3300 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3301 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3302 started = STARTED_CHATTER; // own kibitz we simply discard
3304 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3305 parse_pos = 0; parse[0] = NULLCHAR;
3306 savingComment = TRUE;
3307 suppressKibitz = gameMode != IcsObserving ? 2 :
3308 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3312 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3313 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3314 && atoi(star_match[0])) {
3315 // suppress the acknowledgements of our own autoKibitz
3317 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3318 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3319 SendToPlayer(star_match[0], strlen(star_match[0]));
3320 if(looking_at(buf, &i, "*% ")) // eat prompt
3321 suppressKibitz = FALSE;
3325 } // [HGM] kibitz: end of patch
3327 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3329 // [HGM] chat: intercept tells by users for which we have an open chat window
3331 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3332 looking_at(buf, &i, "* whispers:") ||
3333 looking_at(buf, &i, "* kibitzes:") ||
3334 looking_at(buf, &i, "* shouts:") ||
3335 looking_at(buf, &i, "* c-shouts:") ||
3336 looking_at(buf, &i, "--> * ") ||
3337 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3338 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3339 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3340 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3342 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3343 chattingPartner = -1; collective = 0;
3345 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3346 for(p=0; p<MAX_CHAT; p++) {
3348 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3349 talker[0] = '['; strcat(talker, "] ");
3350 Colorize((channel == 1 ? ColorChannel1 : ColorChannel), FALSE);
3351 chattingPartner = p; break;
3354 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3355 for(p=0; p<MAX_CHAT; p++) {
3357 if(!strcmp("kibitzes", chatPartner[p])) {
3358 talker[0] = '['; strcat(talker, "] ");
3359 chattingPartner = p; break;
3362 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3363 for(p=0; p<MAX_CHAT; p++) {
3365 if(!strcmp("whispers", chatPartner[p])) {
3366 talker[0] = '['; strcat(talker, "] ");
3367 chattingPartner = p; break;
3370 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3371 if(buf[i-8] == '-' && buf[i-3] == 't')
3372 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3374 if(!strcmp("c-shouts", chatPartner[p])) {
3375 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3376 chattingPartner = p; break;
3379 if(chattingPartner < 0)
3380 for(p=0; p<MAX_CHAT; p++) {
3382 if(!strcmp("shouts", chatPartner[p])) {
3383 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3384 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3385 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3386 chattingPartner = p; break;
3390 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3391 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3393 Colorize(ColorTell, FALSE);
3394 if(collective) safeStrCpy(talker, "broadcasts: ", MSG_SIZ);
3396 chattingPartner = p; break;
3398 if(chattingPartner<0) i = oldi, safeStrCpy(lastTalker, talker+1, MSG_SIZ); else {
3399 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3400 started = STARTED_COMMENT;
3401 parse_pos = 0; parse[0] = NULLCHAR;
3402 savingComment = 3 + chattingPartner; // counts as TRUE
3403 if(collective == 3) i = oldi; else {
3404 suppressKibitz = TRUE;
3405 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3406 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3410 } // [HGM] chat: end of patch
3413 if (appData.zippyTalk || appData.zippyPlay) {
3414 /* [DM] Backup address for color zippy lines */
3416 if (loggedOn == TRUE)
3417 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3418 (appData.zippyPlay && ZippyMatch(buf, &backup)))
3421 } // [DM] 'else { ' deleted
3423 /* Regular tells and says */
3424 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3425 looking_at(buf, &i, "* (your partner) tells you: ") ||
3426 looking_at(buf, &i, "* says: ") ||
3427 /* Don't color "message" or "messages" output */
3428 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3429 looking_at(buf, &i, "*. * at *:*: ") ||
3430 looking_at(buf, &i, "--* (*:*): ") ||
3431 /* Message notifications (same color as tells) */
3432 looking_at(buf, &i, "* has left a message ") ||
3433 looking_at(buf, &i, "* just sent you a message:\n") ||
3434 /* Whispers and kibitzes */
3435 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3436 looking_at(buf, &i, "* kibitzes: ") ||
3438 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3440 if (tkind == 1 && strchr(star_match[0], ':')) {
3441 /* Avoid "tells you:" spoofs in channels */
3444 if (star_match[0][0] == NULLCHAR ||
3445 strchr(star_match[0], ' ') ||
3446 (tkind == 3 && strchr(star_match[1], ' '))) {
3447 /* Reject bogus matches */
3450 if (appData.colorize) {
3451 if (oldi > next_out) {
3452 SendToPlayer(&buf[next_out], oldi - next_out);
3457 Colorize(ColorTell, FALSE);
3458 curColor = ColorTell;
3461 Colorize(ColorKibitz, FALSE);
3462 curColor = ColorKibitz;
3465 p = strrchr(star_match[1], '(');
3472 Colorize(ColorChannel1, FALSE);
3473 curColor = ColorChannel1;
3475 Colorize(ColorChannel, FALSE);
3476 curColor = ColorChannel;
3480 curColor = ColorNormal;
3484 if (started == STARTED_NONE && appData.autoComment &&
3485 (gameMode == IcsObserving ||
3486 gameMode == IcsPlayingWhite ||
3487 gameMode == IcsPlayingBlack)) {
3488 parse_pos = i - oldi;
3489 memcpy(parse, &buf[oldi], parse_pos);
3490 parse[parse_pos] = NULLCHAR;
3491 started = STARTED_COMMENT;
3492 savingComment = TRUE;
3493 } else if(collective != 3) {
3494 started = STARTED_CHATTER;
3495 savingComment = FALSE;
3502 if (looking_at(buf, &i, "* s-shouts: ") ||
3503 looking_at(buf, &i, "* c-shouts: ")) {
3504 if (appData.colorize) {
3505 if (oldi > next_out) {
3506 SendToPlayer(&buf[next_out], oldi - next_out);
3509 Colorize(ColorSShout, FALSE);
3510 curColor = ColorSShout;
3513 started = STARTED_CHATTER;
3517 if (looking_at(buf, &i, "--->")) {
3522 if (looking_at(buf, &i, "* shouts: ") ||
3523 looking_at(buf, &i, "--> ")) {
3524 if (appData.colorize) {
3525 if (oldi > next_out) {
3526 SendToPlayer(&buf[next_out], oldi - next_out);
3529 Colorize(ColorShout, FALSE);
3530 curColor = ColorShout;
3533 started = STARTED_CHATTER;
3537 if (looking_at( buf, &i, "Challenge:")) {
3538 if (appData.colorize) {
3539 if (oldi > next_out) {
3540 SendToPlayer(&buf[next_out], oldi - next_out);
3543 Colorize(ColorChallenge, FALSE);
3544 curColor = ColorChallenge;
3550 if (looking_at(buf, &i, "* offers you") ||
3551 looking_at(buf, &i, "* offers to be") ||
3552 looking_at(buf, &i, "* would like to") ||
3553 looking_at(buf, &i, "* requests to") ||
3554 looking_at(buf, &i, "Your opponent offers") ||
3555 looking_at(buf, &i, "Your opponent requests")) {
3557 if (appData.colorize) {
3558 if (oldi > next_out) {
3559 SendToPlayer(&buf[next_out], oldi - next_out);
3562 Colorize(ColorRequest, FALSE);
3563 curColor = ColorRequest;
3568 if (looking_at(buf, &i, "* (*) seeking")) {
3569 if (appData.colorize) {
3570 if (oldi > next_out) {
3571 SendToPlayer(&buf[next_out], oldi - next_out);
3574 Colorize(ColorSeek, FALSE);
3575 curColor = ColorSeek;
3580 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3582 if (looking_at(buf, &i, "\\ ")) {
3583 if (prevColor != ColorNormal) {
3584 if (oldi > next_out) {
3585 SendToPlayer(&buf[next_out], oldi - next_out);
3588 Colorize(prevColor, TRUE);
3589 curColor = prevColor;
3591 if (savingComment) {
3592 parse_pos = i - oldi;
3593 memcpy(parse, &buf[oldi], parse_pos);
3594 parse[parse_pos] = NULLCHAR;
3595 started = STARTED_COMMENT;
3596 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3597 chattingPartner = savingComment - 3; // kludge to remember the box
3599 started = STARTED_CHATTER;
3604 if (looking_at(buf, &i, "Black Strength :") ||
3605 looking_at(buf, &i, "<<< style 10 board >>>") ||
3606 looking_at(buf, &i, "<10>") ||
3607 looking_at(buf, &i, "#@#")) {
3608 /* Wrong board style */
3610 SendToICS(ics_prefix);
3611 SendToICS("set style 12\n");
3612 SendToICS(ics_prefix);
3613 SendToICS("refresh\n");
3617 if (looking_at(buf, &i, "login:")) {
3618 if (!have_sent_ICS_logon) {
3620 have_sent_ICS_logon = 1;
3621 else // no init script was found
3622 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3623 } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3624 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3629 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3630 (looking_at(buf, &i, "\n<12> ") ||
3631 looking_at(buf, &i, "<12> "))) {
3633 if (oldi > next_out) {
3634 SendToPlayer(&buf[next_out], oldi - next_out);
3637 started = STARTED_BOARD;
3642 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3643 looking_at(buf, &i, "<b1> ")) {
3644 if (oldi > next_out) {
3645 SendToPlayer(&buf[next_out], oldi - next_out);
3648 started = STARTED_HOLDINGS;
3653 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3655 /* Header for a move list -- first line */
3657 switch (ics_getting_history) {
3661 case BeginningOfGame:
3662 /* User typed "moves" or "oldmoves" while we
3663 were idle. Pretend we asked for these
3664 moves and soak them up so user can step
3665 through them and/or save them.
3668 gameMode = IcsObserving;
3671 ics_getting_history = H_GOT_UNREQ_HEADER;
3673 case EditGame: /*?*/
3674 case EditPosition: /*?*/
3675 /* Should above feature work in these modes too? */
3676 /* For now it doesn't */
3677 ics_getting_history = H_GOT_UNWANTED_HEADER;
3680 ics_getting_history = H_GOT_UNWANTED_HEADER;
3685 /* Is this the right one? */
3686 if (gameInfo.white && gameInfo.black &&
3687 strcmp(gameInfo.white, star_match[0]) == 0 &&
3688 strcmp(gameInfo.black, star_match[2]) == 0) {
3690 ics_getting_history = H_GOT_REQ_HEADER;
3693 case H_GOT_REQ_HEADER:
3694 case H_GOT_UNREQ_HEADER:
3695 case H_GOT_UNWANTED_HEADER:
3696 case H_GETTING_MOVES:
3697 /* Should not happen */
3698 DisplayError(_("Error gathering move list: two headers"), 0);
3699 ics_getting_history = H_FALSE;
3703 /* Save player ratings into gameInfo if needed */
3704 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3705 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3706 (gameInfo.whiteRating == -1 ||
3707 gameInfo.blackRating == -1)) {
3709 gameInfo.whiteRating = string_to_rating(star_match[1]);
3710 gameInfo.blackRating = string_to_rating(star_match[3]);
3711 if (appData.debugMode)
3712 fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3713 gameInfo.whiteRating, gameInfo.blackRating);
3718 if (looking_at(buf, &i,
3719 "* * match, initial time: * minute*, increment: * second")) {
3720 /* Header for a move list -- second line */
3721 /* Initial board will follow if this is a wild game */
3722 if (gameInfo.event != NULL) free(gameInfo.event);
3723 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3724 gameInfo.event = StrSave(str);
3725 /* [HGM] we switched variant. Translate boards if needed. */
3726 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3730 if (looking_at(buf, &i, "Move ")) {
3731 /* Beginning of a move list */
3732 switch (ics_getting_history) {
3734 /* Normally should not happen */
3735 /* Maybe user hit reset while we were parsing */
3738 /* Happens if we are ignoring a move list that is not
3739 * the one we just requested. Common if the user
3740 * tries to observe two games without turning off
3743 case H_GETTING_MOVES:
3744 /* Should not happen */
3745 DisplayError(_("Error gathering move list: nested"), 0);
3746 ics_getting_history = H_FALSE;
3748 case H_GOT_REQ_HEADER:
3749 ics_getting_history = H_GETTING_MOVES;
3750 started = STARTED_MOVES;
3752 if (oldi > next_out) {
3753 SendToPlayer(&buf[next_out], oldi - next_out);
3756 case H_GOT_UNREQ_HEADER:
3757 ics_getting_history = H_GETTING_MOVES;
3758 started = STARTED_MOVES_NOHIDE;
3761 case H_GOT_UNWANTED_HEADER:
3762 ics_getting_history = H_FALSE;
3768 if (looking_at(buf, &i, "% ") ||
3769 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3770 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3771 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3772 soughtPending = FALSE;
3776 if(suppressKibitz) next_out = i;
3777 savingComment = FALSE;
3781 case STARTED_MOVES_NOHIDE:
3782 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3783 parse[parse_pos + i - oldi] = NULLCHAR;
3784 ParseGameHistory(parse);
3786 if (appData.zippyPlay && first.initDone) {
3787 FeedMovesToProgram(&first, forwardMostMove);
3788 if (gameMode == IcsPlayingWhite) {
3789 if (WhiteOnMove(forwardMostMove)) {
3790 if (first.sendTime) {
3791 if (first.useColors) {
3792 SendToProgram("black\n", &first);
3794 SendTimeRemaining(&first, TRUE);
3796 if (first.useColors) {
3797 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3799 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3800 first.maybeThinking = TRUE;
3802 if (first.usePlayother) {
3803 if (first.sendTime) {
3804 SendTimeRemaining(&first, TRUE);
3806 SendToProgram("playother\n", &first);
3812 } else if (gameMode == IcsPlayingBlack) {
3813 if (!WhiteOnMove(forwardMostMove)) {
3814 if (first.sendTime) {
3815 if (first.useColors) {
3816 SendToProgram("white\n", &first);
3818 SendTimeRemaining(&first, FALSE);
3820 if (first.useColors) {
3821 SendToProgram("black\n", &first);
3823 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3824 first.maybeThinking = TRUE;
3826 if (first.usePlayother) {
3827 if (first.sendTime) {
3828 SendTimeRemaining(&first, FALSE);
3830 SendToProgram("playother\n", &first);
3839 if (gameMode == IcsObserving && ics_gamenum == -1) {
3840 /* Moves came from oldmoves or moves command
3841 while we weren't doing anything else.
3843 currentMove = forwardMostMove;
3844 ClearHighlights();/*!!could figure this out*/
3845 flipView = appData.flipView;
3846 DrawPosition(TRUE, boards[currentMove]);
3847 DisplayBothClocks();
3848 snprintf(str, MSG_SIZ, "%s %s %s",
3849 gameInfo.white, _("vs."), gameInfo.black);
3853 /* Moves were history of an active game */
3854 if (gameInfo.resultDetails != NULL) {
3855 free(gameInfo.resultDetails);
3856 gameInfo.resultDetails = NULL;
3859 HistorySet(parseList, backwardMostMove,
3860 forwardMostMove, currentMove-1);
3861 DisplayMove(currentMove - 1);
3862 if (started == STARTED_MOVES) next_out = i;
3863 started = STARTED_NONE;
3864 ics_getting_history = H_FALSE;
3867 case STARTED_OBSERVE:
3868 started = STARTED_NONE;
3869 SendToICS(ics_prefix);
3870 SendToICS("refresh\n");
3876 if(bookHit) { // [HGM] book: simulate book reply
3877 static char bookMove[MSG_SIZ]; // a bit generous?
3879 programStats.nodes = programStats.depth = programStats.time =
3880 programStats.score = programStats.got_only_move = 0;
3881 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3883 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3884 strcat(bookMove, bookHit);
3885 HandleMachineMove(bookMove, &first);
3890 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3891 started == STARTED_HOLDINGS ||
3892 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3893 /* Accumulate characters in move list or board */
3894 parse[parse_pos++] = buf[i];
3897 /* Start of game messages. Mostly we detect start of game
3898 when the first board image arrives. On some versions
3899 of the ICS, though, we need to do a "refresh" after starting
3900 to observe in order to get the current board right away. */
3901 if (looking_at(buf, &i, "Adding game * to observation list")) {
3902 started = STARTED_OBSERVE;
3906 /* Handle auto-observe */
3907 if (appData.autoObserve &&
3908 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3909 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3911 /* Choose the player that was highlighted, if any. */
3912 if (star_match[0][0] == '\033' ||
3913 star_match[1][0] != '\033') {
3914 player = star_match[0];
3916 player = star_match[2];
3918 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3919 ics_prefix, StripHighlightAndTitle(player));
3922 /* Save ratings from notify string */
3923 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3924 player1Rating = string_to_rating(star_match[1]);
3925 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3926 player2Rating = string_to_rating(star_match[3]);
3928 if (appData.debugMode)
3930 "Ratings from 'Game notification:' %s %d, %s %d\n",
3931 player1Name, player1Rating,
3932 player2Name, player2Rating);
3937 /* Deal with automatic examine mode after a game,
3938 and with IcsObserving -> IcsExamining transition */
3939 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3940 looking_at(buf, &i, "has made you an examiner of game *")) {
3942 int gamenum = atoi(star_match[0]);
3943 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3944 gamenum == ics_gamenum) {
3945 /* We were already playing or observing this game;
3946 no need to refetch history */
3947 gameMode = IcsExamining;
3949 pauseExamForwardMostMove = forwardMostMove;
3950 } else if (currentMove < forwardMostMove) {
3951 ForwardInner(forwardMostMove);
3954 /* I don't think this case really can happen */
3955 SendToICS(ics_prefix);
3956 SendToICS("refresh\n");
3961 /* Error messages */
3962 // if (ics_user_moved) {
3963 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3964 if (looking_at(buf, &i, "Illegal move") ||
3965 looking_at(buf, &i, "Not a legal move") ||
3966 looking_at(buf, &i, "Your king is in check") ||
3967 looking_at(buf, &i, "It isn't your turn") ||
3968 looking_at(buf, &i, "It is not your move")) {
3970 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3971 currentMove = forwardMostMove-1;
3972 DisplayMove(currentMove - 1); /* before DMError */
3973 DrawPosition(FALSE, boards[currentMove]);
3974 SwitchClocks(forwardMostMove-1); // [HGM] race
3975 DisplayBothClocks();
3977 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3983 if (looking_at(buf, &i, "still have time") ||
3984 looking_at(buf, &i, "not out of time") ||
3985 looking_at(buf, &i, "either player is out of time") ||
3986 looking_at(buf, &i, "has timeseal; checking")) {
3987 /* We must have called his flag a little too soon */
3988 whiteFlag = blackFlag = FALSE;
3992 if (looking_at(buf, &i, "added * seconds to") ||
3993 looking_at(buf, &i, "seconds were added to")) {
3994 /* Update the clocks */
3995 SendToICS(ics_prefix);
3996 SendToICS("refresh\n");
4000 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
4001 ics_clock_paused = TRUE;
4006 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
4007 ics_clock_paused = FALSE;
4012 /* Grab player ratings from the Creating: message.
4013 Note we have to check for the special case when
4014 the ICS inserts things like [white] or [black]. */
4015 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
4016 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
4018 0 player 1 name (not necessarily white)
4020 2 empty, white, or black (IGNORED)
4021 3 player 2 name (not necessarily black)
4024 The names/ratings are sorted out when the game
4025 actually starts (below).
4027 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
4028 player1Rating = string_to_rating(star_match[1]);
4029 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
4030 player2Rating = string_to_rating(star_match[4]);
4032 if (appData.debugMode)
4034 "Ratings from 'Creating:' %s %d, %s %d\n",
4035 player1Name, player1Rating,
4036 player2Name, player2Rating);
4041 /* Improved generic start/end-of-game messages */
4042 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
4043 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
4044 /* If tkind == 0: */
4045 /* star_match[0] is the game number */
4046 /* [1] is the white player's name */
4047 /* [2] is the black player's name */
4048 /* For end-of-game: */
4049 /* [3] is the reason for the game end */
4050 /* [4] is a PGN end game-token, preceded by " " */
4051 /* For start-of-game: */
4052 /* [3] begins with "Creating" or "Continuing" */
4053 /* [4] is " *" or empty (don't care). */
4054 int gamenum = atoi(star_match[0]);
4055 char *whitename, *blackname, *why, *endtoken;
4056 ChessMove endtype = EndOfFile;
4059 whitename = star_match[1];
4060 blackname = star_match[2];
4061 why = star_match[3];
4062 endtoken = star_match[4];
4064 whitename = star_match[1];
4065 blackname = star_match[3];
4066 why = star_match[5];
4067 endtoken = star_match[6];
4070 /* Game start messages */
4071 if (strncmp(why, "Creating ", 9) == 0 ||
4072 strncmp(why, "Continuing ", 11) == 0) {
4073 gs_gamenum = gamenum;
4074 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
4075 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
4076 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
4078 if (appData.zippyPlay) {
4079 ZippyGameStart(whitename, blackname);
4082 partnerBoardValid = FALSE; // [HGM] bughouse
4086 /* Game end messages */
4087 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
4088 ics_gamenum != gamenum) {
4091 while (endtoken[0] == ' ') endtoken++;
4092 switch (endtoken[0]) {
4095 endtype = GameUnfinished;
4098 endtype = BlackWins;
4101 if (endtoken[1] == '/')
4102 endtype = GameIsDrawn;
4104 endtype = WhiteWins;
4107 GameEnds(endtype, why, GE_ICS);
4109 if (appData.zippyPlay && first.initDone) {
4110 ZippyGameEnd(endtype, why);
4111 if (first.pr == NoProc) {
4112 /* Start the next process early so that we'll
4113 be ready for the next challenge */
4114 StartChessProgram(&first);
4116 /* Send "new" early, in case this command takes
4117 a long time to finish, so that we'll be ready
4118 for the next challenge. */
4119 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
4123 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
4127 if (looking_at(buf, &i, "Removing game * from observation") ||
4128 looking_at(buf, &i, "no longer observing game *") ||
4129 looking_at(buf, &i, "Game * (*) has no examiners")) {
4130 if (gameMode == IcsObserving &&
4131 atoi(star_match[0]) == ics_gamenum)
4133 /* icsEngineAnalyze */
4134 if (appData.icsEngineAnalyze) {
4141 ics_user_moved = FALSE;
4146 if (looking_at(buf, &i, "no longer examining game *")) {
4147 if (gameMode == IcsExamining &&
4148 atoi(star_match[0]) == ics_gamenum)
4152 ics_user_moved = FALSE;
4157 /* Advance leftover_start past any newlines we find,
4158 so only partial lines can get reparsed */
4159 if (looking_at(buf, &i, "\n")) {
4160 prevColor = curColor;
4161 if (curColor != ColorNormal) {
4162 if (oldi > next_out) {
4163 SendToPlayer(&buf[next_out], oldi - next_out);
4166 Colorize(ColorNormal, FALSE);
4167 curColor = ColorNormal;
4169 if (started == STARTED_BOARD) {
4170 started = STARTED_NONE;
4171 parse[parse_pos] = NULLCHAR;
4172 ParseBoard12(parse);
4175 /* Send premove here */
4176 if (appData.premove) {
4178 if (currentMove == 0 &&
4179 gameMode == IcsPlayingWhite &&
4180 appData.premoveWhite) {
4181 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4182 if (appData.debugMode)
4183 fprintf(debugFP, "Sending premove:\n");
4185 } else if (currentMove == 1 &&
4186 gameMode == IcsPlayingBlack &&
4187 appData.premoveBlack) {
4188 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4189 if (appData.debugMode)
4190 fprintf(debugFP, "Sending premove:\n");
4192 } else if (gotPremove) {
4193 int oldFMM = forwardMostMove;
4195 ClearPremoveHighlights();
4196 if (appData.debugMode)
4197 fprintf(debugFP, "Sending premove:\n");
4198 UserMoveEvent(premoveFromX, premoveFromY,
4199 premoveToX, premoveToY,
4201 if(forwardMostMove == oldFMM) { // premove was rejected, highlight last opponent move
4202 if(moveList[oldFMM-1][1] != '@')
4203 SetHighlights(moveList[oldFMM-1][0]-AAA, moveList[oldFMM-1][1]-ONE,
4204 moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
4206 SetHighlights(-1, -1, moveList[oldFMM-1][2]-AAA, moveList[oldFMM-1][3]-ONE);
4211 /* Usually suppress following prompt */
4212 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4213 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4214 if (looking_at(buf, &i, "*% ")) {
4215 savingComment = FALSE;
4220 } else if (started == STARTED_HOLDINGS) {
4222 char new_piece[MSG_SIZ];
4223 started = STARTED_NONE;
4224 parse[parse_pos] = NULLCHAR;
4225 if (appData.debugMode)
4226 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4227 parse, currentMove);
4228 if (sscanf(parse, " game %d", &gamenum) == 1) {
4229 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4230 new_piece[0] = NULLCHAR;
4231 sscanf(parse, "game %d white [%s black [%s <- %s",
4232 &gamenum, white_holding, black_holding,
4234 white_holding[strlen(white_holding)-1] = NULLCHAR;
4235 black_holding[strlen(black_holding)-1] = NULLCHAR;
4236 if (gameInfo.variant == VariantNormal) {
4237 /* [HGM] We seem to switch variant during a game!
4238 * Presumably no holdings were displayed, so we have
4239 * to move the position two files to the right to
4240 * create room for them!
4242 VariantClass newVariant;
4243 switch(gameInfo.boardWidth) { // base guess on board width
4244 case 9: newVariant = VariantShogi; break;
4245 case 10: newVariant = VariantGreat; break;
4246 default: newVariant = VariantCrazyhouse;
4247 if(strchr(white_holding, 'E') || strchr(black_holding, 'E') ||
4248 strchr(white_holding, 'H') || strchr(black_holding, 'H') )
4249 newVariant = VariantSChess;
4251 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4252 /* Get a move list just to see the header, which
4253 will tell us whether this is really bug or zh */
4254 if (ics_getting_history == H_FALSE) {
4255 ics_getting_history = H_REQUESTED;
4256 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4260 /* [HGM] copy holdings to board holdings area */
4261 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4262 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4263 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4265 if (appData.zippyPlay && first.initDone) {
4266 ZippyHoldings(white_holding, black_holding,
4270 if (tinyLayout || smallLayout) {
4271 char wh[16], bh[16];
4272 PackHolding(wh, white_holding);
4273 PackHolding(bh, black_holding);
4274 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4275 gameInfo.white, gameInfo.black);
4277 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4278 gameInfo.white, white_holding, _("vs."),
4279 gameInfo.black, black_holding);
4281 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4282 DrawPosition(FALSE, boards[currentMove]);
4284 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4285 sscanf(parse, "game %d white [%s black [%s <- %s",
4286 &gamenum, white_holding, black_holding,
4288 white_holding[strlen(white_holding)-1] = NULLCHAR;
4289 black_holding[strlen(black_holding)-1] = NULLCHAR;
4290 /* [HGM] copy holdings to partner-board holdings area */
4291 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4292 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4293 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4294 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4295 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4298 /* Suppress following prompt */
4299 if (looking_at(buf, &i, "*% ")) {
4300 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4301 savingComment = FALSE;
4309 i++; /* skip unparsed character and loop back */
4312 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4313 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4314 // SendToPlayer(&buf[next_out], i - next_out);
4315 started != STARTED_HOLDINGS && leftover_start > next_out) {
4316 SendToPlayer(&buf[next_out], leftover_start - next_out);
4320 leftover_len = buf_len - leftover_start;
4321 /* if buffer ends with something we couldn't parse,
4322 reparse it after appending the next read */
4324 } else if (count == 0) {
4325 RemoveInputSource(isr);
4326 DisplayFatalError(_("Connection closed by ICS"), 0, 6666);
4328 DisplayFatalError(_("Error reading from ICS"), error, 1);
4333 /* Board style 12 looks like this:
4335 <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
4337 * The "<12> " is stripped before it gets to this routine. The two
4338 * trailing 0's (flip state and clock ticking) are later addition, and
4339 * some chess servers may not have them, or may have only the first.
4340 * Additional trailing fields may be added in the future.
4343 #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"
4345 #define RELATION_OBSERVING_PLAYED 0
4346 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4347 #define RELATION_PLAYING_MYMOVE 1
4348 #define RELATION_PLAYING_NOTMYMOVE -1
4349 #define RELATION_EXAMINING 2
4350 #define RELATION_ISOLATED_BOARD -3
4351 #define RELATION_STARTING_POSITION -4 /* FICS only */
4354 ParseBoard12 (char *string)
4358 char *bookHit = NULL; // [HGM] book
4360 GameMode newGameMode;
4361 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4362 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4363 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4364 char to_play, board_chars[200];
4365 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4366 char black[32], white[32];
4368 int prevMove = currentMove;
4371 int fromX, fromY, toX, toY;
4373 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4374 Boolean weird = FALSE, reqFlag = FALSE;
4376 fromX = fromY = toX = toY = -1;
4380 if (appData.debugMode)
4381 fprintf(debugFP, "Parsing board: %s\n", string);
4383 move_str[0] = NULLCHAR;
4384 elapsed_time[0] = NULLCHAR;
4385 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4387 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4388 if(string[i] == ' ') { ranks++; files = 0; }
4390 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4393 for(j = 0; j <i; j++) board_chars[j] = string[j];
4394 board_chars[i] = '\0';
4397 n = sscanf(string, PATTERN, &to_play, &double_push,
4398 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4399 &gamenum, white, black, &relation, &basetime, &increment,
4400 &white_stren, &black_stren, &white_time, &black_time,
4401 &moveNum, str, elapsed_time, move_str, &ics_flip,
4405 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4406 DisplayError(str, 0);
4410 /* Convert the move number to internal form */
4411 moveNum = (moveNum - 1) * 2;
4412 if (to_play == 'B') moveNum++;
4413 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4414 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4420 case RELATION_OBSERVING_PLAYED:
4421 case RELATION_OBSERVING_STATIC:
4422 if (gamenum == -1) {
4423 /* Old ICC buglet */
4424 relation = RELATION_OBSERVING_STATIC;
4426 newGameMode = IcsObserving;
4428 case RELATION_PLAYING_MYMOVE:
4429 case RELATION_PLAYING_NOTMYMOVE:
4431 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4432 IcsPlayingWhite : IcsPlayingBlack;
4433 soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4435 case RELATION_EXAMINING:
4436 newGameMode = IcsExamining;
4438 case RELATION_ISOLATED_BOARD:
4440 /* Just display this board. If user was doing something else,
4441 we will forget about it until the next board comes. */
4442 newGameMode = IcsIdle;
4444 case RELATION_STARTING_POSITION:
4445 newGameMode = gameMode;
4449 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4450 gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4451 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4452 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4453 int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4454 static int lastBgGame = -1;
4456 for (k = 0; k < ranks; k++) {
4457 for (j = 0; j < files; j++)
4458 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4459 if(gameInfo.holdingsWidth > 1) {
4460 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4461 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4464 CopyBoard(partnerBoard, board);
4465 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4466 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4467 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4468 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4469 if(toSqr = strchr(str, '-')) {
4470 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4471 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4472 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4473 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4474 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4475 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4477 DisplayWhiteClock(white_time*fac, to_play == 'W');
4478 DisplayBlackClock(black_time*fac, to_play != 'W');
4479 activePartner = to_play;
4480 if(gamenum != lastBgGame) {
4482 snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4485 lastBgGame = gamenum;
4486 activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4487 partnerUp = 0; flipView = !flipView; } // [HGM] dual
4488 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4489 (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4490 if(!twoBoards) DisplayMessage(partnerStatus, "");
4491 partnerBoardValid = TRUE;
4495 if(appData.dualBoard && appData.bgObserve) {
4496 if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4497 SendToICS(ics_prefix), SendToICS("pobserve\n");
4498 else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4500 snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4505 /* Modify behavior for initial board display on move listing
4508 switch (ics_getting_history) {
4512 case H_GOT_REQ_HEADER:
4513 case H_GOT_UNREQ_HEADER:
4514 /* This is the initial position of the current game */
4515 gamenum = ics_gamenum;
4516 moveNum = 0; /* old ICS bug workaround */
4517 if (to_play == 'B') {
4518 startedFromSetupPosition = TRUE;
4519 blackPlaysFirst = TRUE;
4521 if (forwardMostMove == 0) forwardMostMove = 1;
4522 if (backwardMostMove == 0) backwardMostMove = 1;
4523 if (currentMove == 0) currentMove = 1;
4525 newGameMode = gameMode;
4526 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4528 case H_GOT_UNWANTED_HEADER:
4529 /* This is an initial board that we don't want */
4531 case H_GETTING_MOVES:
4532 /* Should not happen */
4533 DisplayError(_("Error gathering move list: extra board"), 0);
4534 ics_getting_history = H_FALSE;
4538 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4539 move_str[1] == '@' && !gameInfo.holdingsWidth ||
4540 weird && (int)gameInfo.variant < (int)VariantShogi) {
4541 /* [HGM] We seem to have switched variant unexpectedly
4542 * Try to guess new variant from board size
4544 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4545 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4546 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4547 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4548 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4549 if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4550 if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4551 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4552 /* Get a move list just to see the header, which
4553 will tell us whether this is really bug or zh */
4554 if (ics_getting_history == H_FALSE) {
4555 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4556 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4561 /* Take action if this is the first board of a new game, or of a
4562 different game than is currently being displayed. */
4563 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4564 relation == RELATION_ISOLATED_BOARD) {
4566 /* Forget the old game and get the history (if any) of the new one */
4567 if (gameMode != BeginningOfGame) {
4571 if (appData.autoRaiseBoard) BoardToTop();
4573 if (gamenum == -1) {
4574 newGameMode = IcsIdle;
4575 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4576 appData.getMoveList && !reqFlag) {
4577 /* Need to get game history */
4578 ics_getting_history = H_REQUESTED;
4579 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4583 /* Initially flip the board to have black on the bottom if playing
4584 black or if the ICS flip flag is set, but let the user change
4585 it with the Flip View button. */
4586 flipView = appData.autoFlipView ?
4587 (newGameMode == IcsPlayingBlack) || ics_flip :
4590 /* Done with values from previous mode; copy in new ones */
4591 gameMode = newGameMode;
4593 ics_gamenum = gamenum;
4594 if (gamenum == gs_gamenum) {
4595 int klen = strlen(gs_kind);
4596 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4597 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4598 gameInfo.event = StrSave(str);
4600 gameInfo.event = StrSave("ICS game");
4602 gameInfo.site = StrSave(appData.icsHost);
4603 gameInfo.date = PGNDate();
4604 gameInfo.round = StrSave("-");
4605 gameInfo.white = StrSave(white);
4606 gameInfo.black = StrSave(black);
4607 timeControl = basetime * 60 * 1000;
4609 timeIncrement = increment * 1000;
4610 movesPerSession = 0;
4611 gameInfo.timeControl = TimeControlTagValue();
4612 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4613 if (appData.debugMode) {
4614 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4615 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4616 setbuf(debugFP, NULL);
4619 gameInfo.outOfBook = NULL;
4621 /* Do we have the ratings? */
4622 if (strcmp(player1Name, white) == 0 &&
4623 strcmp(player2Name, black) == 0) {
4624 if (appData.debugMode)
4625 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4626 player1Rating, player2Rating);
4627 gameInfo.whiteRating = player1Rating;
4628 gameInfo.blackRating = player2Rating;
4629 } else if (strcmp(player2Name, white) == 0 &&
4630 strcmp(player1Name, black) == 0) {
4631 if (appData.debugMode)
4632 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4633 player2Rating, player1Rating);
4634 gameInfo.whiteRating = player2Rating;
4635 gameInfo.blackRating = player1Rating;
4637 player1Name[0] = player2Name[0] = NULLCHAR;
4639 /* Silence shouts if requested */
4640 if (appData.quietPlay &&
4641 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4642 SendToICS(ics_prefix);
4643 SendToICS("set shout 0\n");
4647 /* Deal with midgame name changes */
4649 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4650 if (gameInfo.white) free(gameInfo.white);
4651 gameInfo.white = StrSave(white);
4653 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4654 if (gameInfo.black) free(gameInfo.black);
4655 gameInfo.black = StrSave(black);
4659 /* Throw away game result if anything actually changes in examine mode */
4660 if (gameMode == IcsExamining && !newGame) {
4661 gameInfo.result = GameUnfinished;
4662 if (gameInfo.resultDetails != NULL) {
4663 free(gameInfo.resultDetails);
4664 gameInfo.resultDetails = NULL;
4668 /* In pausing && IcsExamining mode, we ignore boards coming
4669 in if they are in a different variation than we are. */
4670 if (pauseExamInvalid) return;
4671 if (pausing && gameMode == IcsExamining) {
4672 if (moveNum <= pauseExamForwardMostMove) {
4673 pauseExamInvalid = TRUE;
4674 forwardMostMove = pauseExamForwardMostMove;
4679 if (appData.debugMode) {
4680 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4682 /* Parse the board */
4683 for (k = 0; k < ranks; k++) {
4684 for (j = 0; j < files; j++)
4685 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4686 if(gameInfo.holdingsWidth > 1) {
4687 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4688 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4691 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4692 board[5][BOARD_RGHT+1] = WhiteAngel;
4693 board[6][BOARD_RGHT+1] = WhiteMarshall;
4694 board[1][0] = BlackMarshall;
4695 board[2][0] = BlackAngel;
4696 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4698 CopyBoard(boards[moveNum], board);
4699 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4701 startedFromSetupPosition =
4702 !CompareBoards(board, initialPosition);
4703 if(startedFromSetupPosition)
4704 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4707 /* [HGM] Set castling rights. Take the outermost Rooks,
4708 to make it also work for FRC opening positions. Note that board12
4709 is really defective for later FRC positions, as it has no way to
4710 indicate which Rook can castle if they are on the same side of King.
4711 For the initial position we grant rights to the outermost Rooks,
4712 and remember thos rights, and we then copy them on positions
4713 later in an FRC game. This means WB might not recognize castlings with
4714 Rooks that have moved back to their original position as illegal,
4715 but in ICS mode that is not its job anyway.
4717 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4718 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4720 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4721 if(board[0][i] == WhiteRook) j = i;
4722 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4723 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4724 if(board[0][i] == WhiteRook) j = i;
4725 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4726 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4727 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4728 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4729 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4730 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4731 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4733 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4734 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4735 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4736 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4737 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4738 if(board[BOARD_HEIGHT-1][k] == bKing)
4739 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4740 if(gameInfo.variant == VariantTwoKings) {
4741 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4742 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4743 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4746 r = boards[moveNum][CASTLING][0] = initialRights[0];
4747 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4748 r = boards[moveNum][CASTLING][1] = initialRights[1];
4749 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4750 r = boards[moveNum][CASTLING][3] = initialRights[3];
4751 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4752 r = boards[moveNum][CASTLING][4] = initialRights[4];
4753 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4754 /* wildcastle kludge: always assume King has rights */
4755 r = boards[moveNum][CASTLING][2] = initialRights[2];
4756 r = boards[moveNum][CASTLING][5] = initialRights[5];
4758 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4759 boards[moveNum][EP_STATUS] = EP_NONE;
4760 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4761 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4762 if(double_push != -1) {
4763 int dir = WhiteOnMove(moveNum) ? 1 : -1, last = BOARD_HEIGHT-1;
4764 boards[moveNum][EP_FILE] = // also set new e.p. variables
4765 boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4766 boards[moveNum][EP_RANK] = (last + 3*dir)/2;
4767 boards[moveNum][LAST_TO] = 128*(last + dir) + boards[moveNum][EP_FILE];
4768 } else boards[moveNum][EP_FILE] = boards[moveNum][EP_RANK] = 100;
4771 if (ics_getting_history == H_GOT_REQ_HEADER ||
4772 ics_getting_history == H_GOT_UNREQ_HEADER) {
4773 /* This was an initial position from a move list, not
4774 the current position */
4778 /* Update currentMove and known move number limits */
4779 newMove = newGame || moveNum > forwardMostMove;
4782 forwardMostMove = backwardMostMove = currentMove = moveNum;
4783 if (gameMode == IcsExamining && moveNum == 0) {
4784 /* Workaround for ICS limitation: we are not told the wild
4785 type when starting to examine a game. But if we ask for
4786 the move list, the move list header will tell us */
4787 ics_getting_history = H_REQUESTED;
4788 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4791 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4792 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4794 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4795 /* [HGM] applied this also to an engine that is silently watching */
4796 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4797 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4798 gameInfo.variant == currentlyInitializedVariant) {
4799 takeback = forwardMostMove - moveNum;
4800 for (i = 0; i < takeback; i++) {
4801 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4802 SendToProgram("undo\n", &first);
4807 forwardMostMove = moveNum;
4808 if (!pausing || currentMove > forwardMostMove)
4809 currentMove = forwardMostMove;
4811 /* New part of history that is not contiguous with old part */
4812 if (pausing && gameMode == IcsExamining) {
4813 pauseExamInvalid = TRUE;
4814 forwardMostMove = pauseExamForwardMostMove;
4817 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4819 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4820 // [HGM] when we will receive the move list we now request, it will be
4821 // fed to the engine from the first move on. So if the engine is not
4822 // in the initial position now, bring it there.
4823 InitChessProgram(&first, 0);
4826 ics_getting_history = H_REQUESTED;
4827 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4830 forwardMostMove = backwardMostMove = currentMove = moveNum;
4833 /* Update the clocks */
4834 if (strchr(elapsed_time, '.')) {
4836 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4837 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4839 /* Time is in seconds */
4840 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4841 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4846 if (appData.zippyPlay && newGame &&
4847 gameMode != IcsObserving && gameMode != IcsIdle &&
4848 gameMode != IcsExamining)
4849 ZippyFirstBoard(moveNum, basetime, increment);
4852 /* Put the move on the move list, first converting
4853 to canonical algebraic form. */
4855 if (appData.debugMode) {
4856 int f = forwardMostMove;
4857 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4858 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4859 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4860 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4861 fprintf(debugFP, "moveNum = %d\n", moveNum);
4862 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4863 setbuf(debugFP, NULL);
4865 if (moveNum <= backwardMostMove) {
4866 /* We don't know what the board looked like before
4868 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4869 strcat(parseList[moveNum - 1], " ");
4870 strcat(parseList[moveNum - 1], elapsed_time);
4871 moveList[moveNum - 1][0] = NULLCHAR;
4872 } else if (strcmp(move_str, "none") == 0) {
4873 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4874 /* Again, we don't know what the board looked like;
4875 this is really the start of the game. */
4876 parseList[moveNum - 1][0] = NULLCHAR;
4877 moveList[moveNum - 1][0] = NULLCHAR;
4878 backwardMostMove = moveNum;
4879 startedFromSetupPosition = TRUE;
4880 fromX = fromY = toX = toY = -1;
4882 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4883 // So we parse the long-algebraic move string in stead of the SAN move
4884 int valid; char buf[MSG_SIZ], *prom;
4886 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4887 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4888 // str looks something like "Q/a1-a2"; kill the slash
4890 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4891 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4892 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4893 strcat(buf, prom); // long move lacks promo specification!
4894 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4895 if(appData.debugMode)
4896 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4897 safeStrCpy(move_str, buf, MSG_SIZ);
4899 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4900 &fromX, &fromY, &toX, &toY, &promoChar)
4901 || ParseOneMove(buf, moveNum - 1, &moveType,
4902 &fromX, &fromY, &toX, &toY, &promoChar);
4903 // end of long SAN patch
4905 (void) CoordsToAlgebraic(boards[moveNum - 1],
4906 PosFlags(moveNum - 1),
4907 fromY, fromX, toY, toX, promoChar,
4908 parseList[moveNum-1]);
4909 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4915 if(!IS_SHOGI(gameInfo.variant))
4916 strcat(parseList[moveNum - 1], "+");
4919 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4920 strcat(parseList[moveNum - 1], "#");
4923 strcat(parseList[moveNum - 1], " ");
4924 strcat(parseList[moveNum - 1], elapsed_time);
4925 /* currentMoveString is set as a side-effect of ParseOneMove */
4926 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4927 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4928 strcat(moveList[moveNum - 1], "\n");
4930 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4931 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4932 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4933 ChessSquare old, new = boards[moveNum][k][j];
4934 if(new == EmptySquare || fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4935 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4936 if(old == new) continue;
4937 if(old == PROMOTED(new)) boards[moveNum][k][j] = old;// prevent promoted pieces to revert to primordial ones
4938 else if(new == WhiteWazir || new == BlackWazir) {
4939 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4940 boards[moveNum][k][j] = PROMOTED(old); // choose correct type of Gold in promotion
4941 else boards[moveNum][k][j] = old; // preserve type of Gold
4942 } else if(old == WhitePawn || old == BlackPawn) // Pawn promotions (but not e.p.capture!)
4943 boards[moveNum][k][j] = PROMOTED(new); // use non-primordial representation of chosen piece
4946 /* Move from ICS was illegal!? Punt. */
4947 if (appData.debugMode) {
4948 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4949 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4951 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4952 strcat(parseList[moveNum - 1], " ");
4953 strcat(parseList[moveNum - 1], elapsed_time);
4954 moveList[moveNum - 1][0] = NULLCHAR;
4955 fromX = fromY = toX = toY = -1;
4958 if (appData.debugMode) {
4959 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4960 setbuf(debugFP, NULL);
4964 /* Send move to chess program (BEFORE animating it). */
4965 if (appData.zippyPlay && !newGame && newMove &&
4966 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4968 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4969 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4970 if (moveList[moveNum - 1][0] == NULLCHAR) {
4971 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4973 DisplayError(str, 0);
4975 if (first.sendTime) {
4976 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4978 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4979 if (firstMove && !bookHit) {
4981 if (first.useColors) {
4982 SendToProgram(gameMode == IcsPlayingWhite ?
4984 "black\ngo\n", &first);
4986 SendToProgram("go\n", &first);
4988 first.maybeThinking = TRUE;
4991 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4992 if (moveList[moveNum - 1][0] == NULLCHAR) {
4993 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4994 DisplayError(str, 0);
4996 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4997 SendMoveToProgram(moveNum - 1, &first);
5004 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
5005 /* If move comes from a remote source, animate it. If it
5006 isn't remote, it will have already been animated. */
5007 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
5008 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
5010 if (!pausing && appData.highlightLastMove) {
5011 SetHighlights(fromX, fromY, toX, toY);
5015 /* Start the clocks */
5016 whiteFlag = blackFlag = FALSE;
5017 appData.clockMode = !(basetime == 0 && increment == 0);
5019 ics_clock_paused = TRUE;
5021 } else if (ticking == 1) {
5022 ics_clock_paused = FALSE;
5024 if (gameMode == IcsIdle ||
5025 relation == RELATION_OBSERVING_STATIC ||
5026 relation == RELATION_EXAMINING ||
5028 DisplayBothClocks();
5032 /* Display opponents and material strengths */
5033 if (gameInfo.variant != VariantBughouse &&
5034 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
5035 if (tinyLayout || smallLayout) {
5036 if(gameInfo.variant == VariantNormal)
5037 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
5038 gameInfo.white, white_stren, gameInfo.black, black_stren,
5039 basetime, increment);
5041 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
5042 gameInfo.white, white_stren, gameInfo.black, black_stren,
5043 basetime, increment, (int) gameInfo.variant);
5045 if(gameInfo.variant == VariantNormal)
5046 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
5047 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5048 basetime, increment);
5050 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
5051 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5052 basetime, increment, VariantName(gameInfo.variant));
5055 if (appData.debugMode) {
5056 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
5061 /* Display the board */
5062 if (!pausing && !appData.noGUI) {
5064 if (appData.premove)
5066 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
5067 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
5068 ClearPremoveHighlights();
5070 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
5071 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
5072 DrawPosition(j, boards[currentMove]);
5074 DisplayMove(moveNum - 1);
5075 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
5076 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
5077 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
5078 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
5082 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5084 if(bookHit) { // [HGM] book: simulate book reply
5085 static char bookMove[MSG_SIZ]; // a bit generous?
5087 programStats.nodes = programStats.depth = programStats.time =
5088 programStats.score = programStats.got_only_move = 0;
5089 sprintf(programStats.movelist, "%s (xbook)", bookHit);
5091 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
5092 strcat(bookMove, bookHit);
5093 HandleMachineMove(bookMove, &first);
5102 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
5103 ics_getting_history = H_REQUESTED;
5104 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
5110 SendToBoth (char *msg)
5111 { // to make it easy to keep two engines in step in dual analysis
5112 SendToProgram(msg, &first);
5113 if(second.analyzing) SendToProgram(msg, &second);
5117 AnalysisPeriodicEvent (int force)
5119 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
5120 && !force) || !appData.periodicUpdates)
5123 /* Send . command to Crafty to collect stats */
5126 /* Don't send another until we get a response (this makes
5127 us stop sending to old Crafty's which don't understand
5128 the "." command (sending illegal cmds resets node count & time,
5129 which looks bad)) */
5130 programStats.ok_to_send = 0;
5134 ics_update_width (int new_width)
5136 ics_printf("set width %d\n", new_width);
5140 SendMoveToProgram (int moveNum, ChessProgramState *cps)
5144 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
5145 if(gameInfo.variant == VariantLion || gameInfo.variant == VariantChuChess || gameInfo.variant == VariantChu) {
5146 sprintf(buf, "%s@@@@\n", cps->useUsermove ? "usermove " : "");
5147 SendToProgram(buf, cps);
5150 // null move in variant where engine does not understand it (for analysis purposes)
5151 SendBoard(cps, moveNum + 1); // send position after move in stead.
5154 if (cps->useUsermove) {
5155 SendToProgram("usermove ", cps);
5159 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
5160 int len = space - parseList[moveNum];
5161 memcpy(buf, parseList[moveNum], len);
5163 buf[len] = NULLCHAR;
5165 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
5167 SendToProgram(buf, cps);
5169 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
5170 AlphaRank(moveList[moveNum], 4);
5171 SendToProgram(moveList[moveNum], cps);
5172 AlphaRank(moveList[moveNum], 4); // and back
5174 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5175 * the engine. It would be nice to have a better way to identify castle
5177 if(appData.fischerCastling && cps->useOOCastle) {
5178 int fromX = moveList[moveNum][0] - AAA;
5179 int fromY = moveList[moveNum][1] - ONE;
5180 int toX = moveList[moveNum][2] - AAA;
5181 int toY = moveList[moveNum][3] - ONE;
5182 if((boards[moveNum][fromY][fromX] == WhiteKing
5183 && boards[moveNum][toY][toX] == WhiteRook)
5184 || (boards[moveNum][fromY][fromX] == BlackKing
5185 && boards[moveNum][toY][toX] == BlackRook)) {
5186 if(toX > fromX) SendToProgram("O-O\n", cps);
5187 else SendToProgram("O-O-O\n", cps);
5189 else SendToProgram(moveList[moveNum], cps);
5191 if(moveList[moveNum][4] == ';') { // [HGM] lion: move is double-step over intermediate square
5192 char *m = moveList[moveNum];
5194 *c = m[7]; if(*c == '\n') *c = NULLCHAR; // promoChar
5195 if((boards[moveNum][m[6]-ONE][m[5]-AAA] < BlackPawn) == (boards[moveNum][m[1]-ONE][m[0]-AAA] < BlackPawn)) // move is kludge to indicate castling
5196 snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d\n", m[0], m[1] - '0', // convert to two moves
5199 m[2] + (m[0] > m[5] ? 1 : -1), m[3] - '0');
5200 else if(*c && m[8] != '\n') { // kill square followed by 2 characters: 2nd kill square rather than promo suffix
5201 *c = m[9]; if(*c == '\n') *c = NULLCHAR;
5202 snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to three moves
5207 m[2], m[3] - '0', c);
5209 snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d%s\n", m[0], m[1] - '0', // convert to two moves
5212 m[2], m[3] - '0', c);
5213 SendToProgram(buf, cps);
5215 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5216 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5217 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5218 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5219 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5221 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5222 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5223 SendToProgram(buf, cps);
5225 else SendToProgram(moveList[moveNum], cps);
5226 /* End of additions by Tord */
5229 /* [HGM] setting up the opening has brought engine in force mode! */
5230 /* Send 'go' if we are in a mode where machine should play. */
5231 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5232 (gameMode == TwoMachinesPlay ||
5234 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
5236 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5237 SendToProgram("go\n", cps);
5238 if (appData.debugMode) {
5239 fprintf(debugFP, "(extra)\n");
5242 setboardSpoiledMachineBlack = 0;
5246 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5248 char user_move[MSG_SIZ];
5251 if(gameInfo.variant == VariantSChess && promoChar) {
5252 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5253 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5254 } else suffix[0] = NULLCHAR;
5258 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5259 (int)moveType, fromX, fromY, toX, toY);
5260 DisplayError(user_move + strlen("say "), 0);
5262 case WhiteKingSideCastle:
5263 case BlackKingSideCastle:
5264 case WhiteQueenSideCastleWild:
5265 case BlackQueenSideCastleWild:
5267 case WhiteHSideCastleFR:
5268 case BlackHSideCastleFR:
5270 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5272 case WhiteQueenSideCastle:
5273 case BlackQueenSideCastle:
5274 case WhiteKingSideCastleWild:
5275 case BlackKingSideCastleWild:
5277 case WhiteASideCastleFR:
5278 case BlackASideCastleFR:
5280 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5282 case WhiteNonPromotion:
5283 case BlackNonPromotion:
5284 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5286 case WhitePromotion:
5287 case BlackPromotion:
5288 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
5289 gameInfo.variant == VariantMakruk)
5290 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5291 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5292 PieceToChar(WhiteFerz));
5293 else if(gameInfo.variant == VariantGreat)
5294 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5295 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5296 PieceToChar(WhiteMan));
5298 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5299 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5305 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5306 ToUpper(PieceToChar((ChessSquare) fromX)),
5307 AAA + toX, ONE + toY);
5309 case IllegalMove: /* could be a variant we don't quite understand */
5310 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5312 case WhiteCapturesEnPassant:
5313 case BlackCapturesEnPassant:
5314 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5315 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5318 SendToICS(user_move);
5319 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5320 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5325 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5326 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5327 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5328 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5329 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5332 if(gameMode != IcsExamining) { // is this ever not the case?
5333 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5335 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5336 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5337 } else { // on FICS we must first go to general examine mode
5338 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5340 if(gameInfo.variant != VariantNormal) {
5341 // try figure out wild number, as xboard names are not always valid on ICS
5342 for(i=1; i<=36; i++) {
5343 snprintf(buf, MSG_SIZ, "wild/%d", i);
5344 if(StringToVariant(buf) == gameInfo.variant) break;
5346 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5347 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5348 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5349 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5350 SendToICS(ics_prefix);
5352 if(startedFromSetupPosition || backwardMostMove != 0) {
5353 fen = PositionToFEN(backwardMostMove, NULL, 1);
5354 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5355 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5357 } else { // FICS: everything has to set by separate bsetup commands
5358 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5359 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5361 if(!WhiteOnMove(backwardMostMove)) {
5362 SendToICS("bsetup tomove black\n");
5364 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5365 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5367 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5368 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5370 i = boards[backwardMostMove][EP_STATUS];
5371 if(i >= 0) { // set e.p.
5372 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5378 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5379 SendToICS("bsetup done\n"); // switch to normal examining.
5381 for(i = backwardMostMove; i<last; i++) {
5383 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5384 if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5385 int len = strlen(moveList[i]);
5386 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5387 if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5391 SendToICS(ics_prefix);
5392 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5395 int killX = -1, killY = -1, kill2X = -1, kill2Y = -1; // [HGM] lion: used for passing e.p. capture square to MakeMove
5399 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[9])
5401 if (rf == DROP_RANK) {
5402 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5403 sprintf(move, "%c@%c%c\n",
5404 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5406 if (promoChar == 'x' || promoChar == NULLCHAR) {
5407 sprintf(move, "%c%c%c%c\n",
5408 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5409 if(killX >= 0 && killY >= 0) {
5410 sprintf(move+4, ";%c%c\n", AAA + killX, ONE + killY);
5411 if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c\n", AAA + kill2X, ONE + kill2Y);
5414 sprintf(move, "%c%c%c%c%c\n",
5415 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5416 if(killX >= 0 && killY >= 0) {
5417 sprintf(move+4, ";%c%c%c\n", AAA + killX, ONE + killY, promoChar);
5418 if(kill2X >= 0 && kill2Y >= 0) sprintf(move+7, "%c%c%c\n", AAA + kill2X, ONE + kill2Y, promoChar);
5425 ProcessICSInitScript (FILE *f)
5429 while (fgets(buf, MSG_SIZ, f)) {
5430 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5437 static int lastX, lastY, lastLeftX, lastLeftY, selectFlag;
5439 static ClickType lastClickType;
5442 PieceInString (char *s, ChessSquare piece)
5444 char *p, ID = ToUpper(PieceToChar(piece)), suffix = PieceSuffix(piece);
5445 while((p = strchr(s, ID))) {
5446 if(!suffix || p[1] == suffix) return TRUE;
5453 Partner (ChessSquare *p)
5454 { // change piece into promotion partner if one shogi-promotes to the other
5455 ChessSquare partner = promoPartner[*p];
5456 if(PieceToChar(*p) != '+' && PieceToChar(partner) != '+') return 0;
5457 if(PieceToChar(*p) == '+') partner = boards[currentMove][fromY][fromX];
5465 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5466 static int toggleFlag;
5467 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5468 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5469 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5470 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5471 if(fromY != BOARD_HEIGHT-2 && fromY != 1 && gameInfo.variant != VariantChuChess) pawn = EmptySquare;
5472 if(!step) toggleFlag = Partner(&last); // piece has shogi-promotion
5474 if(step && !(toggleFlag && Partner(&promoSweep))) promoSweep -= step;
5475 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5476 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5477 else if(promoSweep == BlackPawn && step < 0 && !toggleFlag) promoSweep = WhitePawn;
5478 else if(promoSweep == WhiteKing && step > 0 && !toggleFlag) promoSweep = BlackKing;
5479 if(!step) step = -1;
5480 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' ||
5481 !toggleFlag && PieceToChar(promoSweep) == '+' || // skip promoted versions of other
5482 promoRestrict[0] ? !PieceInString(promoRestrict, promoSweep) : // if choice set available, use it
5483 promoSweep == pawn ||
5484 appData.testLegality && (promoSweep == king || gameInfo.variant != VariantChuChess &&
5485 (promoSweep == WhiteLion || promoSweep == BlackLion)));
5487 int victim = boards[currentMove][toY][toX];
5488 boards[currentMove][toY][toX] = promoSweep;
5489 DrawPosition(FALSE, boards[currentMove]);
5490 boards[currentMove][toY][toX] = victim;
5492 ChangeDragPiece(promoSweep);
5496 PromoScroll (int x, int y)
5500 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5501 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5502 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5503 if(!step) return FALSE;
5504 lastX = x; lastY = y;
5505 if((promoSweep < BlackPawn) == flipView) step = -step;
5506 if(step > 0) selectFlag = 1;
5507 if(!selectFlag) Sweep(step);
5512 NextPiece (int step)
5514 ChessSquare piece = boards[currentMove][toY][toX];
5517 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5518 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5519 if(!step) step = -1;
5520 } while(PieceToChar(pieceSweep) == '.');
5521 boards[currentMove][toY][toX] = pieceSweep;
5522 DrawPosition(FALSE, boards[currentMove]);
5523 boards[currentMove][toY][toX] = piece;
5525 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5527 AlphaRank (char *move, int n)
5529 // char *p = move, c; int x, y;
5531 if (appData.debugMode) {
5532 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5536 move[2]>='0' && move[2]<='9' &&
5537 move[3]>='a' && move[3]<='x' ) {
5539 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5540 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5542 if(move[0]>='0' && move[0]<='9' &&
5543 move[1]>='a' && move[1]<='x' &&
5544 move[2]>='0' && move[2]<='9' &&
5545 move[3]>='a' && move[3]<='x' ) {
5546 /* input move, Shogi -> normal */
5547 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5548 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5549 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5550 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5553 move[3]>='0' && move[3]<='9' &&
5554 move[2]>='a' && move[2]<='x' ) {
5556 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5557 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5560 move[0]>='a' && move[0]<='x' &&
5561 move[3]>='0' && move[3]<='9' &&
5562 move[2]>='a' && move[2]<='x' ) {
5563 /* output move, normal -> Shogi */
5564 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5565 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5566 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5567 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5568 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5570 if (appData.debugMode) {
5571 fprintf(debugFP, " out = '%s'\n", move);
5575 char yy_textstr[8000];
5577 /* Parser for moves from gnuchess, ICS, or user typein box */
5579 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5581 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5583 switch (*moveType) {
5584 case WhitePromotion:
5585 case BlackPromotion:
5586 case WhiteNonPromotion:
5587 case BlackNonPromotion:
5590 case WhiteCapturesEnPassant:
5591 case BlackCapturesEnPassant:
5592 case WhiteKingSideCastle:
5593 case WhiteQueenSideCastle:
5594 case BlackKingSideCastle:
5595 case BlackQueenSideCastle:
5596 case WhiteKingSideCastleWild:
5597 case WhiteQueenSideCastleWild:
5598 case BlackKingSideCastleWild:
5599 case BlackQueenSideCastleWild:
5600 /* Code added by Tord: */
5601 case WhiteHSideCastleFR:
5602 case WhiteASideCastleFR:
5603 case BlackHSideCastleFR:
5604 case BlackASideCastleFR:
5605 /* End of code added by Tord */
5606 case IllegalMove: /* bug or odd chess variant */
5607 if(currentMoveString[1] == '@') { // illegal drop
5608 *fromX = WhiteOnMove(moveNum) ?
5609 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5610 (int) CharToPiece(ToLower(currentMoveString[0]));
5613 *fromX = currentMoveString[0] - AAA;
5614 *fromY = currentMoveString[1] - ONE;
5615 *toX = currentMoveString[2] - AAA;
5616 *toY = currentMoveString[3] - ONE;
5617 *promoChar = currentMoveString[4];
5618 if(*promoChar == ';') *promoChar = currentMoveString[7 + 2*(currentMoveString[8] != 0)];
5619 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5620 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5621 if (appData.debugMode) {
5622 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5624 *fromX = *fromY = *toX = *toY = 0;
5627 if (appData.testLegality) {
5628 return (*moveType != IllegalMove);
5630 return !(*fromX == *toX && *fromY == *toY && killX < 0) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5631 // [HGM] lion: if this is a double move we are less critical
5632 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5637 *fromX = *moveType == WhiteDrop ?
5638 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5639 (int) CharToPiece(ToLower(currentMoveString[0]));
5642 *toX = currentMoveString[2] - AAA;
5643 *toY = currentMoveString[3] - ONE;
5644 *promoChar = NULLCHAR;
5648 case ImpossibleMove:
5658 if (appData.debugMode) {
5659 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5662 *fromX = *fromY = *toX = *toY = 0;
5663 *promoChar = NULLCHAR;
5668 Boolean pushed = FALSE;
5669 char *lastParseAttempt;
5672 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5673 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5674 int fromX, fromY, toX, toY; char promoChar;
5679 lastParseAttempt = pv; if(!*pv) return; // turns out we crash when we parse an empty PV
5680 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5681 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5684 endPV = forwardMostMove;
5686 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5687 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5688 lastParseAttempt = pv;
5689 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5690 if(!valid && nr == 0 &&
5691 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5692 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5693 // Hande case where played move is different from leading PV move
5694 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5695 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5696 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5697 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5698 endPV += 2; // if position different, keep this
5699 moveList[endPV-1][0] = fromX + AAA;
5700 moveList[endPV-1][1] = fromY + ONE;
5701 moveList[endPV-1][2] = toX + AAA;
5702 moveList[endPV-1][3] = toY + ONE;
5703 parseList[endPV-1][0] = NULLCHAR;
5704 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5707 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5708 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5709 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5710 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5711 valid++; // allow comments in PV
5715 if(endPV+1 > framePtr) break; // no space, truncate
5718 CopyBoard(boards[endPV], boards[endPV-1]);
5719 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5720 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5721 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5722 CoordsToAlgebraic(boards[endPV - 1],
5723 PosFlags(endPV - 1),
5724 fromY, fromX, toY, toX, promoChar,
5725 parseList[endPV - 1]);
5727 if(atEnd == 2) return; // used hidden, for PV conversion
5728 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5729 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5730 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5731 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5732 DrawPosition(TRUE, boards[currentMove]);
5736 MultiPV (ChessProgramState *cps, int kind)
5737 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5739 for(i=0; i<cps->nrOptions; i++) {
5740 char *s = cps->option[i].name;
5741 if((kind & 1) && !StrCaseCmp(s, "MultiPV") && cps->option[i].type == Spin) return i;
5742 if((kind & 2) && StrCaseStr(s, "multi") && StrCaseStr(s, "PV")
5743 && StrCaseStr(s, "margin") && cps->option[i].type == Spin) return -i-2;
5748 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5749 static int multi, pv_margin;
5750 static ChessProgramState *activeCps;
5753 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5755 int startPV, lineStart, origIndex = index;
5756 char *p, buf2[MSG_SIZ];
5757 ChessProgramState *cps = (pane ? &second : &first);
5759 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5760 lastX = x; lastY = y;
5761 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5762 lineStart = startPV = index;
5763 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5764 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5766 do{ while(buf[index] && buf[index] != '\n') index++;
5767 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5769 if(lineStart == 0 && gameMode == AnalyzeMode) {
5771 if(origIndex > 17 && origIndex < 24) n--; else if(origIndex > index - 6) n++;
5772 if(n == 0) { // click not on "fewer" or "more"
5773 if((multi = -2 - MultiPV(cps, 2)) >= 0) {
5774 pv_margin = cps->option[multi].value;
5775 activeCps = cps; // non-null signals margin adjustment
5777 } else if((multi = MultiPV(cps, 1)) >= 0) {
5778 n += cps->option[multi].value; if(n < 1) n = 1;
5779 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5780 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5781 cps->option[multi].value = n;
5785 } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5786 ExcludeClick(origIndex - lineStart);
5788 } else if(!strncmp(buf+lineStart, "dep\t", 4)) { // column headers clicked
5789 Collapse(origIndex - lineStart);
5792 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5793 *start = startPV; *end = index-1;
5794 extendGame = (gameMode == AnalyzeMode && appData.autoExtend && origIndex - startPV < 5);
5801 static char buf[10*MSG_SIZ];
5802 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5804 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5805 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5806 for(i = forwardMostMove; i<endPV; i++){
5807 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5808 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5811 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5812 if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5813 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5819 LoadPV (int x, int y)
5820 { // called on right mouse click to load PV
5821 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5822 lastX = x; lastY = y;
5823 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5831 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5833 if(pv_margin != activeCps->option[multi].value) {
5835 snprintf(buf, MSG_SIZ, "option %s=%d\n", "Multi-PV Margin", pv_margin);
5836 SendToProgram(buf, activeCps);
5837 activeCps->option[multi].value = pv_margin;
5842 if(endPV < 0) return;
5843 if(appData.autoCopyPV) CopyFENToClipboard();
5845 if(extendGame && currentMove > forwardMostMove) {
5846 Boolean saveAnimate = appData.animate;
5848 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5849 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5850 } else storedGames--; // abandon shelved tail of original game
5853 forwardMostMove = currentMove;
5854 currentMove = oldFMM;
5855 appData.animate = FALSE;
5856 ToNrEvent(forwardMostMove);
5857 appData.animate = saveAnimate;
5859 currentMove = forwardMostMove;
5860 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5861 ClearPremoveHighlights();
5862 DrawPosition(TRUE, boards[currentMove]);
5866 MovePV (int x, int y, int h)
5867 { // step through PV based on mouse coordinates (called on mouse move)
5868 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5870 if(activeCps) { // adjusting engine's multi-pv margin
5871 if(x > lastX) pv_margin++; else
5872 if(x < lastX) pv_margin -= (pv_margin > 0);
5875 snprintf(buf, MSG_SIZ, "margin = %d", pv_margin);
5876 DisplayMessage(buf, "");
5881 // we must somehow check if right button is still down (might be released off board!)
5882 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5883 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5884 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5886 lastX = x; lastY = y;
5888 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5889 if(endPV < 0) return;
5890 if(y < margin) step = 1; else
5891 if(y > h - margin) step = -1;
5892 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5893 currentMove += step;
5894 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5895 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5896 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5897 DrawPosition(FALSE, boards[currentMove]);
5901 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5902 // All positions will have equal probability, but the current method will not provide a unique
5903 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5909 int piecesLeft[(int)BlackPawn];
5910 int seed, nrOfShuffles;
5913 GetPositionNumber ()
5914 { // sets global variable seed
5917 seed = appData.defaultFrcPosition;
5918 if(seed < 0) { // randomize based on time for negative FRC position numbers
5919 for(i=0; i<50; i++) seed += random();
5920 seed = random() ^ random() >> 8 ^ random() << 8;
5921 if(seed<0) seed = -seed;
5926 put (Board board, int pieceType, int rank, int n, int shade)
5927 // put the piece on the (n-1)-th empty squares of the given shade
5931 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5932 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5933 board[rank][i] = (ChessSquare) pieceType;
5934 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5936 piecesLeft[pieceType]--;
5945 AddOnePiece (Board board, int pieceType, int rank, int shade)
5946 // calculate where the next piece goes, (any empty square), and put it there
5950 i = seed % squaresLeft[shade];
5951 nrOfShuffles *= squaresLeft[shade];
5952 seed /= squaresLeft[shade];
5953 put(board, pieceType, rank, i, shade);
5957 AddTwoPieces (Board board, int pieceType, int rank)
5958 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5960 int i, n=squaresLeft[ANY], j=n-1, k;
5962 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5963 i = seed % k; // pick one
5966 while(i >= j) i -= j--;
5967 j = n - 1 - j; i += j;
5968 put(board, pieceType, rank, j, ANY);
5969 put(board, pieceType, rank, i, ANY);
5973 SetUpShuffle (Board board, int number)
5977 GetPositionNumber(); nrOfShuffles = 1;
5979 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5980 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5981 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5983 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5985 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5986 p = (int) board[0][i];
5987 if(p < (int) BlackPawn) piecesLeft[p] ++;
5988 board[0][i] = EmptySquare;
5991 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5992 // shuffles restricted to allow normal castling put KRR first
5993 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5994 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5995 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5996 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5997 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5998 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5999 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
6000 put(board, WhiteRook, 0, 0, ANY);
6001 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
6004 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
6005 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
6006 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
6007 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
6008 while(piecesLeft[p] >= 2) {
6009 AddOnePiece(board, p, 0, LITE);
6010 AddOnePiece(board, p, 0, DARK);
6012 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
6015 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
6016 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
6017 // but we leave King and Rooks for last, to possibly obey FRC restriction
6018 if(p == (int)WhiteRook) continue;
6019 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
6020 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
6023 // now everything is placed, except perhaps King (Unicorn) and Rooks
6025 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
6026 // Last King gets castling rights
6027 while(piecesLeft[(int)WhiteUnicorn]) {
6028 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
6029 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
6032 while(piecesLeft[(int)WhiteKing]) {
6033 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
6034 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
6039 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
6040 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
6043 // Only Rooks can be left; simply place them all
6044 while(piecesLeft[(int)WhiteRook]) {
6045 i = put(board, WhiteRook, 0, 0, ANY);
6046 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
6049 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
6051 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
6054 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
6055 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
6058 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
6062 ptclen (const char *s, char *escapes)
6065 if(!*escapes) return strlen(s);
6066 while(*s) n += (*s != '/' && *s != '-' && *s != '^' && *s != '*' && !strchr(escapes, *s)) - 2*(*s == '='), s++;
6071 SetCharTableEsc (unsigned char *table, const char * map, char * escapes)
6072 /* [HGM] moved here from winboard.c because of its general usefulness */
6073 /* Basically a safe strcpy that uses the last character as King */
6075 int result = FALSE; int NrPieces;
6076 unsigned char partner[EmptySquare];
6078 if( map != NULL && (NrPieces=ptclen(map, escapes)) <= (int) EmptySquare
6079 && NrPieces >= 12 && !(NrPieces&1)) {
6080 int i, ii, offs, j = 0; /* [HGM] Accept even length from 12 to 88 */
6082 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
6083 for( i=offs=0; i<NrPieces/2-1; i++ ) {
6085 if(map[j] == '/') offs = WhitePBishop - i, j++;
6086 if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
6087 table[i+offs] = map[j++];
6088 if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
6089 if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
6090 if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
6092 table[(int) WhiteKing] = map[j++];
6093 for( ii=offs=0; ii<NrPieces/2-1; ii++ ) {
6095 if(map[j] == '/') offs = WhitePBishop - ii, j++;
6096 i = WHITE_TO_BLACK ii;
6097 if(*escapes && (map[j] == '*' || map[j] == '-' || map[j] == '^')) c = map[j++];
6098 table[i+offs] = map[j++];
6099 if(p = strchr(escapes, map[j])) j++, table[i+offs] += 64*(p - escapes + 1);
6100 if(c) partner[i+offs] = table[i+offs], table[i+offs] = c;
6101 if(*escapes && map[j] == '=') pieceNickName[i+offs] = map[++j], j++;
6103 table[(int) BlackKing] = map[j++];
6106 if(*escapes) { // set up promotion pairing
6107 for( i=0; i<(int) EmptySquare; i++ ) promoPartner[i] = (i%BlackPawn < 11 ? i + 11 : i%BlackPawn < 22 ? i - 11 : i); // default
6108 // pieceToChar entirely filled, so we can look up specified partners
6109 for(i=0; i<EmptySquare; i++) { // adjust promotion pairing
6111 if(c == '^' || c == '-') { // has specified partner
6113 for(p=0; p<EmptySquare; p++) if(table[p] == partner[i]) break;
6114 if(c == '^') table[i] = '+';
6115 if(p < EmptySquare) {
6116 if(promoPartner[promoPartner[p]] == p) promoPartner[promoPartner[p]] = promoPartner[p]; // divorce old partners
6117 if(promoPartner[promoPartner[i]] == i) promoPartner[promoPartner[i]] = promoPartner[i];
6118 promoPartner[p] = i, promoPartner[i] = p; // and marry this couple
6120 } else if(c == '*') {
6121 table[i] = partner[i];
6122 promoPartner[i] = (i < BlackPawn ? WhiteTokin : BlackTokin); // promotes to Tokin
6134 SetCharTable (unsigned char *table, const char * map)
6136 return SetCharTableEsc(table, map, "");
6140 Prelude (Board board)
6141 { // [HGM] superchess: random selection of exo-pieces
6142 int i, j, k; ChessSquare p;
6143 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
6145 GetPositionNumber(); // use FRC position number
6147 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
6148 SetCharTable(pieceToChar, appData.pieceToCharTable);
6149 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
6150 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
6153 j = seed%4; seed /= 4;
6154 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
6155 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
6156 board[handSize-1-k][0] = WHITE_TO_BLACK p; board[handSize-1-k][1]++;
6157 j = seed%3 + (seed%3 >= j); seed /= 3;
6158 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
6159 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
6160 board[handSize-1-k][0] = WHITE_TO_BLACK p; board[handSize-1-k][1]++;
6161 j = seed%3; seed /= 3;
6162 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
6163 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
6164 board[handSize-1-k][0] = WHITE_TO_BLACK p; board[handSize-1-k][1]++;
6165 j = seed%2 + (seed%2 >= j); seed /= 2;
6166 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
6167 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
6168 board[handSize-1-k][0] = WHITE_TO_BLACK p; board[handSize-1-k][1]++;
6169 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
6170 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
6171 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
6172 put(board, exoPieces[0], 0, 0, ANY);
6173 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
6177 InitPosition (int redraw)
6179 ChessSquare (* pieces)[BOARD_FILES];
6180 int i, j, pawnRow=1, pieceRows=1, overrule,
6181 oldx = gameInfo.boardWidth,
6182 oldy = gameInfo.boardHeight,
6183 oldh = gameInfo.holdingsWidth;
6186 if(appData.icsActive) shuffleOpenings = appData.fischerCastling = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
6188 /* [AS] Initialize pv info list [HGM] and game status */
6190 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
6191 pvInfoList[i].depth = 0;
6192 boards[i][EP_STATUS] = EP_NONE;
6193 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
6196 initialRulePlies = 0; /* 50-move counter start */
6198 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
6199 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
6203 /* [HGM] logic here is completely changed. In stead of full positions */
6204 /* the initialized data only consist of the two backranks. The switch */
6205 /* selects which one we will use, which is than copied to the Board */
6206 /* initialPosition, which for the rest is initialized by Pawns and */
6207 /* empty squares. This initial position is then copied to boards[0], */
6208 /* possibly after shuffling, so that it remains available. */
6210 gameInfo.holdingsWidth = 0; /* default board sizes */
6211 gameInfo.boardWidth = 8;
6212 gameInfo.boardHeight = 8;
6213 gameInfo.holdingsSize = 0;
6214 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
6215 for(i=0; i<BOARD_FILES-6; i++)
6216 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
6217 initialPosition[EP_STATUS] = EP_NONE;
6218 initialPosition[TOUCHED_W] = initialPosition[TOUCHED_B] = 0;
6219 SetCharTableEsc(pieceToChar, "PNBRQ...........Kpnbrq...........k", SUFFIXES);
6220 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
6221 SetCharTable(pieceNickName, appData.pieceNickNames);
6222 else SetCharTable(pieceNickName, "............");
6225 switch (gameInfo.variant) {
6226 case VariantFischeRandom:
6227 shuffleOpenings = TRUE;
6228 appData.fischerCastling = TRUE;
6231 case VariantShatranj:
6232 pieces = ShatranjArray;
6233 nrCastlingRights = 0;
6234 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
6237 pieces = makrukArray;
6238 nrCastlingRights = 0;
6239 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
6242 pieces = aseanArray;
6243 nrCastlingRights = 0;
6244 SetCharTable(pieceToChar, "PN.R.Q....BKpn.r.q....bk");
6246 case VariantTwoKings:
6247 pieces = twoKingsArray;
6250 pieces = GrandArray;
6251 nrCastlingRights = 0;
6252 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6253 gameInfo.boardWidth = 10;
6254 gameInfo.boardHeight = 10;
6255 gameInfo.holdingsSize = 7;
6257 case VariantCapaRandom:
6258 shuffleOpenings = TRUE;
6259 appData.fischerCastling = TRUE;
6260 case VariantCapablanca:
6261 pieces = CapablancaArray;
6262 gameInfo.boardWidth = 10;
6263 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6266 pieces = GothicArray;
6267 gameInfo.boardWidth = 10;
6268 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6271 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
6272 gameInfo.holdingsSize = 7;
6273 for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
6276 pieces = JanusArray;
6277 gameInfo.boardWidth = 10;
6278 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
6279 nrCastlingRights = 6;
6280 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6281 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6282 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
6283 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6284 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6285 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
6288 pieces = FalconArray;
6289 gameInfo.boardWidth = 10;
6290 SetCharTable(pieceToChar, "PNBRQ............FKpnbrq............fk");
6292 case VariantXiangqi:
6293 pieces = XiangqiArray;
6294 gameInfo.boardWidth = 9;
6295 gameInfo.boardHeight = 10;
6296 nrCastlingRights = 0;
6297 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
6300 pieces = ShogiArray;
6301 gameInfo.boardWidth = 9;
6302 gameInfo.boardHeight = 9;
6303 gameInfo.holdingsSize = 7;
6304 nrCastlingRights = 0;
6305 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
6308 pieces = ChuArray; pieceRows = 3;
6309 gameInfo.boardWidth = 12;
6310 gameInfo.boardHeight = 12;
6311 nrCastlingRights = 0;
6312 // SetCharTableEsc(pieceToChar, "P.BRQSEXOGCATHD.VMLIFN.........^T..^L......^A^H/^F^G^M.^E^X^O^I.^P.^B^R..^D^S^C^VK"
6313 // "p.brqsexogcathd.vmlifn.........^t..^l......^a^h/^f^g^m.^e^x^o^i.^p.^b^r..^d^s^c^vk", SUFFIXES);
6314 SetCharTableEsc(pieceToChar, "P.BRQSEXOG...HD..^DLI^HNV........^T..^L.C...A^AFT/^F^G^M.^E^X^O^I.^P.^B^R..M^S^C^VK"
6315 "p.brqsexog...hd..^dli^hnv........^t..^l.c...a^aft/^f^g^m.^e^x^o^i.^p.^b^r..m^s^c^vk", SUFFIXES);
6317 case VariantCourier:
6318 pieces = CourierArray;
6319 gameInfo.boardWidth = 12;
6320 nrCastlingRights = 0;
6321 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
6323 case VariantKnightmate:
6324 pieces = KnightmateArray;
6325 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
6327 case VariantSpartan:
6328 pieces = SpartanArray;
6329 SetCharTable(pieceToChar, "PNBRQ.....................K......lw......g...h......ck");
6333 SetCharTable(pieceToChar, "PNBRQ................LKpnbrq................lk");
6335 case VariantChuChess:
6336 pieces = ChuChessArray;
6337 gameInfo.boardWidth = 10;
6338 gameInfo.boardHeight = 10;
6339 SetCharTable(pieceToChar, "PNBRQ.....M.+++......LKpnbrq.....m.+++......lk");
6342 pieces = fairyArray;
6343 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
6346 pieces = GreatArray;
6347 gameInfo.boardWidth = 10;
6348 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
6349 gameInfo.holdingsSize = 8;
6353 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
6354 gameInfo.holdingsSize = 8;
6355 startedFromSetupPosition = TRUE;
6357 case VariantCrazyhouse:
6358 case VariantBughouse:
6360 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
6361 gameInfo.holdingsSize = 5;
6363 case VariantWildCastle:
6365 /* !!?shuffle with kings guaranteed to be on d or e file */
6366 shuffleOpenings = 1;
6368 case VariantNoCastle:
6369 /* !!?unconstrained back-rank shuffle */
6370 shuffleOpenings = 1;
6371 case VariantSuicide:
6373 nrCastlingRights = 0;
6378 if(appData.NrFiles >= 0) {
6379 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6380 gameInfo.boardWidth = appData.NrFiles;
6382 if(appData.NrRanks >= 0) {
6383 gameInfo.boardHeight = appData.NrRanks;
6385 if(appData.holdingsSize >= 0) {
6386 i = appData.holdingsSize;
6387 // if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6388 gameInfo.holdingsSize = i;
6390 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6391 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6392 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6394 if(!handSize) handSize = BOARD_HEIGHT;
6395 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6396 if(pawnRow < 1) pawnRow = 1;
6397 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN ||
6398 gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) pawnRow = 2;
6399 if(gameInfo.variant == VariantChu) pawnRow = 3;
6401 /* User pieceToChar list overrules defaults */
6402 if(appData.pieceToCharTable != NULL)
6403 SetCharTableEsc(pieceToChar, appData.pieceToCharTable, SUFFIXES);
6405 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6407 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6408 s = (ChessSquare) 0; /* account holding counts in guard band */
6409 for( i=0; i<BOARD_HEIGHT; i++ )
6410 initialPosition[i][j] = s;
6412 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6413 initialPosition[gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess][j] = pieces[0][j-gameInfo.holdingsWidth];
6414 initialPosition[pawnRow][j] = WhitePawn;
6415 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6416 if(gameInfo.variant == VariantXiangqi) {
6418 initialPosition[pawnRow][j] =
6419 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6420 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6421 initialPosition[2][j] = WhiteCannon;
6422 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6426 if(gameInfo.variant == VariantChu) {
6427 if(j == (BOARD_WIDTH-2)/3 || j == BOARD_WIDTH - (BOARD_WIDTH+1)/3)
6428 initialPosition[pawnRow+1][j] = WhiteCobra,
6429 initialPosition[BOARD_HEIGHT-pawnRow-2][j] = BlackCobra;
6430 for(i=1; i<pieceRows; i++) {
6431 initialPosition[i][j] = pieces[2*i][j-gameInfo.holdingsWidth];
6432 initialPosition[BOARD_HEIGHT-1-i][j] = pieces[2*i+1][j-gameInfo.holdingsWidth];
6435 if(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6436 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6437 initialPosition[0][j] = WhiteRook;
6438 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6441 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess)][j] = pieces[1][j-gameInfo.holdingsWidth];
6443 if(gameInfo.variant == VariantChuChess) initialPosition[0][BOARD_WIDTH/2] = WhiteKing, initialPosition[BOARD_HEIGHT-1][BOARD_WIDTH/2-1] = BlackKing;
6444 if( (gameInfo.variant == VariantShogi) && !overrule ) {
6447 initialPosition[1][j] = WhiteBishop;
6448 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6450 initialPosition[1][j] = WhiteRook;
6451 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6454 if( nrCastlingRights == -1) {
6455 /* [HGM] Build normal castling rights (must be done after board sizing!) */
6456 /* This sets default castling rights from none to normal corners */
6457 /* Variants with other castling rights must set them themselves above */
6458 nrCastlingRights = 6;
6460 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6461 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6462 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6463 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6464 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6465 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6468 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6469 if(gameInfo.variant == VariantGreat) { // promotion commoners
6470 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6471 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6472 initialPosition[handSize-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6473 initialPosition[handSize-1-PieceToNumber(WhiteMan)][1] = 9;
6475 if( gameInfo.variant == VariantSChess ) {
6476 initialPosition[1][0] = BlackMarshall;
6477 initialPosition[2][0] = BlackAngel;
6478 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6479 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6480 initialPosition[1][1] = initialPosition[2][1] =
6481 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6483 initialPosition[CHECK_COUNT] = (gameInfo.variant == Variant3Check ? 0x303 : 0);
6484 if (appData.debugMode) {
6485 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6487 if(shuffleOpenings) {
6488 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6489 startedFromSetupPosition = TRUE;
6491 if(startedFromPositionFile) {
6492 /* [HGM] loadPos: use PositionFile for every new game */
6493 CopyBoard(initialPosition, filePosition);
6494 for(i=0; i<nrCastlingRights; i++)
6495 initialRights[i] = filePosition[CASTLING][i];
6496 startedFromSetupPosition = TRUE;
6498 if(*appData.men) LoadPieceDesc(appData.men);
6500 CopyBoard(boards[0], initialPosition);
6502 if(oldx != gameInfo.boardWidth ||
6503 oldy != gameInfo.boardHeight ||
6504 oldv != gameInfo.variant ||
6505 oldh != gameInfo.holdingsWidth
6507 InitDrawingSizes(-2 ,0);
6509 oldv = gameInfo.variant;
6511 DrawPosition(TRUE, boards[currentMove]);
6515 SendBoard (ChessProgramState *cps, int moveNum)
6517 char message[MSG_SIZ];
6519 if (cps->useSetboard) {
6520 char* fen = PositionToFEN(moveNum, cps->fenOverride, 1);
6521 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6522 SendToProgram(message, cps);
6527 int i, j, left=0, right=BOARD_WIDTH;
6528 /* Kludge to set black to move, avoiding the troublesome and now
6529 * deprecated "black" command.
6531 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6532 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn && !pieceDesc[WhitePawn] ? "a2a3\n" : "black\nforce\n", cps);
6534 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6536 SendToProgram("edit\n", cps);
6537 SendToProgram("#\n", cps);
6538 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6539 bp = &boards[moveNum][i][left];
6540 for (j = left; j < right; j++, bp++) {
6541 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6542 if ((int) *bp < (int) BlackPawn) {
6543 if(j == BOARD_RGHT+1)
6544 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6545 else snprintf(message, MSG_SIZ, "%c%c%d\n", PieceToChar(*bp), AAA + j, ONE + i - '0');
6546 if(message[0] == '+' || message[0] == '~') {
6547 snprintf(message, MSG_SIZ,"%c%c%d+\n",
6548 PieceToChar((ChessSquare)(DEMOTED(*bp))),
6549 AAA + j, ONE + i - '0');
6551 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6552 message[1] = BOARD_RGHT - 1 - j + '1';
6553 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6555 SendToProgram(message, cps);
6560 SendToProgram("c\n", cps);
6561 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6562 bp = &boards[moveNum][i][left];
6563 for (j = left; j < right; j++, bp++) {
6564 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6565 if (((int) *bp != (int) EmptySquare)
6566 && ((int) *bp >= (int) BlackPawn)) {
6567 if(j == BOARD_LEFT-2)
6568 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6569 else snprintf(message,MSG_SIZ, "%c%c%d\n", ToUpper(PieceToChar(*bp)),
6570 AAA + j, ONE + i - '0');
6571 if(message[0] == '+' || message[0] == '~') {
6572 snprintf(message, MSG_SIZ,"%c%c%d+\n",
6573 PieceToChar((ChessSquare)(DEMOTED(*bp))),
6574 AAA + j, ONE + i - '0');
6576 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6577 message[1] = BOARD_RGHT - 1 - j + '1';
6578 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6580 SendToProgram(message, cps);
6585 SendToProgram(".\n", cps);
6587 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6590 char exclusionHeader[MSG_SIZ];
6591 int exCnt, excludePtr;
6592 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6593 static Exclusion excluTab[200];
6594 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6600 for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6601 exclusionHeader[19] = s ? '-' : '+'; // update tail state
6607 safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
6608 excludePtr = 24; exCnt = 0;
6613 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6614 { // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6615 char buf[2*MOVE_LEN], *p;
6616 Exclusion *e = excluTab;
6618 for(i=0; i<exCnt; i++)
6619 if(e[i].ff == fromX && e[i].fr == fromY &&
6620 e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
6621 if(i == exCnt) { // was not in exclude list; add it
6622 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6623 if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6624 if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6627 e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6628 excludePtr++; e[i].mark = excludePtr++;
6629 for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6632 exclusionHeader[e[i].mark] = state;
6636 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6637 { // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6641 if((signed char)promoChar == -1) { // kludge to indicate best move
6642 if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6643 return 1; // if unparsable, abort
6645 // update exclusion map (resolving toggle by consulting existing state)
6646 k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6648 if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6649 if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6650 excludeMap[k] |= 1<<j;
6651 else excludeMap[k] &= ~(1<<j);
6653 UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6655 snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6656 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6658 return (state == '+');
6662 ExcludeClick (int index)
6665 Exclusion *e = excluTab;
6666 if(index < 25) { // none, best or tail clicked
6667 if(index < 13) { // none: include all
6668 WriteMap(0); // clear map
6669 for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6670 SendToBoth("include all\n"); // and inform engine
6671 } else if(index > 18) { // tail
6672 if(exclusionHeader[19] == '-') { // tail was excluded
6673 SendToBoth("include all\n");
6674 WriteMap(0); // clear map completely
6675 // now re-exclude selected moves
6676 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6677 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6678 } else { // tail was included or in mixed state
6679 SendToBoth("exclude all\n");
6680 WriteMap(0xFF); // fill map completely
6681 // now re-include selected moves
6682 j = 0; // count them
6683 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6684 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6685 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6688 ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6691 for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6692 char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6693 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6700 DefaultPromoChoice (int white)
6703 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6704 gameInfo.variant == VariantMakruk)
6705 result = WhiteFerz; // no choice
6706 else if(gameInfo.variant == VariantASEAN)
6707 result = WhiteRook; // no choice
6708 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6709 result= WhiteKing; // in Suicide Q is the last thing we want
6710 else if(gameInfo.variant == VariantSpartan)
6711 result = white ? WhiteQueen : WhiteAngel;
6712 else result = WhiteQueen;
6713 if(!white) result = WHITE_TO_BLACK result;
6717 static int autoQueen; // [HGM] oneclick
6720 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6722 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6723 /* [HGM] add Shogi promotions */
6724 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6725 ChessSquare piece, partner;
6729 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6730 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6732 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6733 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6736 if(legal[toY][toX] == 4) return FALSE;
6738 piece = boards[currentMove][fromY][fromX];
6739 if(gameInfo.variant == VariantChu) {
6740 promotionZoneSize = (BOARD_HEIGHT - deadRanks)/3;
6741 if(legal[toY][toX] == 6) return FALSE; // no promotion if highlights deny it
6742 highestPromotingPiece = (PieceToChar(piece) == '+' || PieceToChar(CHUPROMOTED(piece)) != '+') ? WhitePawn : WhiteKing;
6743 } else if(gameInfo.variant == VariantShogi) {
6744 promotionZoneSize = (BOARD_HEIGHT- deadRanks)/3 +(BOARD_HEIGHT == 8);
6745 highestPromotingPiece = (int)WhiteAlfil;
6746 if(PieceToChar(piece) != '+' || PieceToChar(CHUPROMOTED(piece)) == '+') highestPromotingPiece = piece;
6747 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6748 promotionZoneSize = 3;
6751 // Treat Lance as Pawn when it is not representing Amazon or Lance
6752 if(gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu) {
6753 if(piece == WhiteLance) piece = WhitePawn; else
6754 if(piece == BlackLance) piece = BlackPawn;
6757 // next weed out all moves that do not touch the promotion zone at all
6758 if((int)piece >= BlackPawn) {
6759 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6761 if(fromY < promotionZoneSize && gameInfo.variant == VariantChuChess) return FALSE;
6762 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6764 if( toY < BOARD_HEIGHT - deadRanks - promotionZoneSize &&
6765 fromY < BOARD_HEIGHT - deadRanks - promotionZoneSize) return FALSE;
6766 if(fromY >= BOARD_HEIGHT - deadRanks - promotionZoneSize && gameInfo.variant == VariantChuChess)
6770 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6772 // weed out mandatory Shogi promotions
6773 if(gameInfo.variant == VariantShogi) {
6774 if(piece >= BlackPawn) {
6775 if(toY == 0 && piece == BlackPawn ||
6776 toY == 0 && piece == BlackQueen ||
6777 toY <= 1 && piece == BlackKnight) {
6782 if(toY == BOARD_HEIGHT-deadRanks-1 && piece == WhitePawn ||
6783 toY == BOARD_HEIGHT-deadRanks-1 && piece == WhiteQueen ||
6784 toY >= BOARD_HEIGHT-deadRanks-2 && piece == WhiteKnight) {
6791 // weed out obviously illegal Pawn moves
6792 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6793 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6794 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6795 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6796 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6797 // note we are not allowed to test for valid (non-)capture, due to premove
6800 // we either have a choice what to promote to, or (in Shogi) whether to promote
6801 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6802 gameInfo.variant == VariantMakruk) {
6803 ChessSquare p=BlackFerz; // no choice
6804 while(p < EmptySquare) { //but make sure we use piece that exists
6805 *promoChoice = PieceToChar(p++);
6806 if(*promoChoice != '.') break;
6808 if(!*engineVariant) return FALSE; // if used as parent variant there might be promotion choice
6810 // no sense asking what we must promote to if it is going to explode...
6811 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6812 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6815 // give caller the default choice even if we will not make it
6816 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6817 partner = piece; // pieces can promote if the pieceToCharTable says so
6818 if(IS_SHOGI(gameInfo.variant)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? '=' : '+'); // obsolete?
6819 else if(Partner(&partner)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? NULLCHAR : '+');
6820 if( sweepSelect && gameInfo.variant != VariantGreat
6821 && gameInfo.variant != VariantGrand
6822 && gameInfo.variant != VariantSuper) return FALSE;
6823 if(autoQueen) return FALSE; // predetermined
6825 // suppress promotion popup on illegal moves that are not premoves
6826 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6827 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6828 if(appData.testLegality && !premove) {
6829 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6830 fromY, fromX, toY, toX, IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantChuChess ? '+' : NULLCHAR);
6831 if(moveType == IllegalMove) *promoChoice = NULLCHAR; // could be the fact we promoted was illegal
6832 if(moveType != WhitePromotion && moveType != BlackPromotion)
6840 InPalace (int row, int column)
6841 { /* [HGM] for Xiangqi */
6842 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6843 column < (BOARD_WIDTH + 4)/2 &&
6844 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6849 PieceForSquare (int x, int y)
6851 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT) return -1;
6852 if(x == BOARD_RGHT+1 && handOffsets & 1) y += handSize - BOARD_HEIGHT;
6853 if(x == BOARD_LEFT-2 && !(handOffsets & 2)) y += handSize - BOARD_HEIGHT;
6854 return boards[currentMove][y][x];
6858 More (Board board, int col, int start, int end)
6861 for(k=start; k<end; k++) if(board[k][col]) return (col == 1 ? WhiteMonarch : BlackMonarch); // arrow image
6866 DrawPosition (int repaint, Board board)
6868 Board compactedBoard;
6869 if(handSize > BOARD_HEIGHT && board) {
6871 CopyBoard(compactedBoard, board);
6872 if(handOffsets & 1) {
6873 for(k=0; k<BOARD_HEIGHT; k++) {
6874 compactedBoard[k][BOARD_WIDTH-1] = board[k+handSize-BOARD_HEIGHT][BOARD_WIDTH-1];
6875 compactedBoard[k][BOARD_WIDTH-2] = board[k+handSize-BOARD_HEIGHT][BOARD_WIDTH-2];
6877 compactedBoard[0][BOARD_WIDTH-1] = More(board, BOARD_WIDTH-2, 0, handSize-BOARD_HEIGHT+1);
6878 } else compactedBoard[BOARD_HEIGHT-1][BOARD_WIDTH-1] = More(board, BOARD_WIDTH-2, BOARD_HEIGHT-1, handSize);
6879 if(!(handOffsets & 2)) {
6880 for(k=0; k<BOARD_HEIGHT; k++) {
6881 compactedBoard[k][0] = board[k+handSize-BOARD_HEIGHT][0];
6882 compactedBoard[k][1] = board[k+handSize-BOARD_HEIGHT][1];
6884 compactedBoard[0][0] = More(board, 1, 0, handSize-BOARD_HEIGHT+1);
6885 } else compactedBoard[BOARD_HEIGHT-1][0] = More(board, 1, BOARD_HEIGHT-1, handSize);
6886 DrawPositionX(TRUE, compactedBoard);
6887 } else DrawPositionX(repaint, board);
6891 OKToStartUserMove (int x, int y)
6893 ChessSquare from_piece;
6896 if (matchMode) return FALSE;
6897 if (gameMode == EditPosition) return TRUE;
6899 if (x >= 0 && y >= 0)
6900 from_piece = boards[currentMove][y][x];
6902 from_piece = EmptySquare;
6904 if (from_piece == EmptySquare) return FALSE;
6906 white_piece = (int)from_piece >= (int)WhitePawn &&
6907 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6911 case TwoMachinesPlay:
6919 case MachinePlaysWhite:
6920 case IcsPlayingBlack:
6921 if (appData.zippyPlay) return FALSE;
6923 DisplayMoveError(_("You are playing Black"));
6928 case MachinePlaysBlack:
6929 case IcsPlayingWhite:
6930 if (appData.zippyPlay) return FALSE;
6932 DisplayMoveError(_("You are playing White"));
6937 case PlayFromGameFile:
6938 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6941 if (!white_piece && WhiteOnMove(currentMove)) {
6942 DisplayMoveError(_("It is White's turn"));
6945 if (white_piece && !WhiteOnMove(currentMove)) {
6946 DisplayMoveError(_("It is Black's turn"));
6949 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6950 /* Editing correspondence game history */
6951 /* Could disallow this or prompt for confirmation */
6956 case BeginningOfGame:
6957 if (appData.icsActive) return FALSE;
6958 if (!appData.noChessProgram) {
6960 DisplayMoveError(_("You are playing White"));
6967 if (!white_piece && WhiteOnMove(currentMove)) {
6968 DisplayMoveError(_("It is White's turn"));
6971 if (white_piece && !WhiteOnMove(currentMove)) {
6972 DisplayMoveError(_("It is Black's turn"));
6981 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6982 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6983 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6984 && gameMode != AnalyzeFile && gameMode != Training) {
6985 DisplayMoveError(_("Displayed position is not current"));
6992 OnlyMove (int *x, int *y, Boolean captures)
6994 DisambiguateClosure cl;
6995 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6997 case MachinePlaysBlack:
6998 case IcsPlayingWhite:
6999 case BeginningOfGame:
7000 if(!WhiteOnMove(currentMove)) return FALSE;
7002 case MachinePlaysWhite:
7003 case IcsPlayingBlack:
7004 if(WhiteOnMove(currentMove)) return FALSE;
7011 cl.pieceIn = EmptySquare;
7016 cl.promoCharIn = NULLCHAR;
7017 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
7018 if( cl.kind == NormalMove ||
7019 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
7020 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
7021 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
7028 if(cl.kind != ImpossibleMove) return FALSE;
7029 cl.pieceIn = EmptySquare;
7034 cl.promoCharIn = NULLCHAR;
7035 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
7036 if( cl.kind == NormalMove ||
7037 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
7038 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
7039 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
7044 autoQueen = TRUE; // act as if autoQueen on when we click to-square
7050 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
7051 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
7052 int lastLoadGameUseList = FALSE;
7053 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
7054 ChessMove lastLoadGameStart = EndOfFile;
7056 Boolean addToBookFlag;
7057 static Board rightsBoard, nullBoard;
7060 UserMoveEvent (int fromX, int fromY, int toX, int toY, int promoChar)
7064 int ff=fromX, rf=fromY, ft=toX, rt=toY;
7066 /* Check if the user is playing in turn. This is complicated because we
7067 let the user "pick up" a piece before it is his turn. So the piece he
7068 tried to pick up may have been captured by the time he puts it down!
7069 Therefore we use the color the user is supposed to be playing in this
7070 test, not the color of the piece that is currently on the starting
7071 square---except in EditGame mode, where the user is playing both
7072 sides; fortunately there the capture race can't happen. (It can
7073 now happen in IcsExamining mode, but that's just too bad. The user
7074 will get a somewhat confusing message in that case.)
7079 case TwoMachinesPlay:
7083 /* We switched into a game mode where moves are not accepted,
7084 perhaps while the mouse button was down. */
7087 case MachinePlaysWhite:
7088 /* User is moving for Black */
7089 if (WhiteOnMove(currentMove)) {
7090 DisplayMoveError(_("It is White's turn"));
7095 case MachinePlaysBlack:
7096 /* User is moving for White */
7097 if (!WhiteOnMove(currentMove)) {
7098 DisplayMoveError(_("It is Black's turn"));
7103 case PlayFromGameFile:
7104 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
7107 case BeginningOfGame:
7110 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
7111 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
7112 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
7113 /* User is moving for Black */
7114 if (WhiteOnMove(currentMove)) {
7115 DisplayMoveError(_("It is White's turn"));
7119 /* User is moving for White */
7120 if (!WhiteOnMove(currentMove)) {
7121 DisplayMoveError(_("It is Black's turn"));
7127 case IcsPlayingBlack:
7128 /* User is moving for Black */
7129 if (WhiteOnMove(currentMove)) {
7130 if (!appData.premove) {
7131 DisplayMoveError(_("It is White's turn"));
7132 } else if (toX >= 0 && toY >= 0) {
7135 premoveFromX = fromX;
7136 premoveFromY = fromY;
7137 premovePromoChar = promoChar;
7139 if (appData.debugMode)
7140 fprintf(debugFP, "Got premove: fromX %d,"
7141 "fromY %d, toX %d, toY %d\n",
7142 fromX, fromY, toX, toY);
7144 DrawPosition(TRUE, boards[currentMove]); // [HGM] repair animation damage done by premove (in particular emptying from-square)
7149 case IcsPlayingWhite:
7150 /* User is moving for White */
7151 if (!WhiteOnMove(currentMove)) {
7152 if (!appData.premove) {
7153 DisplayMoveError(_("It is Black's turn"));
7154 } else if (toX >= 0 && toY >= 0) {
7157 premoveFromX = fromX;
7158 premoveFromY = fromY;
7159 premovePromoChar = promoChar;
7161 if (appData.debugMode)
7162 fprintf(debugFP, "Got premove: fromX %d,"
7163 "fromY %d, toX %d, toY %d\n",
7164 fromX, fromY, toX, toY);
7166 DrawPosition(TRUE, boards[currentMove]);
7175 /* EditPosition, empty square, or different color piece;
7176 click-click move is possible */
7177 if (toX == -2 || toY == -2) {
7178 boards[0][fromY][fromX] = (boards[0][fromY][fromX] == EmptySquare ? DarkSquare : EmptySquare);
7179 DrawPosition(FALSE, boards[currentMove]);
7181 } else if (toX >= 0 && toY >= 0) {
7182 if(!appData.pieceMenu && toX == fromX && toY == fromY && boards[0][rf][ff] != EmptySquare) {
7183 ChessSquare p = boards[0][rf][ff];
7184 if(PieceToChar(p) == '+') gatingPiece = CHUDEMOTED(p); else
7185 if(PieceToChar(CHUPROMOTED(p)) =='+') gatingPiece = CHUPROMOTED(p); else
7186 if(p == WhiteKing || p == BlackKing || p == WhiteRook || p == BlackRook || p == WhitePawn || p == BlackPawn) {
7187 int n = rightsBoard[toY][toX] ^= 1; // toggle virginity of K or R
7188 DisplayMessage("", n ? _("rights granted") : _("rights revoked"));
7191 } else rightsBoard[toY][toX] = 0; // revoke rights on moving
7192 boards[0][toY][toX] = boards[0][fromY][fromX];
7193 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
7194 if(boards[0][fromY][0] != EmptySquare) {
7195 if(boards[0][fromY][1]) boards[0][fromY][1]--;
7196 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
7199 if(fromX == BOARD_RGHT+1) {
7200 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
7201 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
7202 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
7205 boards[0][fromY][fromX] = gatingPiece;
7207 DrawPosition(FALSE, boards[currentMove]);
7213 if((toX < 0 || toY < 0) && (fromY != DROP_RANK || fromX != EmptySquare)) return;
7214 pup = boards[currentMove][toY][toX];
7216 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
7217 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
7218 if( pup != EmptySquare ) return;
7219 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
7220 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
7221 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
7222 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
7223 if(fromX == 0) fromY = handSize-1 - fromY; // black holdings upside-down
7224 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
7225 while(PieceToChar(fromX) == '.' || PieceToChar(fromX) == '+' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
7229 /* [HGM] always test for legality, to get promotion info */
7230 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
7231 fromY, fromX, toY, toX, promoChar);
7233 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame || PosFlags(0) & F_NULL_MOVE)) moveType = NormalMove;
7235 if(moveType == IllegalMove && legal[toY][toX] > 1) moveType = NormalMove; // someone explicitly told us this move is legal
7237 /* [HGM] but possibly ignore an IllegalMove result */
7238 if (appData.testLegality) {
7239 if (moveType == IllegalMove || moveType == ImpossibleMove) {
7240 DisplayMoveError(_("Illegal move"));
7245 if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
7246 if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
7247 ClearPremoveHighlights(); // was included
7248 else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
7249 DrawPosition(FALSE, NULL);
7253 if(addToBookFlag) { // adding moves to book
7254 char buf[MSG_SIZ], move[MSG_SIZ];
7255 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, move);
7256 if(killX >= 0) snprintf(move, MSG_SIZ, "%c%dx%c%d-%c%d%c", fromX + AAA, fromY + ONE - '0',
7257 killX + AAA, killY + ONE - '0', toX + AAA, toY + ONE - '0', promoChar);
7258 snprintf(buf, MSG_SIZ, " 0.0%% 1 %s\n", move);
7260 addToBookFlag = FALSE;
7265 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
7268 /* Common tail of UserMoveEvent and DropMenuEvent */
7270 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
7274 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
7275 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
7276 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
7277 if(WhiteOnMove(currentMove)) {
7278 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
7280 if(!boards[currentMove][handSize-1-k][1]) return 0;
7284 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
7285 move type in caller when we know the move is a legal promotion */
7286 if(moveType == NormalMove && promoChar)
7287 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
7289 /* [HGM] <popupFix> The following if has been moved here from
7290 UserMoveEvent(). Because it seemed to belong here (why not allow
7291 piece drops in training games?), and because it can only be
7292 performed after it is known to what we promote. */
7293 if (gameMode == Training) {
7294 /* compare the move played on the board to the next move in the
7295 * game. If they match, display the move and the opponent's response.
7296 * If they don't match, display an error message.
7300 CopyBoard(testBoard, boards[currentMove]);
7301 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
7303 if (CompareBoards(testBoard, boards[currentMove+1])) {
7304 ForwardInner(currentMove+1);
7306 /* Autoplay the opponent's response.
7307 * if appData.animate was TRUE when Training mode was entered,
7308 * the response will be animated.
7310 saveAnimate = appData.animate;
7311 appData.animate = animateTraining;
7312 ForwardInner(currentMove+1);
7313 appData.animate = saveAnimate;
7315 /* check for the end of the game */
7316 if (currentMove >= forwardMostMove) {
7317 gameMode = PlayFromGameFile;
7319 SetTrainingModeOff();
7320 DisplayInformation(_("End of game"));
7323 DisplayError(_("Incorrect move"), 0);
7328 /* Ok, now we know that the move is good, so we can kill
7329 the previous line in Analysis Mode */
7330 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
7331 && currentMove < forwardMostMove) {
7332 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
7333 else forwardMostMove = currentMove;
7338 /* If we need the chess program but it's dead, restart it */
7339 ResurrectChessProgram();
7341 /* A user move restarts a paused game*/
7345 thinkOutput[0] = NULLCHAR;
7347 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
7349 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
7350 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7354 if (gameMode == BeginningOfGame) {
7355 if (appData.noChessProgram) {
7356 gameMode = EditGame;
7360 gameMode = MachinePlaysBlack;
7363 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
7365 if (first.sendName) {
7366 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
7367 SendToProgram(buf, &first);
7374 /* Relay move to ICS or chess engine */
7375 if (appData.icsActive) {
7376 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
7377 gameMode == IcsExamining) {
7378 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7379 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7381 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7383 // also send plain move, in case ICS does not understand atomic claims
7384 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7388 if (first.sendTime && (gameMode == BeginningOfGame ||
7389 gameMode == MachinePlaysWhite ||
7390 gameMode == MachinePlaysBlack)) {
7391 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
7393 if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
7394 // [HGM] book: if program might be playing, let it use book
7395 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
7396 first.maybeThinking = TRUE;
7397 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
7398 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
7399 SendBoard(&first, currentMove+1);
7400 if(second.analyzing) {
7401 if(!second.useSetboard) SendToProgram("undo\n", &second);
7402 SendBoard(&second, currentMove+1);
7405 SendMoveToProgram(forwardMostMove-1, &first);
7406 if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
7408 if (currentMove == cmailOldMove + 1) {
7409 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7413 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7417 if(appData.testLegality)
7418 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
7424 if (WhiteOnMove(currentMove)) {
7425 GameEnds(BlackWins, "Black mates", GE_PLAYER);
7427 GameEnds(WhiteWins, "White mates", GE_PLAYER);
7431 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
7436 case MachinePlaysBlack:
7437 case MachinePlaysWhite:
7438 /* disable certain menu options while machine is thinking */
7439 SetMachineThinkingEnables();
7446 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
7447 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
7449 if(bookHit) { // [HGM] book: simulate book reply
7450 static char bookMove[MSG_SIZ]; // a bit generous?
7452 programStats.nodes = programStats.depth = programStats.time =
7453 programStats.score = programStats.got_only_move = 0;
7454 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7456 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7457 strcat(bookMove, bookHit);
7458 HandleMachineMove(bookMove, &first);
7464 MarkByFEN(char *fen)
7467 if(!appData.markers || !appData.highlightDragging) return;
7468 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) legal[r][f] = marker[r][f] = 0;
7469 r=BOARD_HEIGHT-1-deadRanks; f=BOARD_LEFT;
7472 if(*fen == 'M') legal[r][f] = 2; else // request promotion choice
7473 if(*fen == 'B') legal[r][f] = 4; else // request auto-promotion to victim
7474 if(*fen >= 'A' && *fen <= 'Z') legal[r][f] = 6; else
7475 if(*fen >= 'a' && *fen <= 'z') *fen += 'A' - 'a';
7476 if(*fen == '/' && f > BOARD_LEFT) f = BOARD_LEFT, r--; else
7477 if(*fen == 'T') marker[r][f++] = 0; else
7478 if(*fen == 'Y') marker[r][f++] = 1; else
7479 if(*fen == 'G') marker[r][f++] = 3; else
7480 if(*fen == 'B') marker[r][f++] = 4; else
7481 if(*fen == 'C') marker[r][f++] = 5; else
7482 if(*fen == 'M') marker[r][f++] = 6; else
7483 if(*fen == 'W') marker[r][f++] = 7; else
7484 if(*fen == 'D') marker[r][f++] = 8; else
7485 if(*fen == 'R') marker[r][f++] = 2; else {
7486 while(*fen <= '9' && *fen >= '0') s = 10*s + *fen++ - '0';
7489 while(f >= BOARD_RGHT) f -= BOARD_RGHT - BOARD_LEFT, r--;
7493 DrawPosition(TRUE, NULL);
7496 static char baseMarker[BOARD_RANKS][BOARD_FILES], baseLegal[BOARD_RANKS][BOARD_FILES];
7499 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7501 typedef char Markers[BOARD_RANKS][BOARD_FILES];
7502 Markers *m = (Markers *) closure;
7503 if(rf == fromY && ff == fromX && (killX < 0 ? !(rt == rf && ft == ff) && legNr & 1 :
7504 kill2X < 0 ? rt == killY && ft == killX || legNr & 2 : rt == killY && ft == killX || legNr & 4))
7505 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7506 || kind == WhiteCapturesEnPassant
7507 || kind == BlackCapturesEnPassant) + 3*(kind == FirstLeg && (killX < 0 & legNr || legNr & 2 && kill2X < 0)), legal[rt][ft] = 3;
7508 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3, legal[rt][ft] = 3;
7511 static int hoverSavedValid;
7514 MarkTargetSquares (int clear)
7517 if(clear) { // no reason to ever suppress clearing
7518 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) sum += marker[y][x], marker[y][x] = 0;
7519 hoverSavedValid = 0;
7520 if(!sum || clear < 0) return; // nothing was cleared,no redraw needed
7523 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7524 !appData.testLegality && !pieceDefs || gameMode == EditPosition) return;
7525 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7526 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7527 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7529 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = legal[y][x] = 0;
7532 DrawPosition(FALSE, NULL);
7536 Explode (Board board, int fromX, int fromY, int toX, int toY)
7538 if(gameInfo.variant == VariantAtomic &&
7539 (board[toY][toX] != EmptySquare || // capture?
7540 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
7541 board[fromY][fromX] == BlackPawn )
7543 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7549 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7552 CanPromote (ChessSquare piece, int y)
7554 int zone = (gameInfo.variant == VariantChuChess ? 3 : 1);
7555 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7556 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7557 if(IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantXiangqi ||
7558 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
7559 (gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7560 gameInfo.variant == VariantMakruk) && !*engineVariant) return FALSE;
7561 return (piece == BlackPawn && y <= zone ||
7562 piece == WhitePawn && y >= BOARD_HEIGHT-1-deadRanks-zone ||
7563 piece == BlackLance && y <= zone ||
7564 piece == WhiteLance && y >= BOARD_HEIGHT-1-deadRanks-zone );
7568 HoverEvent (int xPix, int yPix, int x, int y)
7570 static int oldX = -1, oldY = -1, oldFromX = -1, oldFromY = -1;
7572 if(!first.highlight) return;
7573 if(fromX != oldFromX || fromY != oldFromY) oldX = oldY = -1; // kludge to fake entry on from-click
7574 if(x == oldX && y == oldY) return; // only do something if we enter new square
7575 oldFromX = fromX; oldFromY = fromY;
7576 if(oldX == -1 && oldY == -1 && x == fromX && y == fromY) { // record markings after from-change
7577 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7578 baseMarker[r][f] = marker[r][f], baseLegal[r][f] = legal[r][f];
7579 hoverSavedValid = 1;
7580 } else if(oldX != x || oldY != y) {
7581 // [HGM] lift: entered new to-square; redraw arrow, and inform engine
7582 if(hoverSavedValid) // don't restore markers that are supposed to be cleared
7583 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7584 marker[r][f] = baseMarker[r][f], legal[r][f] = baseLegal[r][f];
7585 if((marker[y][x] == 2 || marker[y][x] == 6) && legal[y][x]) {
7587 snprintf(buf, MSG_SIZ, "hover %c%d\n", x + AAA, y + ONE - '0');
7588 SendToProgram(buf, &first);
7591 // SetHighlights(fromX, fromY, x, y);
7595 void ReportClick(char *action, int x, int y)
7597 char buf[MSG_SIZ]; // Inform engine of what user does
7599 if(action[0] == 'l') // mark any target square of a lifted piece as legal to-square, clear markers
7600 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7601 legal[r][f] = !pieceDefs || !appData.markers, marker[r][f] = 0;
7602 if(!first.highlight || gameMode == EditPosition) return;
7603 snprintf(buf, MSG_SIZ, "%s %c%d%s\n", action, x+AAA, y+ONE-'0', controlKey && action[0]=='p' ? "," : "");
7604 SendToProgram(buf, &first);
7607 Boolean right; // instructs front-end to use button-1 events as if they were button 3
7608 Boolean deferChoice;
7609 int createX = -1, createY = -1; // square where we last created a piece in EditPosition mode
7612 LeftClick (ClickType clickType, int xPix, int yPix)
7615 static Boolean saveAnimate;
7616 static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0, flashing = 0, saveFlash;
7617 char promoChoice = NULLCHAR;
7619 static TimeMark lastClickTime, prevClickTime;
7621 if(flashing) return;
7623 if(!deferChoice) { // when called for a retry, skip everything to the point where we left off
7624 x = EventToSquare(xPix, BOARD_WIDTH);
7625 y = EventToSquare(yPix, BOARD_HEIGHT);
7626 if (!flipView && y >= 0) {
7627 y = BOARD_HEIGHT - 1 - y;
7629 if (flipView && x >= 0) {
7630 x = BOARD_WIDTH - 1 - x;
7633 // map clicks in offsetted holdings back to true coords (or switch the offset)
7634 if(x == BOARD_RGHT+1) {
7635 if(handOffsets & 1) {
7636 if(y == 0) { handOffsets &= ~1; DrawPosition(TRUE, boards[currentMove]); return; }
7637 y += handSize - BOARD_HEIGHT;
7638 } else if(y == BOARD_HEIGHT-1) { handOffsets |= 1; DrawPosition(TRUE, boards[currentMove]); return; }
7640 if(x == BOARD_LEFT-2) {
7641 if(!(handOffsets & 2)) {
7642 if(y == 0) { handOffsets |= 2; DrawPosition(TRUE, boards[currentMove]); return; }
7643 y += handSize - BOARD_HEIGHT;
7644 } else if(y == BOARD_HEIGHT-1) { handOffsets &= ~2; DrawPosition(TRUE, boards[currentMove]); return; }
7647 if(appData.monoMouse && gameMode == EditPosition && fromX < 0 && clickType == Press &&
7648 (boards[currentMove][y][x] == EmptySquare || x == createX && y == createY) ) {
7650 RightClick(clickType, xPix, yPix, &dummy, &dummy);
7655 createX = createY = -1;
7657 if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7659 prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7661 if (clickType == Press) ErrorPopDown();
7662 lastClickType = clickType, lastLeftX = xPix, lastLeftY = yPix; // [HGM] alien: remember state
7664 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7665 defaultPromoChoice = promoSweep;
7666 promoSweep = EmptySquare; // terminate sweep
7667 promoDefaultAltered = TRUE;
7668 if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7671 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7672 if(clickType == Release) return; // ignore upclick of click-click destination
7673 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7674 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7675 if(gameInfo.holdingsWidth &&
7676 (WhiteOnMove(currentMove)
7677 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7678 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7679 // click in right holdings, for determining promotion piece
7680 ChessSquare p = boards[currentMove][y][x];
7681 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7682 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7683 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7684 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7689 DrawPosition(FALSE, boards[currentMove]);
7693 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7694 if(clickType == Press
7695 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7696 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7697 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7700 if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7701 // could be static click on premove from-square: abort premove
7703 ClearPremoveHighlights();
7706 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7707 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7709 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7710 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7711 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7712 defaultPromoChoice = DefaultPromoChoice(side);
7715 autoQueen = appData.alwaysPromoteToQueen;
7719 gatingPiece = EmptySquare;
7720 if (clickType != Press) {
7721 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7722 DragPieceEnd(xPix, yPix); dragging = 0;
7723 DrawPosition(FALSE, NULL);
7727 doubleClick = FALSE;
7728 if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7729 doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7731 fromX = x; fromY = y; toX = toY = killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
7732 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7733 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7734 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7736 if (OKToStartUserMove(fromX, fromY)) {
7738 ReportClick("lift", x, y);
7739 MarkTargetSquares(0);
7740 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7741 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7742 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7743 promoSweep = defaultPromoChoice;
7744 selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
7745 Sweep(0); // Pawn that is going to promote: preview promotion piece
7746 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7748 if (appData.highlightDragging) {
7749 SetHighlights(fromX, fromY, -1, -1);
7753 } else fromX = fromY = -1;
7759 if (clickType == Press && gameMode != EditPosition) {
7764 // ignore off-board to clicks
7765 if(y < 0 || x < 0) return;
7767 /* Check if clicking again on the same color piece */
7768 fromP = boards[currentMove][fromY][fromX];
7769 toP = boards[currentMove][y][x];
7770 frc = appData.fischerCastling || gameInfo.variant == VariantSChess;
7771 if( (killX < 0 || x != fromX || y != fromY) && // [HGM] lion: do not interpret igui as deselect!
7772 marker[y][x] == 0 && // if engine told we can move to here, do it even if own piece
7773 ((WhitePawn <= fromP && fromP <= WhiteKing &&
7774 WhitePawn <= toP && toP <= WhiteKing &&
7775 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7776 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7777 (BlackPawn <= fromP && fromP <= BlackKing &&
7778 BlackPawn <= toP && toP <= BlackKing &&
7779 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7780 !(fromP == BlackKing && toP == BlackRook && frc)))) {
7781 /* Clicked again on same color piece -- changed his mind */
7782 second = (x == fromX && y == fromY);
7783 killX = killY = kill2X = kill2Y = -1; *promoRestrict = NULLCHAR;
7784 if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7785 second = FALSE; // first double-click rather than scond click
7786 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7788 promoDefaultAltered = FALSE;
7789 if(!second) MarkTargetSquares(1);
7790 if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
7791 if (appData.highlightDragging) {
7792 SetHighlights(x, y, -1, -1);
7796 if (OKToStartUserMove(x, y)) {
7797 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7798 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7799 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7800 gatingPiece = boards[currentMove][fromY][fromX];
7801 else gatingPiece = doubleClick ? fromP : EmptySquare;
7803 fromY = y; dragging = 1;
7804 if(!second) ReportClick("lift", x, y);
7805 MarkTargetSquares(0);
7806 DragPieceBegin(xPix, yPix, FALSE);
7807 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7808 promoSweep = defaultPromoChoice;
7809 selectFlag = 0; lastX = xPix; lastY = yPix; *promoRestrict = 0;
7810 Sweep(0); // Pawn that is going to promote: preview promotion piece
7814 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7817 // ignore clicks on holdings
7818 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7821 if(x == fromX && y == fromY && clickType == Press && gameMode == EditPosition && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7822 gatingPiece = boards[currentMove][fromY][fromX]; // prepare to copy rather than move
7823 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7827 if (clickType == Release && x == fromX && y == fromY && killX < 0 && !sweepSelecting) {
7828 DragPieceEnd(xPix, yPix); dragging = 0;
7830 // a deferred attempt to click-click move an empty square on top of a piece
7831 boards[currentMove][y][x] = EmptySquare;
7833 DrawPosition(FALSE, boards[currentMove]);
7834 fromX = fromY = -1; clearFlag = 0;
7837 if (appData.animateDragging) {
7838 /* Undo animation damage if any */
7839 DrawPosition(FALSE, NULL);
7842 /* Second up/down in same square; just abort move */
7845 gatingPiece = EmptySquare;
7848 ClearPremoveHighlights();
7849 MarkTargetSquares(-1);
7850 DrawPosition(FALSE, NULL); // make user highlights are drawn (and deferred marker clearing)
7852 /* First upclick in same square; start click-click mode */
7853 SetHighlights(x, y, -1, -1);
7860 if(gameMode != EditPosition && !appData.testLegality && !legal[y][x] &&
7861 fromX >= BOARD_LEFT && fromX < BOARD_RGHT && (x != killX || y != killY) && !sweepSelecting) {
7862 if(dragging) DragPieceEnd(xPix, yPix), dragging = 0;
7863 DisplayMessage(_("only marked squares are legal"),"");
7864 DrawPosition(TRUE, NULL);
7865 return; // ignore to-click
7868 /* we now have a different from- and (possibly off-board) to-square */
7869 /* Completed move */
7870 if(!sweepSelecting) {
7875 piece = boards[currentMove][fromY][fromX];
7877 saveAnimate = appData.animate;
7878 if (clickType == Press) {
7879 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7880 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7881 // must be Edit Position mode with empty-square selected
7882 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7883 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7886 if(dragging == 2) { // [HGM] lion: just turn buttonless drag into normal drag, and let release to the job
7889 if(x == killX && y == killY) { // second click on this square, which was selected as first-leg target
7890 killX = kill2X; killY = kill2Y; kill2X = kill2Y = -1; // this informs us no second leg is coming, so treat as to-click without intermediate
7892 if(marker[y][x] == 5) return; // [HGM] lion: to-click on cyan square; defer action to release
7893 if(legal[y][x] == 2 || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7894 if(appData.sweepSelect) {
7895 promoSweep = defaultPromoChoice;
7896 if(gameInfo.variant != VariantChuChess && PieceToChar(CHUPROMOTED(piece)) == '+') promoSweep = CHUPROMOTED(piece);
7897 selectFlag = 0; lastX = xPix; lastY = yPix;
7898 ReportClick("put", x, y); // extra put to prompt engine for 'choice' command
7899 saveFlash = appData.flashCount; appData.flashCount = 0;
7900 Sweep(0); // Pawn that is going to promote: preview promotion piece
7902 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7903 MarkTargetSquares(1);
7905 return; // promo popup appears on up-click
7907 /* Finish clickclick move */
7908 if (appData.animate || appData.highlightLastMove) {
7909 SetHighlights(fromX, fromY, toX, toY);
7913 MarkTargetSquares(1);
7914 } else if(sweepSelecting) { // this must be the up-click corresponding to the down-click that started the sweep
7915 sweepSelecting = 0; appData.animate = FALSE; // do not animate, a selected piece already on to-square
7916 *promoRestrict = 0; appData.flashCount = saveFlash;
7917 if (appData.animate || appData.highlightLastMove) {
7918 SetHighlights(fromX, fromY, toX, toY);
7922 MarkTargetSquares(1);
7925 // [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
7926 /* Finish drag move */
7927 if (appData.highlightLastMove) {
7928 SetHighlights(fromX, fromY, toX, toY);
7933 if(PieceToChar(CHUPROMOTED(boards[currentMove][fromY][fromX])) == '+')
7934 defaultPromoChoice = CHUPROMOTED(boards[currentMove][fromY][fromX]);
7935 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7936 if(marker[y][x] == 5) { // [HGM] lion: this was the release of a to-click or drag on a cyan square
7937 dragging *= 2; // flag button-less dragging if we are dragging
7938 MarkTargetSquares(1);
7939 if(x == killX && y == killY) killX = kill2X, killY = kill2Y, kill2X = kill2Y = -1; // cancel last kill
7941 kill2X = killX; kill2Y = killY;
7942 killX = x; killY = y; // remember this square as intermediate
7943 ReportClick("put", x, y); // and inform engine
7944 ReportClick("lift", x, y);
7945 MarkTargetSquares(0);
7949 DragPieceEnd(xPix, yPix); dragging = 0;
7950 /* Don't animate move and drag both */
7951 appData.animate = FALSE;
7952 MarkTargetSquares(-1); // -1 defers displaying marker change to prevent piece reappearing on from-square!
7955 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7956 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7957 ChessSquare piece = boards[currentMove][fromY][fromX];
7958 if(gameMode == EditPosition && piece != EmptySquare &&
7959 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7962 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7963 n = PieceToNumber(piece - (int)BlackPawn);
7964 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7965 boards[currentMove][handSize-1 - n][0] = piece;
7966 boards[currentMove][handSize-1 - n][1]++;
7968 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7969 n = PieceToNumber(piece);
7970 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7971 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7972 boards[currentMove][n][BOARD_WIDTH-2]++;
7974 boards[currentMove][fromY][fromX] = EmptySquare;
7978 MarkTargetSquares(1);
7979 DrawPosition(TRUE, boards[currentMove]);
7983 // off-board moves should not be highlighted
7984 if(x < 0 || y < 0) {
7986 DrawPosition(FALSE, NULL);
7987 } else ReportClick("put", x, y);
7989 if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7992 if(legal[toY][toX] == 2) { // highlight-induced promotion
7993 if(piece == defaultPromoChoice) promoChoice = NULLCHAR; // deferral
7994 else promoChoice = ToLower(PieceToChar(defaultPromoChoice));
7995 } else if(legal[toY][toX] == 4) { // blue target square: engine must supply promotion choice
7996 if(!*promoRestrict) { // but has not done that yet
7997 deferChoice = TRUE; // set up retry for when it does
7998 return; // and wait for that
8000 promoChoice = ToLower(*promoRestrict); // force engine's choice
8001 deferChoice = FALSE;
8004 if (legal[toY][toX] == 2 && !appData.sweepSelect || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
8005 SetHighlights(fromX, fromY, toX, toY);
8006 MarkTargetSquares(1);
8007 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
8008 // [HGM] super: promotion to captured piece selected from holdings
8009 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
8010 promotionChoice = TRUE;
8011 // kludge follows to temporarily execute move on display, without promoting yet
8012 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
8013 boards[currentMove][toY][toX] = p;
8014 DrawPosition(FALSE, boards[currentMove]);
8015 boards[currentMove][fromY][fromX] = p; // take back, but display stays
8016 boards[currentMove][toY][toX] = q;
8017 DisplayMessage("Click in holdings to choose piece", "");
8020 DrawPosition(FALSE, NULL); // shows piece on from-square during promo popup
8021 PromotionPopUp(promoChoice);
8023 int oldMove = currentMove;
8024 flashing = 1; // prevent recursive calling (by release of to-click) while flashing piece
8025 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
8026 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
8027 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY), DrawPosition(FALSE, NULL);
8028 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
8029 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
8030 DrawPosition(TRUE, boards[currentMove]);
8031 else DrawPosition(FALSE, NULL);
8035 appData.animate = saveAnimate;
8036 if (appData.animate || appData.animateDragging) {
8037 /* Undo animation damage if needed */
8038 // DrawPosition(FALSE, NULL);
8043 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
8044 { // front-end-free part taken out of PieceMenuPopup
8045 int whichMenu; int xSqr, ySqr;
8047 if(seekGraphUp) { // [HGM] seekgraph
8048 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
8049 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
8053 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
8054 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
8055 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
8056 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
8057 if(action == Press) {
8058 originalFlip = flipView;
8059 flipView = !flipView; // temporarily flip board to see game from partners perspective
8060 DrawPosition(TRUE, partnerBoard);
8061 DisplayMessage(partnerStatus, "");
8063 } else if(action == Release) {
8064 flipView = originalFlip;
8065 DrawPosition(TRUE, boards[currentMove]);
8071 xSqr = EventToSquare(x, BOARD_WIDTH);
8072 ySqr = EventToSquare(y, BOARD_HEIGHT);
8073 if (action == Release) {
8074 if(pieceSweep != EmptySquare) {
8075 EditPositionMenuEvent(pieceSweep, toX, toY);
8076 pieceSweep = EmptySquare;
8077 } else UnLoadPV(); // [HGM] pv
8079 if (action != Press) return -2; // return code to be ignored
8082 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
8084 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
8085 if (xSqr < 0 || ySqr < 0) return -1;
8086 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
8087 if(flipView) xSqr = BOARD_WIDTH - 1 - xSqr; else ySqr = BOARD_HEIGHT - 1 - ySqr;
8088 if(xSqr == createX && ySqr == createY && xSqr != BOARD_LEFT-2 && xSqr != BOARD_RGHT+1) {
8089 ChessSquare p = boards[currentMove][ySqr][xSqr];
8090 do { if(++p == EmptySquare) p = WhitePawn; } while(PieceToChar(p) == '.');
8091 boards[currentMove][ySqr][xSqr] = p; DrawPosition(FALSE, boards[currentMove]);
8094 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
8095 createX = toX = xSqr; createY = toY = ySqr; lastX = x, lastY = y;
8099 if(!appData.icsEngineAnalyze) return -1;
8100 case IcsPlayingWhite:
8101 case IcsPlayingBlack:
8102 if(!appData.zippyPlay) goto noZip;
8105 case MachinePlaysWhite:
8106 case MachinePlaysBlack:
8107 case TwoMachinesPlay: // [HGM] pv: use for showing PV
8108 if (!appData.dropMenu) {
8110 return 2; // flag front-end to grab mouse events
8112 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
8113 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
8116 if (xSqr < 0 || ySqr < 0) return -1;
8117 if (!appData.dropMenu || appData.testLegality &&
8118 gameInfo.variant != VariantBughouse &&
8119 gameInfo.variant != VariantCrazyhouse) return -1;
8120 whichMenu = 1; // drop menu
8126 if (((*fromX = xSqr) < 0) ||
8127 ((*fromY = ySqr) < 0)) {
8128 *fromX = *fromY = -1;
8132 *fromX = BOARD_WIDTH - 1 - *fromX;
8134 *fromY = BOARD_HEIGHT - 1 - *fromY;
8140 Wheel (int dir, int x, int y)
8142 if(gameMode == EditPosition) {
8143 int xSqr = EventToSquare(x, BOARD_WIDTH);
8144 int ySqr = EventToSquare(y, BOARD_HEIGHT);
8145 if(ySqr < 0 || xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return;
8146 if(flipView) xSqr = BOARD_WIDTH - 1 - xSqr; else ySqr = BOARD_HEIGHT - 1 - ySqr;
8148 boards[currentMove][ySqr][xSqr] += dir;
8149 if((int) boards[currentMove][ySqr][xSqr] < WhitePawn) boards[currentMove][ySqr][xSqr] = BlackKing;
8150 if((int) boards[currentMove][ySqr][xSqr] > BlackKing) boards[currentMove][ySqr][xSqr] = WhitePawn;
8151 } while(PieceToChar(boards[currentMove][ySqr][xSqr]) == '.');
8152 DrawPosition(FALSE, boards[currentMove]);
8153 } else if(dir > 0) ForwardEvent(); else BackwardEvent();
8157 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
8159 // char * hint = lastHint;
8160 FrontEndProgramStats stats;
8162 stats.which = cps == &first ? 0 : 1;
8163 stats.depth = cpstats->depth;
8164 stats.nodes = cpstats->nodes;
8165 stats.score = cpstats->score;
8166 stats.time = cpstats->time;
8167 stats.pv = cpstats->movelist;
8168 stats.hint = lastHint;
8169 stats.an_move_index = 0;
8170 stats.an_move_count = 0;
8172 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
8173 stats.hint = cpstats->move_name;
8174 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
8175 stats.an_move_count = cpstats->nr_moves;
8178 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
8180 if( gameMode == AnalyzeMode && stats.pv && stats.pv[0]
8181 && appData.analysisBell && stats.time >= 100*appData.analysisBell ) RingBell();
8183 SetProgramStats( &stats );
8187 ClearEngineOutputPane (int which)
8189 static FrontEndProgramStats dummyStats;
8190 dummyStats.which = which;
8191 dummyStats.pv = "#";
8192 SetProgramStats( &dummyStats );
8195 #define MAXPLAYERS 500
8198 TourneyStandings (int display)
8200 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
8201 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
8202 char result, *p, *names[MAXPLAYERS];
8204 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
8205 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
8206 names[0] = p = strdup(appData.participants);
8207 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
8209 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
8211 while(result = appData.results[nr]) {
8212 color = Pairing(nr, nPlayers, &w, &b, &dummy);
8213 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
8214 wScore = bScore = 0;
8216 case '+': wScore = 2; break;
8217 case '-': bScore = 2; break;
8218 case '=': wScore = bScore = 1; break;
8220 case '*': return strdup("busy"); // tourney not finished
8228 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
8229 for(w=0; w<nPlayers; w++) {
8231 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
8232 ranking[w] = b; points[w] = bScore; score[b] = -2;
8234 p = malloc(nPlayers*34+1);
8235 for(w=0; w<nPlayers && w<display; w++)
8236 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
8242 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
8243 { // count all piece types
8245 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
8246 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
8247 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8250 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
8251 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
8252 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
8253 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
8254 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
8255 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
8260 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
8262 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
8263 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
8265 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
8266 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
8267 if(myPawns == 2 && nMine == 3) // KPP
8268 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
8269 if(myPawns == 1 && nMine == 2) // KP
8270 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
8271 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
8272 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
8273 if(myPawns) return FALSE;
8274 if(pCnt[WhiteRook+side])
8275 return pCnt[BlackRook-side] ||
8276 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
8277 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
8278 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
8279 if(pCnt[WhiteCannon+side]) {
8280 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
8281 return majorDefense || pCnt[BlackAlfil-side] >= 2;
8283 if(pCnt[WhiteKnight+side])
8284 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
8289 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
8291 VariantClass v = gameInfo.variant;
8293 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
8294 if(v == VariantShatranj) return TRUE; // always winnable through baring
8295 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
8296 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
8298 if(v == VariantXiangqi) {
8299 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
8301 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
8302 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
8303 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
8304 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
8305 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
8306 if(stale) // we have at least one last-rank P plus perhaps C
8307 return majors // KPKX
8308 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
8310 return pCnt[WhiteFerz+side] // KCAK
8311 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
8312 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
8313 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
8315 } else if(v == VariantKnightmate) {
8316 if(nMine == 1) return FALSE;
8317 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
8318 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
8319 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
8321 if(nMine == 1) return FALSE; // bare King
8322 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
8323 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
8324 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
8325 // by now we have King + 1 piece (or multiple Bishops on the same color)
8326 if(pCnt[WhiteKnight+side])
8327 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
8328 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
8329 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
8331 return (pCnt[BlackKnight-side]); // KBKN, KFKN
8332 if(pCnt[WhiteAlfil+side])
8333 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
8334 if(pCnt[WhiteWazir+side])
8335 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
8342 CompareWithRights (Board b1, Board b2)
8345 if(!CompareBoards(b1, b2)) return FALSE;
8346 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
8347 /* compare castling rights */
8348 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
8349 rights++; /* King lost rights, while rook still had them */
8350 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
8351 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
8352 rights++; /* but at least one rook lost them */
8354 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
8356 if( b1[CASTLING][5] != NoRights ) {
8357 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
8364 Adjudicate (ChessProgramState *cps)
8365 { // [HGM] some adjudications useful with buggy engines
8366 // [HGM] adjudicate: made into separate routine, which now can be called after every move
8367 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
8368 // Actually ending the game is now based on the additional internal condition canAdjudicate.
8369 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
8370 int k, drop, count = 0; static int bare = 1;
8371 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
8372 Boolean canAdjudicate = !appData.icsActive;
8374 // most tests only when we understand the game, i.e. legality-checking on
8375 if( appData.testLegality )
8376 { /* [HGM] Some more adjudications for obstinate engines */
8377 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+2], i;
8378 static int moveCount = 6;
8380 char *reason = NULL;
8382 /* Count what is on board. */
8383 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8385 /* Some material-based adjudications that have to be made before stalemate test */
8386 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
8387 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
8388 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
8389 if(canAdjudicate && appData.checkMates) {
8391 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8392 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
8393 "Xboard adjudication: King destroyed", GE_XBOARD );
8398 /* Bare King in Shatranj (loses) or Losers (wins) */
8399 if( nrW == 1 || nrB == 1) {
8400 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
8401 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
8402 if(canAdjudicate && appData.checkMates) {
8404 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
8405 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8406 "Xboard adjudication: Bare king", GE_XBOARD );
8410 if( gameInfo.variant == VariantShatranj && --bare < 0)
8412 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
8413 if(canAdjudicate && appData.checkMates) {
8414 /* but only adjudicate if adjudication enabled */
8416 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8417 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
8418 "Xboard adjudication: Bare king", GE_XBOARD );
8425 // don't wait for engine to announce game end if we can judge ourselves
8426 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8428 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
8429 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
8430 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
8431 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
8434 reason = "Xboard adjudication: 3rd check";
8435 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
8446 reason = "Xboard adjudication: Stalemate";
8447 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
8448 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
8449 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
8450 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
8451 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
8452 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
8453 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
8454 EP_CHECKMATE : EP_WINS);
8455 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
8456 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
8460 reason = "Xboard adjudication: Checkmate";
8461 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
8462 if(gameInfo.variant == VariantShogi) {
8463 if(forwardMostMove > backwardMostMove
8464 && moveList[forwardMostMove-1][1] == '@'
8465 && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
8466 reason = "XBoard adjudication: pawn-drop mate";
8467 boards[forwardMostMove][EP_STATUS] = EP_WINS;
8473 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
8475 result = GameIsDrawn; break;
8477 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
8479 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
8483 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
8485 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8486 GameEnds( result, reason, GE_XBOARD );
8490 /* Next absolutely insufficient mating material. */
8491 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
8492 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
8493 { /* includes KBK, KNK, KK of KBKB with like Bishops */
8495 /* always flag draws, for judging claims */
8496 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
8498 if(canAdjudicate && appData.materialDraws) {
8499 /* but only adjudicate them if adjudication enabled */
8500 if(engineOpponent) {
8501 SendToProgram("force\n", engineOpponent); // suppress reply
8502 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
8504 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
8509 /* Then some trivial draws (only adjudicate, cannot be claimed) */
8510 if(gameInfo.variant == VariantXiangqi ?
8511 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
8513 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
8514 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
8515 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
8516 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
8518 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
8519 { /* if the first 3 moves do not show a tactical win, declare draw */
8520 if(engineOpponent) {
8521 SendToProgram("force\n", engineOpponent); // suppress reply
8522 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8524 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
8527 } else moveCount = 6;
8529 if(gameInfo.variant == VariantMakruk && // Makruk counting rules
8530 (nrW == 1 || nrB == 1 || nr[WhitePawn] + nr[BlackPawn] == 0)) { // which only kick in when pawnless or bare King
8531 int maxcnt, his, mine, c, wom = WhiteOnMove(forwardMostMove);
8532 count = forwardMostMove;
8533 while(count >= backwardMostMove) {
8534 int np = nr[WhitePawn] + nr[BlackPawn];
8535 if(wom) mine = nrW, his = nrB, c = BlackPawn;
8536 else mine = nrB, his = nrW, c = WhitePawn;
8537 if(mine > 1 && np) { count++; break; }
8538 if(mine > 1) maxcnt = 64; else
8539 maxcnt = (nr[WhiteRook+c] > 1 ? 8 : nr[WhiteRook+c] ? 16 : nr[WhiteMan+c] > 1 ? 22 :
8540 nr[WhiteKnight+c] > 1 ? 32 : nr[WhiteMan+c] ? 44 : 64) - his - 1;
8541 while(boards[count][EP_STATUS] != EP_CAPTURE && count > backwardMostMove) count--; // seek previous character
8542 if(count == backwardMostMove) break;
8543 if(forwardMostMove - count >= 2*maxcnt + 1 - (mine == 1)) break;
8544 Count(boards[--count], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8546 if(forwardMostMove - count >= 2*maxcnt + 1 - (mine == 1)) {
8547 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8548 if(canAdjudicate && appData.ruleMoves >= 0) {
8549 GameEnds( GameIsDrawn, "Xboard adjudication: counting rule", GE_XBOARD );
8556 // Repetition draws and 50-move rule can be applied independently of legality testing
8558 /* Check for rep-draws */
8560 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
8561 && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
8562 for(k = forwardMostMove-2;
8563 k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
8564 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
8565 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
8568 if(CompareBoards(boards[k], boards[forwardMostMove])) {
8569 /* compare castling rights */
8570 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
8571 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
8572 rights++; /* King lost rights, while rook still had them */
8573 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
8574 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
8575 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
8576 rights++; /* but at least one rook lost them */
8578 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
8579 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
8581 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
8582 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
8583 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
8586 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
8587 && appData.drawRepeats > 1) {
8588 /* adjudicate after user-specified nr of repeats */
8589 int result = GameIsDrawn;
8590 char *details = "XBoard adjudication: repetition draw";
8591 if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
8592 // [HGM] xiangqi: check for forbidden perpetuals
8593 int m, ourPerpetual = 1, hisPerpetual = 1;
8594 for(m=forwardMostMove; m>k; m-=2) {
8595 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
8596 ourPerpetual = 0; // the current mover did not always check
8597 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
8598 hisPerpetual = 0; // the opponent did not always check
8600 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
8601 ourPerpetual, hisPerpetual);
8602 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
8603 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8604 details = "Xboard adjudication: perpetual checking";
8606 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
8607 break; // (or we would have caught him before). Abort repetition-checking loop.
8609 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
8610 if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
8612 details = "Xboard adjudication: repetition";
8614 } else // it must be XQ
8615 // Now check for perpetual chases
8616 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
8617 hisPerpetual = PerpetualChase(k, forwardMostMove);
8618 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
8619 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
8620 static char resdet[MSG_SIZ];
8621 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8623 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
8625 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
8626 break; // Abort repetition-checking loop.
8628 // if neither of us is checking or chasing all the time, or both are, it is draw
8630 if(engineOpponent) {
8631 SendToProgram("force\n", engineOpponent); // suppress reply
8632 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8634 GameEnds( result, details, GE_XBOARD );
8637 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
8638 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
8642 /* Now we test for 50-move draws. Determine ply count */
8643 count = forwardMostMove;
8644 /* look for last irreversble move */
8645 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
8647 /* if we hit starting position, add initial plies */
8648 if( count == backwardMostMove )
8649 count -= initialRulePlies;
8650 count = forwardMostMove - count;
8651 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
8652 // adjust reversible move counter for checks in Xiangqi
8653 int i = forwardMostMove - count, inCheck = 0, lastCheck;
8654 if(i < backwardMostMove) i = backwardMostMove;
8655 while(i <= forwardMostMove) {
8656 lastCheck = inCheck; // check evasion does not count
8657 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
8658 if(inCheck || lastCheck) count--; // check does not count
8662 if( count >= 100 && gameInfo.variant != VariantMakruk) // do not accept 50-move claims in Makruk
8663 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8664 /* this is used to judge if draw claims are legal */
8665 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
8666 if(engineOpponent) {
8667 SendToProgram("force\n", engineOpponent); // suppress reply
8668 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8670 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
8674 /* if draw offer is pending, treat it as a draw claim
8675 * when draw condition present, to allow engines a way to
8676 * claim draws before making their move to avoid a race
8677 * condition occurring after their move
8679 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
8681 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
8682 p = "Draw claim: 50-move rule";
8683 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
8684 p = "Draw claim: 3-fold repetition";
8685 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
8686 p = "Draw claim: insufficient mating material";
8687 if( p != NULL && canAdjudicate) {
8688 if(engineOpponent) {
8689 SendToProgram("force\n", engineOpponent); // suppress reply
8690 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8692 GameEnds( GameIsDrawn, p, GE_XBOARD );
8697 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
8698 if(engineOpponent) {
8699 SendToProgram("force\n", engineOpponent); // suppress reply
8700 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8702 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
8708 typedef int (CDECL *PPROBE_EGBB) (int player, int *piece, int *square);
8709 typedef int (CDECL *PLOAD_EGBB) (char *path, int cache_size, int load_options);
8710 static int egbbCode[] = { 6, 5, 4, 3, 2, 1 };
8715 int pieces[10], squares[10], cnt=0, r, f, res;
8717 static PPROBE_EGBB probeBB;
8718 if(!appData.testLegality) return 10;
8719 if(BOARD_HEIGHT != 8 || BOARD_RGHT-BOARD_LEFT != 8) return 12;
8720 if(gameInfo.holdingsSize && gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess) return 12;
8721 if(loaded == 2 && forwardMostMove < 2) loaded = 0; // retry on new game
8722 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8723 ChessSquare piece = boards[forwardMostMove][r][f];
8724 int black = (piece >= BlackPawn);
8725 int type = piece - black*BlackPawn;
8726 if(piece == EmptySquare) continue;
8727 if(type != WhiteKing && type > WhiteQueen) return 12; // unorthodox piece
8728 if(type == WhiteKing) type = WhiteQueen + 1;
8729 type = egbbCode[type];
8730 squares[cnt] = r*(BOARD_RGHT - BOARD_LEFT) + f - BOARD_LEFT;
8731 pieces[cnt] = type + black*6;
8732 if(++cnt > 5) return 11;
8734 pieces[cnt] = squares[cnt] = 0;
8736 if(loaded == 2) return 13; // loading failed before
8738 char *p, *path = strstr(appData.egtFormats, "scorpio:"), buf[MSG_SIZ];
8741 loaded = 2; // prepare for failure
8742 if(!path) return 13; // no egbb installed
8743 strncpy(buf, path + 8, MSG_SIZ);
8744 if(p = strchr(buf, ',')) *p = NULLCHAR; else p = buf + strlen(buf);
8745 snprintf(p, MSG_SIZ - strlen(buf), "%c%s", SLASH, EGBB_NAME);
8746 lib = LoadLibrary(buf);
8747 if(!lib) { DisplayError(_("could not load EGBB library"), 0); return 13; }
8748 loadBB = (PLOAD_EGBB) GetProcAddress(lib, "load_egbb_xmen");
8749 probeBB = (PPROBE_EGBB) GetProcAddress(lib, "probe_egbb_xmen");
8750 if(!loadBB || !probeBB) { DisplayError(_("wrong EGBB version"), 0); return 13; }
8751 p[1] = NULLCHAR; loadBB(buf, 64*1028, 2); // 2 = SMART_LOAD
8752 loaded = 1; // success!
8754 res = probeBB(forwardMostMove & 1, pieces, squares);
8755 return res > 0 ? 1 : res < 0 ? -1 : 0;
8759 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8760 { // [HGM] book: this routine intercepts moves to simulate book replies
8761 char *bookHit = NULL;
8763 if(cps->drawDepth && BitbaseProbe() == 0) { // [HG} egbb: reduce depth in drawn position
8765 snprintf(buf, MSG_SIZ, "sd %d\n", cps->drawDepth);
8766 SendToProgram(buf, cps);
8768 //first determine if the incoming move brings opponent into his book
8769 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8770 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8771 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8772 if(bookHit != NULL && !cps->bookSuspend) {
8773 // make sure opponent is not going to reply after receiving move to book position
8774 SendToProgram("force\n", cps);
8775 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8777 if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
8778 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8779 // now arrange restart after book miss
8781 // after a book hit we never send 'go', and the code after the call to this routine
8782 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8783 char buf[MSG_SIZ], *move = bookHit;
8785 int fromX, fromY, toX, toY;
8789 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8790 &fromX, &fromY, &toX, &toY, &promoChar)) {
8791 (void) CoordsToAlgebraic(boards[forwardMostMove],
8792 PosFlags(forwardMostMove),
8793 fromY, fromX, toY, toX, promoChar, move);
8795 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8799 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8800 SendToProgram(buf, cps);
8801 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8802 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8803 SendToProgram("go\n", cps);
8804 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8805 } else { // 'go' might be sent based on 'firstMove' after this routine returns
8806 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8807 SendToProgram("go\n", cps);
8808 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8810 return bookHit; // notify caller of hit, so it can take action to send move to opponent
8814 LoadError (char *errmess, ChessProgramState *cps)
8815 { // unloads engine and switches back to -ncp mode if it was first
8816 if(cps->initDone) return FALSE;
8817 cps->isr = NULL; // this should suppress further error popups from breaking pipes
8818 DestroyChildProcess(cps->pr, 9 ); // just to be sure
8821 appData.noChessProgram = TRUE;
8822 gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8823 gameMode = BeginningOfGame; ModeHighlight();
8826 if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8827 DisplayMessage("", ""); // erase waiting message
8828 if(errmess) DisplayError(errmess, 0); // announce reason, if given
8833 ChessProgramState *savedState;
8835 DeferredBookMove (void)
8837 if(savedState->lastPing != savedState->lastPong)
8838 ScheduleDelayedEvent(DeferredBookMove, 10);
8840 HandleMachineMove(savedMessage, savedState);
8843 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8844 static ChessProgramState *stalledEngine;
8845 static char stashedInputMove[MSG_SIZ], abortEngineThink;
8848 HandleMachineMove (char *message, ChessProgramState *cps)
8850 static char firstLeg[20], legs;
8851 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8852 char realname[MSG_SIZ];
8853 int fromX, fromY, toX, toY;
8855 char promoChar, roar;
8860 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8861 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8862 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8863 DisplayError(_("Invalid pairing from pairing engine"), 0);
8866 pairingReceived = 1;
8868 return; // Skim the pairing messages here.
8871 oldError = cps->userError; cps->userError = 0;
8873 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8875 * Kludge to ignore BEL characters
8877 while (*message == '\007') message++;
8880 * [HGM] engine debug message: ignore lines starting with '#' character
8882 if(cps->debug && *message == '#') return;
8885 * Look for book output
8887 if (cps == &first && bookRequested) {
8888 if (message[0] == '\t' || message[0] == ' ') {
8889 /* Part of the book output is here; append it */
8890 strcat(bookOutput, message);
8891 strcat(bookOutput, " \n");
8893 } else if (bookOutput[0] != NULLCHAR) {
8894 /* All of book output has arrived; display it */
8895 char *p = bookOutput;
8896 while (*p != NULLCHAR) {
8897 if (*p == '\t') *p = ' ';
8900 DisplayInformation(bookOutput);
8901 bookRequested = FALSE;
8902 /* Fall through to parse the current output */
8907 * Look for machine move.
8909 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8910 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8912 if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8913 if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8914 safeStrCpy(stashedInputMove, message, MSG_SIZ);
8915 stalledEngine = cps;
8916 if(appData.ponderNextMove) { // bring opponent out of ponder
8917 if(gameMode == TwoMachinesPlay) {
8918 if(cps->other->pause)
8919 PauseEngine(cps->other);
8921 SendToProgram("easy\n", cps->other);
8930 /* This method is only useful on engines that support ping */
8931 if(abortEngineThink) {
8932 if (appData.debugMode) {
8933 fprintf(debugFP, "Undoing move from aborted think of %s\n", cps->which);
8935 SendToProgram("undo\n", cps);
8939 if (cps->lastPing != cps->lastPong) {
8940 /* Extra move from before last new; ignore */
8941 if (appData.debugMode) {
8942 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8949 int machineWhite = FALSE;
8952 case BeginningOfGame:
8953 /* Extra move from before last reset; ignore */
8954 if (appData.debugMode) {
8955 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8962 /* Extra move after we tried to stop. The mode test is
8963 not a reliable way of detecting this problem, but it's
8964 the best we can do on engines that don't support ping.
8966 if (appData.debugMode) {
8967 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8968 cps->which, gameMode);
8970 SendToProgram("undo\n", cps);
8973 case MachinePlaysWhite:
8974 case IcsPlayingWhite:
8975 machineWhite = TRUE;
8978 case MachinePlaysBlack:
8979 case IcsPlayingBlack:
8980 machineWhite = FALSE;
8983 case TwoMachinesPlay:
8984 machineWhite = (cps->twoMachinesColor[0] == 'w');
8987 if (WhiteOnMove(forwardMostMove) != machineWhite) {
8988 if (appData.debugMode) {
8990 "Ignoring move out of turn by %s, gameMode %d"
8991 ", forwardMost %d\n",
8992 cps->which, gameMode, forwardMostMove);
8998 if(cps->alphaRank) AlphaRank(machineMove, 4);
9000 // [HGM] lion: (some very limited) support for Alien protocol
9001 killX = killY = kill2X = kill2Y = -1;
9002 if(machineMove[strlen(machineMove)-1] == ',') { // move ends in coma: non-final leg of composite move
9003 if(legs++) return; // middle leg contains only redundant info, ignore (but count it)
9004 safeStrCpy(firstLeg, machineMove, 20); // just remember it for processing when second leg arrives
9007 if(p = strchr(machineMove, ',')) { // we got both legs in one (happens on book move)
9008 char *q = strchr(p+1, ','); // second comma?
9009 safeStrCpy(firstLeg, machineMove, 20); // kludge: fake we received the first leg earlier, and clip it off
9010 if(q) legs = 2, p = q; else legs = 1; // with 3-leg move we clipof first two legs!
9011 safeStrCpy(machineMove, firstLeg + (p - machineMove) + 1, 20);
9013 if(firstLeg[0]) { // there was a previous leg;
9014 // only support case where same piece makes two step
9015 char buf[20], *p = machineMove+1, *q = buf+1, f;
9016 safeStrCpy(buf, machineMove, 20);
9017 while(isdigit(*q)) q++; // find start of to-square
9018 safeStrCpy(machineMove, firstLeg, 20);
9019 while(isdigit(*p)) p++; // to-square of first leg (which is now copied to machineMove)
9020 if(legs == 2) sscanf(p, "%c%d", &f, &kill2Y), kill2X = f - AAA, kill2Y -= ONE - '0'; // in 3-leg move 2nd kill is to-sqr of 1st leg
9021 else if(*p == *buf) // if first-leg to not equal to second-leg from first leg says unmodified (assume it is King move of castling)
9022 safeStrCpy(p, q, 20); // glue to-square of second leg to from-square of first, to process over-all move
9023 sscanf(buf, "%c%d", &f, &killY); killX = f - AAA; killY -= ONE - '0'; // pass intermediate square to MakeMove in global
9024 firstLeg[0] = NULLCHAR; legs = 0;
9027 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
9028 &fromX, &fromY, &toX, &toY, &promoChar)) {
9029 /* Machine move could not be parsed; ignore it. */
9030 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
9031 machineMove, _(cps->which));
9032 DisplayMoveError(buf1);
9033 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c via %c%c, %c%c) res=%d",
9034 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, killX+AAA, killY+ONE, kill2X+AAA, kill2Y+ONE, moveType);
9035 if (gameMode == TwoMachinesPlay) {
9036 GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9042 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
9043 /* So we have to redo legality test with true e.p. status here, */
9044 /* to make sure an illegal e.p. capture does not slip through, */
9045 /* to cause a forfeit on a justified illegal-move complaint */
9046 /* of the opponent. */
9047 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
9049 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
9050 fromY, fromX, toY, toX, promoChar);
9051 if(moveType == IllegalMove) {
9052 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
9053 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
9054 GameEnds(cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9057 } else if(!appData.fischerCastling)
9058 /* [HGM] Kludge to handle engines that send FRC-style castling
9059 when they shouldn't (like TSCP-Gothic) */
9061 case WhiteASideCastleFR:
9062 case BlackASideCastleFR:
9064 currentMoveString[2]++;
9066 case WhiteHSideCastleFR:
9067 case BlackHSideCastleFR:
9069 currentMoveString[2]--;
9071 default: ; // nothing to do, but suppresses warning of pedantic compilers
9074 hintRequested = FALSE;
9075 lastHint[0] = NULLCHAR;
9076 bookRequested = FALSE;
9077 /* Program may be pondering now */
9078 cps->maybeThinking = TRUE;
9079 if (cps->sendTime == 2) cps->sendTime = 1;
9080 if (cps->offeredDraw) cps->offeredDraw--;
9082 /* [AS] Save move info*/
9083 pvInfoList[ forwardMostMove ].score = programStats.score;
9084 pvInfoList[ forwardMostMove ].depth = programStats.depth;
9085 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
9087 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
9089 /* Test suites abort the 'game' after one move */
9090 if(*appData.finger) {
9092 char *fen = PositionToFEN(backwardMostMove, NULL, 0); // no counts in EPD
9093 if(!f) f = fopen(appData.finger, "w");
9094 if(f) fprintf(f, "%s bm %s;\n", fen, parseList[backwardMostMove]), fflush(f);
9095 else { DisplayFatalError("Bad output file", errno, 0); return; }
9097 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9100 if(solvingTime >= 0) {
9101 snprintf(buf1, MSG_SIZ, "%d. %4.2fs: %s ", matchGame, solvingTime/100., parseList[backwardMostMove]);
9102 totalTime += solvingTime; first.matchWins++; solvingTime = -1;
9104 snprintf(buf1, MSG_SIZ, "%d. %s?%s ", matchGame, parseList[backwardMostMove], solvingTime == -2 ? " ???" : "");
9105 if(solvingTime == -2) second.matchWins++;
9107 OutputKibitz(2, buf1);
9108 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9111 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
9112 if( gameMode == TwoMachinesPlay && appData.adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
9115 while( count < adjudicateLossPlies ) {
9116 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
9119 score = -score; /* Flip score for winning side */
9122 if( score > appData.adjudicateLossThreshold ) {
9129 if( count >= adjudicateLossPlies ) {
9130 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9132 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
9133 "Xboard adjudication",
9140 if(Adjudicate(cps)) {
9141 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9142 return; // [HGM] adjudicate: for all automatic game ends
9146 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
9148 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
9149 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
9151 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
9153 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
9155 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
9156 char buf[3*MSG_SIZ];
9158 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
9159 programStats.score / 100.,
9161 programStats.time / 100.,
9162 (unsigned int)programStats.nodes,
9163 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
9164 programStats.movelist);
9170 /* [AS] Clear stats for next move */
9171 ClearProgramStats();
9172 thinkOutput[0] = NULLCHAR;
9173 hiddenThinkOutputState = 0;
9176 if (gameMode == TwoMachinesPlay) {
9177 /* [HGM] relaying draw offers moved to after reception of move */
9178 /* and interpreting offer as claim if it brings draw condition */
9179 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
9180 SendToProgram("draw\n", cps->other);
9182 if (cps->other->sendTime) {
9183 SendTimeRemaining(cps->other,
9184 cps->other->twoMachinesColor[0] == 'w');
9186 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
9187 if (firstMove && !bookHit) {
9189 if (cps->other->useColors) {
9190 SendToProgram(cps->other->twoMachinesColor, cps->other);
9192 SendToProgram("go\n", cps->other);
9194 cps->other->maybeThinking = TRUE;
9197 roar = (killX >= 0 && IS_LION(boards[forwardMostMove][toY][toX]));
9199 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
9201 if (!pausing && appData.ringBellAfterMoves) {
9202 if(!roar) RingBell();
9206 * Reenable menu items that were disabled while
9207 * machine was thinking
9209 if (gameMode != TwoMachinesPlay)
9210 SetUserThinkingEnables();
9212 // [HGM] book: after book hit opponent has received move and is now in force mode
9213 // force the book reply into it, and then fake that it outputted this move by jumping
9214 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
9216 static char bookMove[MSG_SIZ]; // a bit generous?
9218 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
9219 strcat(bookMove, bookHit);
9222 programStats.nodes = programStats.depth = programStats.time =
9223 programStats.score = programStats.got_only_move = 0;
9224 sprintf(programStats.movelist, "%s (xbook)", bookHit);
9226 if(cps->lastPing != cps->lastPong) {
9227 savedMessage = message; // args for deferred call
9229 ScheduleDelayedEvent(DeferredBookMove, 10);
9238 /* Set special modes for chess engines. Later something general
9239 * could be added here; for now there is just one kludge feature,
9240 * needed because Crafty 15.10 and earlier don't ignore SIGINT
9241 * when "xboard" is given as an interactive command.
9243 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
9244 cps->useSigint = FALSE;
9245 cps->useSigterm = FALSE;
9247 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
9248 ParseFeatures(message+8, cps); if(tryNr < 3) tryNr = 3;
9249 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
9252 if (!strncmp(message, "setup ", 6) &&
9253 (!appData.testLegality || gameInfo.variant == VariantFairy || gameInfo.variant == VariantUnknown ||
9254 NonStandardBoardSize(gameInfo.variant, gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize))
9255 ) { // [HGM] allow first engine to define opening position
9256 int dummy, w, h, hand, s=6; char buf[MSG_SIZ], varName[MSG_SIZ];
9257 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
9259 if(sscanf(message, "setup (%s", buf) == 1) {
9260 s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTableEsc(pieceToChar, buf, SUFFIXES);
9261 ASSIGN(appData.pieceToCharTable, buf);
9263 dummy = sscanf(message+s, "%dx%d+%d_%s", &w, &h, &hand, varName);
9265 while(message[s] && message[s++] != ' ');
9266 if(BOARD_HEIGHT != h || BOARD_WIDTH != w + 4*(hand != 0) || gameInfo.holdingsSize != hand ||
9267 dummy == 4 && gameInfo.variant != StringToVariant(varName) ) { // engine wants to change board format or variant
9268 // if(hand <= h) deadRanks = 0; else deadRanks = hand - h, h = hand; // adapt board to over-sized holdings
9269 if(hand > h) handSize = hand; else handSize = h;
9270 appData.NrFiles = w; appData.NrRanks = h; appData.holdingsSize = hand;
9271 if(dummy == 4) gameInfo.variant = StringToVariant(varName); // parent variant
9272 InitPosition(1); // calls InitDrawingSizes to let new parameters take effect
9273 if(*buf) SetCharTableEsc(pieceToChar, buf, SUFFIXES); // do again, for it was spoiled by InitPosition
9274 startedFromSetupPosition = FALSE;
9277 if(startedFromSetupPosition) return;
9278 ParseFEN(boards[0], &dummy, message+s, FALSE);
9279 DrawPosition(TRUE, boards[0]);
9280 CopyBoard(initialPosition, boards[0]);
9281 startedFromSetupPosition = TRUE;
9284 if(sscanf(message, "piece %s %s", buf2, buf1) == 2) {
9285 ChessSquare piece = WhitePawn;
9286 char *p=message+6, *q, *s = SUFFIXES, ID = *p, promoted = 0;
9287 if(*p == '+') promoted++, ID = *++p;
9288 if(q = strchr(s, p[1])) ID += 64*(q - s + 1), p++;
9289 piece = CharToPiece(ID & 255); if(promoted) piece = CHUPROMOTED(piece);
9290 if(cps != &first || appData.testLegality && *engineVariant == NULLCHAR
9291 /* always accept definition of */ && piece != WhiteFalcon && piece != BlackFalcon
9292 /* wild-card pieces. */ && piece != WhiteCobra && piece != BlackCobra
9293 /* For variants we don't have */ && gameInfo.variant != VariantBerolina
9294 /* correct rules for, we cannot */ && gameInfo.variant != VariantCylinder
9295 /* enforce legality on our own! */ && gameInfo.variant != VariantUnknown
9296 && gameInfo.variant != VariantGreat
9297 && gameInfo.variant != VariantFairy ) return;
9298 if(piece < EmptySquare) {
9300 ASSIGN(pieceDesc[piece], buf1);
9301 if((ID & 32) == 0 && p[1] == '&') { ASSIGN(pieceDesc[WHITE_TO_BLACK piece], buf1); }
9305 if(!appData.testLegality && sscanf(message, "choice %s", promoRestrict) == 1) {
9307 LeftClick(Press, 0, 0); // finish the click that was interrupted
9308 } else if(promoSweep != EmptySquare) {
9309 promoSweep = CharToPiece(currentMove&1 ? ToLower(*promoRestrict) : ToUpper(*promoRestrict));
9310 if(strlen(promoRestrict) > 1) Sweep(0);
9314 /* [HGM] Allow engine to set up a position. Don't ask me why one would
9315 * want this, I was asked to put it in, and obliged.
9317 if (!strncmp(message, "setboard ", 9)) {
9318 Board initial_position;
9320 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
9322 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9, FALSE)) {
9323 DisplayError(_("Bad FEN received from engine"), 0);
9327 CopyBoard(boards[0], initial_position);
9328 initialRulePlies = FENrulePlies;
9329 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
9330 else gameMode = MachinePlaysBlack;
9331 DrawPosition(FALSE, boards[currentMove]);
9337 * Look for communication commands
9339 if (!strncmp(message, "telluser ", 9)) {
9340 if(message[9] == '\\' && message[10] == '\\')
9341 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
9343 DisplayNote(message + 9);
9346 if (!strncmp(message, "tellusererror ", 14)) {
9348 if(message[14] == '\\' && message[15] == '\\')
9349 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
9351 DisplayError(message + 14, 0);
9354 if (!strncmp(message, "tellopponent ", 13)) {
9355 if (appData.icsActive) {
9357 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
9361 DisplayNote(message + 13);
9365 if (!strncmp(message, "tellothers ", 11)) {
9366 if (appData.icsActive) {
9368 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
9371 } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
9374 if (!strncmp(message, "tellall ", 8)) {
9375 if (appData.icsActive) {
9377 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
9381 DisplayNote(message + 8);
9385 if (strncmp(message, "warning", 7) == 0) {
9386 /* Undocumented feature, use tellusererror in new code */
9387 DisplayError(message, 0);
9390 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
9391 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
9392 strcat(realname, " query");
9393 AskQuestion(realname, buf2, buf1, cps->pr);
9396 /* Commands from the engine directly to ICS. We don't allow these to be
9397 * sent until we are logged on. Crafty kibitzes have been known to
9398 * interfere with the login process.
9401 if (!strncmp(message, "tellics ", 8)) {
9402 SendToICS(message + 8);
9406 if (!strncmp(message, "tellicsnoalias ", 15)) {
9407 SendToICS(ics_prefix);
9408 SendToICS(message + 15);
9412 /* The following are for backward compatibility only */
9413 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
9414 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
9415 SendToICS(ics_prefix);
9421 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
9422 if(initPing == cps->lastPong) {
9423 if(gameInfo.variant == VariantUnknown) {
9424 DisplayError(_("Engine did not send setup for non-standard variant"), 0);
9425 *engineVariant = NULLCHAR; ASSIGN(appData.variant, "normal"); // back to normal as error recovery?
9426 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9430 if(cps->lastPing == cps->lastPong && abortEngineThink) {
9431 abortEngineThink = FALSE;
9432 DisplayMessage("", "");
9437 if(!strncmp(message, "highlight ", 10)) {
9438 if(appData.testLegality && !*engineVariant && appData.markers) return;
9439 MarkByFEN(message+10); // [HGM] alien: allow engine to mark board squares
9442 if(!strncmp(message, "click ", 6)) {
9443 char f, c=0; int x, y; // [HGM] alien: allow engine to finish user moves (i.e. engine-driven one-click moving)
9444 if(appData.testLegality || !appData.oneClick) return;
9445 sscanf(message+6, "%c%d%c", &f, &y, &c);
9446 x = f - 'a' + BOARD_LEFT, y -= ONE - '0';
9447 if(flipView) x = BOARD_WIDTH-1 - x; else y = BOARD_HEIGHT-1 - y;
9448 x = x*squareSize + (x+1)*lineGap + squareSize/2;
9449 y = y*squareSize + (y+1)*lineGap + squareSize/2;
9450 f = first.highlight; first.highlight = 0; // kludge to suppress lift/put in response to own clicks
9451 if(lastClickType == Press) // if button still down, fake release on same square, to be ready for next click
9452 LeftClick(Release, lastLeftX, lastLeftY);
9453 controlKey = (c == ',');
9454 LeftClick(Press, x, y);
9455 LeftClick(Release, x, y);
9456 first.highlight = f;
9459 if(strncmp(message, "uciok", 5) == 0) { // response to "uci" probe
9460 appData.isUCI[0] = isUCI = 1;
9461 ReplaceEngine(&first, 0); // retry install as UCI
9465 * If the move is illegal, cancel it and redraw the board.
9466 * Also deal with other error cases. Matching is rather loose
9467 * here to accommodate engines written before the spec.
9469 if (strncmp(message + 1, "llegal move", 11) == 0 ||
9470 strncmp(message, "Error", 5) == 0) {
9471 if (StrStr(message, "name") ||
9472 StrStr(message, "rating") || StrStr(message, "?") ||
9473 StrStr(message, "result") || StrStr(message, "board") ||
9474 StrStr(message, "bk") || StrStr(message, "computer") ||
9475 StrStr(message, "variant") || StrStr(message, "hint") ||
9476 StrStr(message, "random") || StrStr(message, "depth") ||
9477 StrStr(message, "accepted")) {
9480 if (StrStr(message, "protover")) {
9481 /* Program is responding to input, so it's apparently done
9482 initializing, and this error message indicates it is
9483 protocol version 1. So we don't need to wait any longer
9484 for it to initialize and send feature commands. */
9485 FeatureDone(cps, 1);
9486 cps->protocolVersion = 1;
9489 cps->maybeThinking = FALSE;
9491 if (StrStr(message, "draw")) {
9492 /* Program doesn't have "draw" command */
9493 cps->sendDrawOffers = 0;
9496 if (cps->sendTime != 1 &&
9497 (StrStr(message, "time") || StrStr(message, "otim"))) {
9498 /* Program apparently doesn't have "time" or "otim" command */
9502 if (StrStr(message, "analyze")) {
9503 cps->analysisSupport = FALSE;
9504 cps->analyzing = FALSE;
9505 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
9506 EditGameEvent(); // [HGM] try to preserve loaded game
9507 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
9508 DisplayError(buf2, 0);
9511 if (StrStr(message, "(no matching move)st")) {
9512 /* Special kludge for GNU Chess 4 only */
9513 cps->stKludge = TRUE;
9514 SendTimeControl(cps, movesPerSession, timeControl,
9515 timeIncrement, appData.searchDepth,
9519 if (StrStr(message, "(no matching move)sd")) {
9520 /* Special kludge for GNU Chess 4 only */
9521 cps->sdKludge = TRUE;
9522 SendTimeControl(cps, movesPerSession, timeControl,
9523 timeIncrement, appData.searchDepth,
9527 if (!StrStr(message, "llegal")) {
9530 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9531 gameMode == IcsIdle) return;
9532 if (forwardMostMove <= backwardMostMove) return;
9533 if (pausing) PauseEvent();
9534 if(appData.forceIllegal) {
9535 // [HGM] illegal: machine refused move; force position after move into it
9536 SendToProgram("force\n", cps);
9537 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
9538 // we have a real problem now, as SendBoard will use the a2a3 kludge
9539 // when black is to move, while there might be nothing on a2 or black
9540 // might already have the move. So send the board as if white has the move.
9541 // But first we must change the stm of the engine, as it refused the last move
9542 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
9543 if(WhiteOnMove(forwardMostMove)) {
9544 SendToProgram("a7a6\n", cps); // for the engine black still had the move
9545 SendBoard(cps, forwardMostMove); // kludgeless board
9547 SendToProgram("a2a3\n", cps); // for the engine white still had the move
9548 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9549 SendBoard(cps, forwardMostMove+1); // kludgeless board
9551 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
9552 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
9553 gameMode == TwoMachinesPlay)
9554 SendToProgram("go\n", cps);
9557 if (gameMode == PlayFromGameFile) {
9558 /* Stop reading this game file */
9559 gameMode = EditGame;
9562 /* [HGM] illegal-move claim should forfeit game when Xboard */
9563 /* only passes fully legal moves */
9564 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
9565 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9566 "False illegal-move claim", GE_XBOARD );
9567 return; // do not take back move we tested as valid
9569 currentMove = forwardMostMove-1;
9570 DisplayMove(currentMove-1); /* before DisplayMoveError */
9571 SwitchClocks(forwardMostMove-1); // [HGM] race
9572 DisplayBothClocks();
9573 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
9574 parseList[currentMove], _(cps->which));
9575 DisplayMoveError(buf1);
9576 DrawPosition(FALSE, boards[currentMove]);
9578 SetUserThinkingEnables();
9581 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
9582 /* Program has a broken "time" command that
9583 outputs a string not ending in newline.
9587 if (cps->pseudo) { // [HGM] pseudo-engine, granted unusual powers
9588 if (sscanf(message, "wtime %ld\n", &whiteTimeRemaining) == 1 || // adjust clock times
9589 sscanf(message, "btime %ld\n", &blackTimeRemaining) == 1 ) return;
9593 * If chess program startup fails, exit with an error message.
9594 * Attempts to recover here are futile. [HGM] Well, we try anyway
9596 if ((StrStr(message, "unknown host") != NULL)
9597 || (StrStr(message, "No remote directory") != NULL)
9598 || (StrStr(message, "not found") != NULL)
9599 || (StrStr(message, "No such file") != NULL)
9600 || (StrStr(message, "can't alloc") != NULL)
9601 || (StrStr(message, "Permission denied") != NULL)) {
9603 cps->maybeThinking = FALSE;
9604 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
9605 _(cps->which), cps->program, cps->host, message);
9606 RemoveInputSource(cps->isr);
9607 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
9608 if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
9609 if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
9615 * Look for hint output
9617 if (sscanf(message, "Hint: %s", buf1) == 1) {
9618 if (cps == &first && hintRequested) {
9619 hintRequested = FALSE;
9620 if (ParseOneMove(buf1, forwardMostMove, &moveType,
9621 &fromX, &fromY, &toX, &toY, &promoChar)) {
9622 (void) CoordsToAlgebraic(boards[forwardMostMove],
9623 PosFlags(forwardMostMove),
9624 fromY, fromX, toY, toX, promoChar, buf1);
9625 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
9626 DisplayInformation(buf2);
9628 /* Hint move could not be parsed!? */
9629 snprintf(buf2, sizeof(buf2),
9630 _("Illegal hint move \"%s\"\nfrom %s chess program"),
9631 buf1, _(cps->which));
9632 DisplayError(buf2, 0);
9635 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
9641 * Ignore other messages if game is not in progress
9643 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9644 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
9647 * look for win, lose, draw, or draw offer
9649 if (strncmp(message, "1-0", 3) == 0) {
9650 char *p, *q, *r = "";
9651 p = strchr(message, '{');
9659 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
9661 } else if (strncmp(message, "0-1", 3) == 0) {
9662 char *p, *q, *r = "";
9663 p = strchr(message, '{');
9671 /* Kludge for Arasan 4.1 bug */
9672 if (strcmp(r, "Black resigns") == 0) {
9673 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
9676 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
9678 } else if (strncmp(message, "1/2", 3) == 0) {
9679 char *p, *q, *r = "";
9680 p = strchr(message, '{');
9689 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
9692 } else if (strncmp(message, "White resign", 12) == 0) {
9693 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9695 } else if (strncmp(message, "Black resign", 12) == 0) {
9696 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9698 } else if (strncmp(message, "White matches", 13) == 0 ||
9699 strncmp(message, "Black matches", 13) == 0 ) {
9700 /* [HGM] ignore GNUShogi noises */
9702 } else if (strncmp(message, "White", 5) == 0 &&
9703 message[5] != '(' &&
9704 StrStr(message, "Black") == NULL) {
9705 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9707 } else if (strncmp(message, "Black", 5) == 0 &&
9708 message[5] != '(') {
9709 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9711 } else if (strcmp(message, "resign") == 0 ||
9712 strcmp(message, "computer resigns") == 0) {
9714 case MachinePlaysBlack:
9715 case IcsPlayingBlack:
9716 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
9718 case MachinePlaysWhite:
9719 case IcsPlayingWhite:
9720 GameEnds(BlackWins, "White resigns", GE_ENGINE);
9722 case TwoMachinesPlay:
9723 if (cps->twoMachinesColor[0] == 'w')
9724 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9726 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9733 } else if (strncmp(message, "opponent mates", 14) == 0) {
9735 case MachinePlaysBlack:
9736 case IcsPlayingBlack:
9737 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9739 case MachinePlaysWhite:
9740 case IcsPlayingWhite:
9741 GameEnds(BlackWins, "Black mates", GE_ENGINE);
9743 case TwoMachinesPlay:
9744 if (cps->twoMachinesColor[0] == 'w')
9745 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9747 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9754 } else if (strncmp(message, "computer mates", 14) == 0) {
9756 case MachinePlaysBlack:
9757 case IcsPlayingBlack:
9758 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
9760 case MachinePlaysWhite:
9761 case IcsPlayingWhite:
9762 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9764 case TwoMachinesPlay:
9765 if (cps->twoMachinesColor[0] == 'w')
9766 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9768 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9775 } else if (strncmp(message, "checkmate", 9) == 0) {
9776 if (WhiteOnMove(forwardMostMove)) {
9777 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9779 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9782 } else if (strstr(message, "Draw") != NULL ||
9783 strstr(message, "game is a draw") != NULL) {
9784 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
9786 } else if (strstr(message, "offer") != NULL &&
9787 strstr(message, "draw") != NULL) {
9789 if (appData.zippyPlay && first.initDone) {
9790 /* Relay offer to ICS */
9791 SendToICS(ics_prefix);
9792 SendToICS("draw\n");
9795 cps->offeredDraw = 2; /* valid until this engine moves twice */
9796 if (gameMode == TwoMachinesPlay) {
9797 if (cps->other->offeredDraw) {
9798 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9799 /* [HGM] in two-machine mode we delay relaying draw offer */
9800 /* until after we also have move, to see if it is really claim */
9802 } else if (gameMode == MachinePlaysWhite ||
9803 gameMode == MachinePlaysBlack) {
9804 if (userOfferedDraw) {
9805 DisplayInformation(_("Machine accepts your draw offer"));
9806 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9808 DisplayInformation(_("Machine offers a draw.\nSelect Action / Draw to accept."));
9815 * Look for thinking output
9817 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
9818 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9820 int plylev, mvleft, mvtot, curscore, time;
9821 char mvname[MOVE_LEN];
9825 int prefixHint = FALSE;
9826 mvname[0] = NULLCHAR;
9829 case MachinePlaysBlack:
9830 case IcsPlayingBlack:
9831 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9833 case MachinePlaysWhite:
9834 case IcsPlayingWhite:
9835 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9840 case IcsObserving: /* [DM] icsEngineAnalyze */
9841 if (!appData.icsEngineAnalyze) ignore = TRUE;
9843 case TwoMachinesPlay:
9844 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
9854 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
9857 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9858 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
9859 char score_buf[MSG_SIZ];
9861 if(nodes>>32 == u64Const(0xFFFFFFFF)) // [HGM] negative node count read
9862 nodes += u64Const(0x100000000);
9864 if (plyext != ' ' && plyext != '\t') {
9868 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9869 if( cps->scoreIsAbsolute &&
9870 ( gameMode == MachinePlaysBlack ||
9871 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
9872 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
9873 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
9874 !WhiteOnMove(currentMove)
9877 curscore = -curscore;
9880 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
9882 if(*bestMove) { // rememer time best EPD move was first found
9883 int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
9884 ChessMove mt; char *p = bestMove;
9885 int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
9887 while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
9888 if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
9889 solvingTime = (solvingTime < 0 ? time : solvingTime);
9893 while(*p && *p != ' ') p++;
9894 while(*p == ' ') p++;
9896 if(!solved) solvingTime = -1;
9898 if(*avoidMove && !solved) {
9899 int ff1, tf1, fr1, tr1, ff2, tf2, fr2, tr2; char pp1, pp2;
9900 ChessMove mt; char *p = avoidMove, solved = 1;
9901 int ok = ParseOneMove(pv, forwardMostMove, &mt, &ff2, &fr2, &tf2, &tr2, &pp2);
9902 while(ok && *p && ParseOneMove(p, forwardMostMove, &mt, &ff1, &fr1, &tf1, &tr1, &pp1)) {
9903 if(ff1==ff2 && fr1==fr2 && tf1==tf2 && tr1==tr2 && pp1==pp2) {
9904 solved = 0; solvingTime = -2;
9907 while(*p && *p != ' ') p++;
9908 while(*p == ' ') p++;
9910 if(solved && !*bestMove) solvingTime = (solvingTime < 0 ? time : solvingTime);
9913 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
9916 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
9917 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
9918 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
9919 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
9920 if(f = fopen(buf, "w")) { // export PV to applicable PV file
9921 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
9925 /* TRANSLATORS: PV = principal variation, the variation the chess engine thinks is the best for everyone */
9926 DisplayError(_("failed writing PV"), 0);
9929 tempStats.depth = plylev;
9930 tempStats.nodes = nodes;
9931 tempStats.time = time;
9932 tempStats.score = curscore;
9933 tempStats.got_only_move = 0;
9935 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
9938 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
9939 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
9940 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
9941 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
9942 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
9943 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
9944 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
9945 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
9948 /* Buffer overflow protection */
9949 if (pv[0] != NULLCHAR) {
9950 if (strlen(pv) >= sizeof(tempStats.movelist)
9951 && appData.debugMode) {
9953 "PV is too long; using the first %u bytes.\n",
9954 (unsigned) sizeof(tempStats.movelist) - 1);
9957 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9959 sprintf(tempStats.movelist, " no PV\n");
9962 if (tempStats.seen_stat) {
9963 tempStats.ok_to_send = 1;
9966 if (strchr(tempStats.movelist, '(') != NULL) {
9967 tempStats.line_is_book = 1;
9968 tempStats.nr_moves = 0;
9969 tempStats.moves_left = 0;
9971 tempStats.line_is_book = 0;
9974 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9975 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9977 SendProgramStatsToFrontend( cps, &tempStats );
9980 [AS] Protect the thinkOutput buffer from overflow... this
9981 is only useful if buf1 hasn't overflowed first!
9983 if((gameMode == AnalyzeMode && appData.whitePOV || appData.scoreWhite) && !WhiteOnMove(forwardMostMove)) curscore *= -1;
9984 if(curscore >= MATE_SCORE)
9985 snprintf(score_buf, MSG_SIZ, "#%d", curscore - MATE_SCORE);
9986 else if(curscore <= -MATE_SCORE)
9987 snprintf(score_buf, MSG_SIZ, "#%d", curscore + MATE_SCORE);
9989 snprintf(score_buf, MSG_SIZ, "%+.2f", ((double) curscore) / 100.0);
9990 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%s %s%s",
9992 (gameMode == TwoMachinesPlay ?
9993 ToUpper(cps->twoMachinesColor[0]) : ' '),
9995 prefixHint ? lastHint : "",
9996 prefixHint ? " " : "" );
9998 if( buf1[0] != NULLCHAR ) {
9999 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
10001 if( strlen(pv) > max_len ) {
10002 if( appData.debugMode) {
10003 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
10005 pv[max_len+1] = '\0';
10008 strcat( thinkOutput, pv);
10011 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
10012 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10013 DisplayMove(currentMove - 1);
10017 } else if ((p=StrStr(message, "(only move)")) != NULL) {
10018 /* crafty (9.25+) says "(only move) <move>"
10019 * if there is only 1 legal move
10021 sscanf(p, "(only move) %s", buf1);
10022 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
10023 sprintf(programStats.movelist, "%s (only move)", buf1);
10024 programStats.depth = 1;
10025 programStats.nr_moves = 1;
10026 programStats.moves_left = 1;
10027 programStats.nodes = 1;
10028 programStats.time = 1;
10029 programStats.got_only_move = 1;
10031 /* Not really, but we also use this member to
10032 mean "line isn't going to change" (Crafty
10033 isn't searching, so stats won't change) */
10034 programStats.line_is_book = 1;
10036 SendProgramStatsToFrontend( cps, &programStats );
10038 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
10039 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10040 DisplayMove(currentMove - 1);
10043 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
10044 &time, &nodes, &plylev, &mvleft,
10045 &mvtot, mvname) >= 5) {
10046 /* The stat01: line is from Crafty (9.29+) in response
10047 to the "." command */
10048 programStats.seen_stat = 1;
10049 cps->maybeThinking = TRUE;
10051 if (programStats.got_only_move || !appData.periodicUpdates)
10054 programStats.depth = plylev;
10055 programStats.time = time;
10056 programStats.nodes = nodes;
10057 programStats.moves_left = mvleft;
10058 programStats.nr_moves = mvtot;
10059 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
10060 programStats.ok_to_send = 1;
10061 programStats.movelist[0] = '\0';
10063 SendProgramStatsToFrontend( cps, &programStats );
10067 } else if (strncmp(message,"++",2) == 0) {
10068 /* Crafty 9.29+ outputs this */
10069 programStats.got_fail = 2;
10072 } else if (strncmp(message,"--",2) == 0) {
10073 /* Crafty 9.29+ outputs this */
10074 programStats.got_fail = 1;
10077 } else if (thinkOutput[0] != NULLCHAR &&
10078 strncmp(message, " ", 4) == 0) {
10079 unsigned message_len;
10082 while (*p && *p == ' ') p++;
10084 message_len = strlen( p );
10086 /* [AS] Avoid buffer overflow */
10087 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
10088 strcat(thinkOutput, " ");
10089 strcat(thinkOutput, p);
10092 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
10093 strcat(programStats.movelist, " ");
10094 strcat(programStats.movelist, p);
10097 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
10098 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
10099 DisplayMove(currentMove - 1);
10105 buf1[0] = NULLCHAR;
10107 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
10108 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
10110 ChessProgramStats cpstats;
10112 if (plyext != ' ' && plyext != '\t') {
10116 /* [AS] Negate score if machine is playing black and reporting absolute scores */
10117 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
10118 curscore = -curscore;
10121 cpstats.depth = plylev;
10122 cpstats.nodes = nodes;
10123 cpstats.time = time;
10124 cpstats.score = curscore;
10125 cpstats.got_only_move = 0;
10126 cpstats.movelist[0] = '\0';
10128 if (buf1[0] != NULLCHAR) {
10129 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
10132 cpstats.ok_to_send = 0;
10133 cpstats.line_is_book = 0;
10134 cpstats.nr_moves = 0;
10135 cpstats.moves_left = 0;
10137 SendProgramStatsToFrontend( cps, &cpstats );
10144 /* Parse a game score from the character string "game", and
10145 record it as the history of the current game. The game
10146 score is NOT assumed to start from the standard position.
10147 The display is not updated in any way.
10150 ParseGameHistory (char *game)
10152 ChessMove moveType;
10153 int fromX, fromY, toX, toY, boardIndex, mask;
10158 if (appData.debugMode)
10159 fprintf(debugFP, "Parsing game history: %s\n", game);
10161 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
10162 gameInfo.site = StrSave(appData.icsHost);
10163 gameInfo.date = PGNDate();
10164 gameInfo.round = StrSave("-");
10166 /* Parse out names of players */
10167 while (*game == ' ') game++;
10169 while (*game != ' ') *p++ = *game++;
10171 gameInfo.white = StrSave(buf);
10172 while (*game == ' ') game++;
10174 while (*game != ' ' && *game != '\n') *p++ = *game++;
10176 gameInfo.black = StrSave(buf);
10179 boardIndex = blackPlaysFirst ? 1 : 0;
10182 yyboardindex = boardIndex;
10183 moveType = (ChessMove) Myylex();
10184 switch (moveType) {
10185 case IllegalMove: /* maybe suicide chess, etc. */
10186 if (appData.debugMode) {
10187 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
10188 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10189 setbuf(debugFP, NULL);
10191 case WhitePromotion:
10192 case BlackPromotion:
10193 case WhiteNonPromotion:
10194 case BlackNonPromotion:
10197 case WhiteCapturesEnPassant:
10198 case BlackCapturesEnPassant:
10199 case WhiteKingSideCastle:
10200 case WhiteQueenSideCastle:
10201 case BlackKingSideCastle:
10202 case BlackQueenSideCastle:
10203 case WhiteKingSideCastleWild:
10204 case WhiteQueenSideCastleWild:
10205 case BlackKingSideCastleWild:
10206 case BlackQueenSideCastleWild:
10208 case WhiteHSideCastleFR:
10209 case WhiteASideCastleFR:
10210 case BlackHSideCastleFR:
10211 case BlackASideCastleFR:
10213 fromX = currentMoveString[0] - AAA;
10214 fromY = currentMoveString[1] - ONE;
10215 toX = currentMoveString[2] - AAA;
10216 toY = currentMoveString[3] - ONE;
10217 promoChar = currentMoveString[4];
10221 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
10222 fromX = moveType == WhiteDrop ?
10223 (int) CharToPiece(ToUpper(currentMoveString[0])) :
10224 (int) CharToPiece(ToLower(currentMoveString[0]));
10226 toX = currentMoveString[2] - AAA;
10227 toY = currentMoveString[3] - ONE;
10228 promoChar = NULLCHAR;
10230 case AmbiguousMove:
10232 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
10233 if (appData.debugMode) {
10234 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
10235 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10236 setbuf(debugFP, NULL);
10238 DisplayError(buf, 0);
10240 case ImpossibleMove:
10242 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
10243 if (appData.debugMode) {
10244 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
10245 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
10246 setbuf(debugFP, NULL);
10248 DisplayError(buf, 0);
10251 if (boardIndex < backwardMostMove) {
10252 /* Oops, gap. How did that happen? */
10253 DisplayError(_("Gap in move list"), 0);
10256 backwardMostMove = blackPlaysFirst ? 1 : 0;
10257 if (boardIndex > forwardMostMove) {
10258 forwardMostMove = boardIndex;
10262 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
10263 strcat(parseList[boardIndex-1], " ");
10264 strcat(parseList[boardIndex-1], yy_text);
10276 case GameUnfinished:
10277 if (gameMode == IcsExamining) {
10278 if (boardIndex < backwardMostMove) {
10279 /* Oops, gap. How did that happen? */
10282 backwardMostMove = blackPlaysFirst ? 1 : 0;
10285 gameInfo.result = moveType;
10286 p = strchr(yy_text, '{');
10287 if (p == NULL) p = strchr(yy_text, '(');
10290 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
10292 q = strchr(p, *p == '{' ? '}' : ')');
10293 if (q != NULL) *q = NULLCHAR;
10296 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10297 gameInfo.resultDetails = StrSave(p);
10300 if (boardIndex >= forwardMostMove &&
10301 !(gameMode == IcsObserving && ics_gamenum == -1)) {
10302 backwardMostMove = blackPlaysFirst ? 1 : 0;
10305 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
10306 fromY, fromX, toY, toX, promoChar,
10307 parseList[boardIndex]);
10308 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
10309 /* currentMoveString is set as a side-effect of yylex */
10310 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
10311 strcat(moveList[boardIndex], "\n");
10313 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
10314 mask = (WhiteOnMove(boardIndex) ? 0xFF : 0xFF00);
10315 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
10321 if(boards[boardIndex][CHECK_COUNT]) boards[boardIndex][CHECK_COUNT] -= mask & 0x101;
10322 if(!boards[boardIndex][CHECK_COUNT] || boards[boardIndex][CHECK_COUNT] & mask) {
10323 if(!IS_SHOGI(gameInfo.variant)) strcat(parseList[boardIndex - 1], "+");
10328 strcat(parseList[boardIndex - 1], "#");
10335 /* Apply a move to the given board */
10337 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
10339 ChessSquare captured = board[toY][toX], piece, pawn, king, killed, killed2; int p, rookX, oldEP, epRank, epFile, lastFile, lastRank, berolina = 0;
10340 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess ? 3 : 1;
10342 /* [HGM] compute & store e.p. status and castling rights for new position */
10343 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
10345 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
10346 oldEP = (signed char)board[EP_STATUS]; epRank = board[EP_RANK]; epFile = board[EP_FILE]; lastFile = board[LAST_TO] & 255,lastRank = board[LAST_TO] >> 8;
10347 board[EP_STATUS] = EP_NONE;
10348 board[EP_FILE] = board[EP_RANK] = 100, board[LAST_TO] = 0x4040;
10350 if (fromY == DROP_RANK) {
10351 /* must be first */
10352 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
10353 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
10356 piece = board[toY][toX] = (ChessSquare) fromX;
10358 // ChessSquare victim;
10361 if( killX >= 0 && killY >= 0 ) { // [HGM] lion: Lion trampled over something
10362 // victim = board[killY][killX],
10363 killed = board[killY][killX],
10364 board[killY][killX] = EmptySquare,
10365 board[EP_STATUS] = EP_CAPTURE;
10366 if( kill2X >= 0 && kill2Y >= 0)
10367 killed2 = board[kill2Y][kill2X], board[kill2Y][kill2X] = EmptySquare;
10370 if( board[toY][toX] != EmptySquare ) {
10371 board[EP_STATUS] = EP_CAPTURE;
10372 if( (fromX != toX || fromY != toY) && // not igui!
10373 (captured == WhiteLion && board[fromY][fromX] != BlackLion ||
10374 captured == BlackLion && board[fromY][fromX] != WhiteLion ) ) { // [HGM] lion: Chu Lion-capture rules
10375 board[EP_STATUS] = EP_IRON_LION; // non-Lion x Lion: no counter-strike allowed
10379 pawn = board[fromY][fromX];
10380 if(pieceDesc[pawn] && strchr(pieceDesc[pawn], 'e')) { // piece with user-defined e.p. capture
10381 if(captured == EmptySquare && toX == epFile && (toY == (epRank & 127) || toY + (pawn < BlackPawn ? -1 : 1) == epRank - 128)) {
10382 captured = board[lastRank][lastFile]; // remove victim
10383 board[lastRank][lastFile] = EmptySquare;
10384 pawn = EmptySquare; // kludge to suppress old e.p. code
10387 if( pawn == WhiteLance || pawn == BlackLance ) {
10388 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu ) {
10389 if(gameInfo.variant == VariantSpartan) board[EP_STATUS] = EP_PAWN_MOVE; // in Spartan no e.p. rights must be set
10390 else pawn += WhitePawn - WhiteLance; // Lance is Pawn-like in most variants, so let Pawn code treat it by this kludge
10393 if( pawn == WhitePawn ) {
10394 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
10395 board[EP_STATUS] = EP_PAWN_MOVE;
10396 if( toY-fromY>=2) {
10397 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY - 1 | 128*(toY - fromY > 2);
10398 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
10399 gameInfo.variant != VariantBerolina || toX < fromX)
10400 board[EP_STATUS] = toX | berolina;
10401 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
10402 gameInfo.variant != VariantBerolina || toX > fromX)
10403 board[EP_STATUS] = toX;
10404 board[LAST_TO] = toX + 256*toY;
10407 if( pawn == BlackPawn ) {
10408 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
10409 board[EP_STATUS] = EP_PAWN_MOVE;
10410 if( toY-fromY<= -2) {
10411 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY + 1 | 128*(fromY - toY > 2);
10412 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
10413 gameInfo.variant != VariantBerolina || toX < fromX)
10414 board[EP_STATUS] = toX | berolina;
10415 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
10416 gameInfo.variant != VariantBerolina || toX > fromX)
10417 board[EP_STATUS] = toX;
10418 board[LAST_TO] = toX + 256*toY;
10422 if(fromY == 0) board[TOUCHED_W] |= 1<<fromX; else // new way to keep track of virginity
10423 if(fromY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<fromX;
10424 if(toY == 0) board[TOUCHED_W] |= 1<<toX; else
10425 if(toY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<toX;
10427 for(i=0; i<nrCastlingRights; i++) {
10428 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
10429 board[CASTLING][i] == toX && castlingRank[i] == toY
10430 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
10433 if(gameInfo.variant == VariantSChess) { // update virginity
10434 if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
10435 if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
10436 if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
10437 if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
10440 if (fromX == toX && fromY == toY && killX < 0) return;
10442 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
10443 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
10444 if(gameInfo.variant == VariantKnightmate)
10445 king += (int) WhiteUnicorn - (int) WhiteKing;
10447 if(pieceDesc[piece] && killX >= 0 && strchr(pieceDesc[piece], 'O') // Betza castling-enabled
10448 && (piece < BlackPawn ? killed < BlackPawn : killed >= BlackPawn)) { // and tramples own
10449 board[toY][toX] = piece; board[fromY][fromX] = EmptySquare;
10450 board[toY][toX + (killX < fromX ? 1 : -1)] = killed;
10451 board[EP_STATUS] = EP_NONE; // capture was fake!
10453 if(nrCastlingRights == 0 && board[toY][toX] < EmptySquare && (piece < BlackPawn) == (board[toY][toX] < BlackPawn)) {
10454 board[fromY][fromX] = board[toY][toX]; // capture own will lead to swapping
10455 board[toY][toX] = piece;
10456 board[EP_STATUS] = EP_NONE; // capture was fake!
10458 /* Code added by Tord: */
10459 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
10460 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
10461 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
10462 board[EP_STATUS] = EP_NONE; // capture was fake!
10463 board[fromY][fromX] = EmptySquare;
10464 board[toY][toX] = EmptySquare;
10465 if((toX > fromX) != (piece == WhiteRook)) {
10466 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
10468 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
10470 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
10471 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
10472 board[EP_STATUS] = EP_NONE;
10473 board[fromY][fromX] = EmptySquare;
10474 board[toY][toX] = EmptySquare;
10475 if((toX > fromX) != (piece == BlackRook)) {
10476 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
10478 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
10480 /* End of code added by Tord */
10482 } else if (pieceDesc[piece] && piece == king && !strchr(pieceDesc[piece], 'O') && strchr(pieceDesc[piece], 'i')) {
10483 board[fromY][fromX] = EmptySquare; // never castle if King has virgin moves defined on it other than castling
10484 board[toY][toX] = piece;
10485 } else if (board[fromY][fromX] == king
10486 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10487 && toY == fromY && toX > fromX+1) {
10488 for(rookX=fromX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT-1; rookX++)
10489 ; // castle with nearest piece
10490 board[fromY][toX-1] = board[fromY][rookX];
10491 board[fromY][rookX] = EmptySquare;
10492 board[fromY][fromX] = EmptySquare;
10493 board[toY][toX] = king;
10494 } else if (board[fromY][fromX] == king
10495 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10496 && toY == fromY && toX < fromX-1) {
10497 for(rookX=fromX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
10498 ; // castle with nearest piece
10499 board[fromY][toX+1] = board[fromY][rookX];
10500 board[fromY][rookX] = EmptySquare;
10501 board[fromY][fromX] = EmptySquare;
10502 board[toY][toX] = king;
10503 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
10504 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10505 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
10507 /* white pawn promotion */
10508 board[toY][toX] = CharToPiece(ToUpper(promoChar));
10509 if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
10510 board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
10511 board[fromY][fromX] = EmptySquare;
10512 } else if ((fromY >= BOARD_HEIGHT>>1)
10513 && (epFile == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10515 && gameInfo.variant != VariantXiangqi
10516 && gameInfo.variant != VariantBerolina
10517 && (pawn == WhitePawn)
10518 && (board[toY][toX] == EmptySquare)) {
10519 if(lastFile == 100) lastFile = (board[fromY][toX] == BlackPawn ? toX : fromX), lastRank = fromY; // assume FIDE e.p. if victim present
10520 board[fromY][fromX] = EmptySquare;
10521 board[toY][toX] = piece;
10522 captured = board[lastRank][lastFile], board[lastRank][lastFile] = EmptySquare;
10523 } else if ((fromY == BOARD_HEIGHT-4)
10525 && gameInfo.variant == VariantBerolina
10526 && (board[fromY][fromX] == WhitePawn)
10527 && (board[toY][toX] == EmptySquare)) {
10528 board[fromY][fromX] = EmptySquare;
10529 board[toY][toX] = WhitePawn;
10530 if(oldEP & EP_BEROLIN_A) {
10531 captured = board[fromY][fromX-1];
10532 board[fromY][fromX-1] = EmptySquare;
10533 }else{ captured = board[fromY][fromX+1];
10534 board[fromY][fromX+1] = EmptySquare;
10536 } else if (board[fromY][fromX] == king
10537 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10538 && toY == fromY && toX > fromX+1) {
10539 for(rookX=toX+1; board[toY][rookX] == EmptySquare && rookX < BOARD_RGHT - 1; rookX++)
10541 board[fromY][toX-1] = board[fromY][rookX];
10542 board[fromY][rookX] = EmptySquare;
10543 board[fromY][fromX] = EmptySquare;
10544 board[toY][toX] = king;
10545 } else if (board[fromY][fromX] == king
10546 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10547 && toY == fromY && toX < fromX-1) {
10548 for(rookX=toX-1; board[toY][rookX] == EmptySquare && rookX > 0; rookX--)
10550 board[fromY][toX+1] = board[fromY][rookX];
10551 board[fromY][rookX] = EmptySquare;
10552 board[fromY][fromX] = EmptySquare;
10553 board[toY][toX] = king;
10554 } else if (fromY == 7 && fromX == 3
10555 && board[fromY][fromX] == BlackKing
10556 && toY == 7 && toX == 5) {
10557 board[fromY][fromX] = EmptySquare;
10558 board[toY][toX] = BlackKing;
10559 board[fromY][7] = EmptySquare;
10560 board[toY][4] = BlackRook;
10561 } else if (fromY == 7 && fromX == 3
10562 && board[fromY][fromX] == BlackKing
10563 && toY == 7 && toX == 1) {
10564 board[fromY][fromX] = EmptySquare;
10565 board[toY][toX] = BlackKing;
10566 board[fromY][0] = EmptySquare;
10567 board[toY][2] = BlackRook;
10568 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
10569 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10570 && toY < promoRank && promoChar
10572 /* black pawn promotion */
10573 board[toY][toX] = CharToPiece(ToLower(promoChar));
10574 if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED(board[toY][toX])) == '~') /* [HGM] use shadow piece (if available) */
10575 board[toY][toX] = (ChessSquare) (PROMOTED(board[toY][toX]));
10576 board[fromY][fromX] = EmptySquare;
10577 } else if ((fromY < BOARD_HEIGHT>>1)
10578 && (epFile == toX && epRank == toY || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10580 && gameInfo.variant != VariantXiangqi
10581 && gameInfo.variant != VariantBerolina
10582 && (pawn == BlackPawn)
10583 && (board[toY][toX] == EmptySquare)) {
10584 if(lastFile == 100) lastFile = (board[fromY][toX] == WhitePawn ? toX : fromX), lastRank = fromY;
10585 board[fromY][fromX] = EmptySquare;
10586 board[toY][toX] = piece;
10587 captured = board[lastRank][lastFile], board[lastRank][lastFile] = EmptySquare;
10588 } else if ((fromY == 3)
10590 && gameInfo.variant == VariantBerolina
10591 && (board[fromY][fromX] == BlackPawn)
10592 && (board[toY][toX] == EmptySquare)) {
10593 board[fromY][fromX] = EmptySquare;
10594 board[toY][toX] = BlackPawn;
10595 if(oldEP & EP_BEROLIN_A) {
10596 captured = board[fromY][fromX-1];
10597 board[fromY][fromX-1] = EmptySquare;
10598 }else{ captured = board[fromY][fromX+1];
10599 board[fromY][fromX+1] = EmptySquare;
10602 ChessSquare piece = board[fromY][fromX]; // [HGM] lion: allow for igui (where from == to)
10603 board[fromY][fromX] = EmptySquare;
10604 board[toY][toX] = piece;
10608 if (gameInfo.holdingsWidth != 0) {
10610 /* !!A lot more code needs to be written to support holdings */
10611 /* [HGM] OK, so I have written it. Holdings are stored in the */
10612 /* penultimate board files, so they are automaticlly stored */
10613 /* in the game history. */
10614 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
10615 && promoChar && piece != WhitePawn && piece != BlackPawn) {
10616 /* Delete from holdings, by decreasing count */
10617 /* and erasing image if necessary */
10618 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
10619 if(p < (int) BlackPawn) { /* white drop */
10620 p -= (int)WhitePawn;
10621 p = PieceToNumber((ChessSquare)p);
10622 if(p >= gameInfo.holdingsSize) p = 0;
10623 if(--board[p][BOARD_WIDTH-2] <= 0)
10624 board[p][BOARD_WIDTH-1] = EmptySquare;
10625 if((int)board[p][BOARD_WIDTH-2] < 0)
10626 board[p][BOARD_WIDTH-2] = 0;
10627 } else { /* black drop */
10628 p -= (int)BlackPawn;
10629 p = PieceToNumber((ChessSquare)p);
10630 if(p >= gameInfo.holdingsSize) p = 0;
10631 if(--board[handSize-1-p][1] <= 0)
10632 board[handSize-1-p][0] = EmptySquare;
10633 if((int)board[handSize-1-p][1] < 0)
10634 board[handSize-1-p][1] = 0;
10637 if (captured != EmptySquare && gameInfo.holdingsSize > 0
10638 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
10639 /* [HGM] holdings: Add to holdings, if holdings exist */
10640 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
10641 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
10642 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
10644 p = (int) captured;
10645 if (p >= (int) BlackPawn) {
10646 p -= (int)BlackPawn;
10647 if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
10648 /* Restore shogi-promoted piece to its original first */
10649 captured = (ChessSquare) (DEMOTED(captured));
10652 p = PieceToNumber((ChessSquare)p);
10653 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
10654 board[p][BOARD_WIDTH-2]++;
10655 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
10657 p -= (int)WhitePawn;
10658 if(DEMOTED(p) >= 0 && PieceToChar(p) == '+') {
10659 captured = (ChessSquare) (DEMOTED(captured));
10662 p = PieceToNumber((ChessSquare)p);
10663 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
10664 board[handSize-1-p][1]++;
10665 board[handSize-1-p][0] = WHITE_TO_BLACK captured;
10668 } else if (gameInfo.variant == VariantAtomic) {
10669 if (captured != EmptySquare) {
10671 for (y = toY-1; y <= toY+1; y++) {
10672 for (x = toX-1; x <= toX+1; x++) {
10673 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
10674 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
10675 board[y][x] = EmptySquare;
10679 board[toY][toX] = EmptySquare;
10683 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
10684 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
10686 if(promoChar == '+') {
10687 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
10688 board[toY][toX] = (ChessSquare) (CHUPROMOTED(piece));
10689 if(gameInfo.variant == VariantChuChess && (piece == WhiteKnight || piece == BlackKnight))
10690 board[toY][toX] = piece + WhiteLion - WhiteKnight; // adjust Knight promotions to Lion
10691 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
10692 ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
10693 if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
10694 && pieceToChar[PROMOTED(newPiece)] == '~') newPiece = PROMOTED(newPiece);// but promoted version available
10695 board[toY][toX] = newPiece;
10697 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10698 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
10699 // [HGM] superchess: take promotion piece out of holdings
10700 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
10701 if((int)piece < (int)BlackPawn) { // determine stm from piece color
10702 if(!--board[k][BOARD_WIDTH-2])
10703 board[k][BOARD_WIDTH-1] = EmptySquare;
10705 if(!--board[handSize-1-k][1])
10706 board[handSize-1-k][0] = EmptySquare;
10711 /* Updates forwardMostMove */
10713 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
10715 int x = toX, y = toY, mask;
10716 char *s = parseList[forwardMostMove];
10717 ChessSquare p = boards[forwardMostMove][toY][toX];
10718 // forwardMostMove++; // [HGM] bare: moved downstream
10720 if(kill2X >= 0) x = kill2X, y = kill2Y; else
10721 if(killX >= 0 && killY >= 0) x = killX, y = killY; // [HGM] lion: make SAN move to intermediate square, if there is one
10722 (void) CoordsToAlgebraic(boards[forwardMostMove],
10723 PosFlags(forwardMostMove),
10724 fromY, fromX, y, x, (killX < 0)*promoChar,
10726 if(kill2X >= 0 && kill2Y >= 0)
10727 sprintf(s + strlen(s), "x%c%d", killX + AAA, killY + ONE - '0'); // 2nd leg of 3-leg move is always capture
10728 if(killX >= 0 && killY >= 0)
10729 sprintf(s + strlen(s), "%c%c%d%c", p == EmptySquare || toX == fromX && toY == fromY || toX== kill2X && toY == kill2Y ? '-' : 'x',
10730 toX + AAA, toY + ONE - '0', promoChar);
10732 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
10733 int timeLeft; static int lastLoadFlag=0; int king, piece;
10734 piece = boards[forwardMostMove][fromY][fromX];
10735 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
10736 if(gameInfo.variant == VariantKnightmate)
10737 king += (int) WhiteUnicorn - (int) WhiteKing;
10738 if(forwardMostMove == 0) {
10739 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
10740 fprintf(serverMoves, "%s;", UserName());
10741 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
10742 fprintf(serverMoves, "%s;", second.tidy);
10743 fprintf(serverMoves, "%s;", first.tidy);
10744 if(gameMode == MachinePlaysWhite)
10745 fprintf(serverMoves, "%s;", UserName());
10746 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
10747 fprintf(serverMoves, "%s;", second.tidy);
10748 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
10749 lastLoadFlag = loadFlag;
10751 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
10752 // print castling suffix
10753 if( toY == fromY && piece == king ) {
10755 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
10757 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
10760 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
10761 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
10762 boards[forwardMostMove][toY][toX] == EmptySquare
10763 && fromX != toX && fromY != toY)
10764 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
10765 // promotion suffix
10766 if(promoChar != NULLCHAR) {
10767 if(fromY == 0 || fromY == BOARD_HEIGHT-1)
10768 fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
10769 ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
10770 else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
10773 char buf[MOVE_LEN*2], *p; int len;
10774 fprintf(serverMoves, "/%d/%d",
10775 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
10776 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
10777 else timeLeft = blackTimeRemaining/1000;
10778 fprintf(serverMoves, "/%d", timeLeft);
10779 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
10780 if(p = strchr(buf, '/')) *p = NULLCHAR; else
10781 if(p = strchr(buf, '=')) *p = NULLCHAR;
10782 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
10783 fprintf(serverMoves, "/%s", buf);
10785 fflush(serverMoves);
10788 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
10789 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
10792 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
10793 if (commentList[forwardMostMove+1] != NULL) {
10794 free(commentList[forwardMostMove+1]);
10795 commentList[forwardMostMove+1] = NULL;
10797 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
10798 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
10799 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
10800 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
10801 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10802 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10803 adjustedClock = FALSE;
10804 gameInfo.result = GameUnfinished;
10805 if (gameInfo.resultDetails != NULL) {
10806 free(gameInfo.resultDetails);
10807 gameInfo.resultDetails = NULL;
10809 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
10810 moveList[forwardMostMove - 1]);
10811 mask = (WhiteOnMove(forwardMostMove) ? 0xFF : 0xFF00);
10812 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
10818 if(boards[forwardMostMove][CHECK_COUNT]) boards[forwardMostMove][CHECK_COUNT] -= mask & 0x101;
10819 if(!boards[forwardMostMove][CHECK_COUNT] || boards[forwardMostMove][CHECK_COUNT] & mask) {
10820 if(!IS_SHOGI(gameInfo.variant)) strcat(parseList[forwardMostMove - 1], "+");
10825 strcat(parseList[forwardMostMove - 1], "#");
10830 /* Updates currentMove if not pausing */
10832 ShowMove (int fromX, int fromY, int toX, int toY)
10834 int instant = (gameMode == PlayFromGameFile) ?
10835 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
10836 if(appData.noGUI) return;
10837 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10839 if (forwardMostMove == currentMove + 1) {
10840 AnimateMove(boards[forwardMostMove - 1],
10841 fromX, fromY, toX, toY);
10844 currentMove = forwardMostMove;
10847 killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
10849 if (instant) return;
10851 DisplayMove(currentMove - 1);
10852 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10853 if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
10854 SetHighlights(fromX, fromY, toX, toY);
10857 DrawPosition(FALSE, boards[currentMove]);
10858 DisplayBothClocks();
10859 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
10863 SendEgtPath (ChessProgramState *cps)
10864 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
10865 char buf[MSG_SIZ], name[MSG_SIZ], *p;
10867 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
10870 char c, *q = name+1, *r, *s;
10872 name[0] = ','; // extract next format name from feature and copy with prefixed ','
10873 while(*p && *p != ',') *q++ = *p++;
10874 *q++ = ':'; *q = 0;
10875 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
10876 strcmp(name, ",nalimov:") == 0 ) {
10877 // take nalimov path from the menu-changeable option first, if it is defined
10878 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
10879 SendToProgram(buf,cps); // send egtbpath command for nalimov
10881 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
10882 (s = StrStr(appData.egtFormats, name)) != NULL) {
10883 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
10884 s = r = StrStr(s, ":") + 1; // beginning of path info
10885 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
10886 c = *r; *r = 0; // temporarily null-terminate path info
10887 *--q = 0; // strip of trailig ':' from name
10888 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
10890 SendToProgram(buf,cps); // send egtbpath command for this format
10892 if(*p == ',') p++; // read away comma to position for next format name
10897 NonStandardBoardSize (VariantClass v, int boardWidth, int boardHeight, int holdingsSize)
10899 int width = 8, height = 8, holdings = 0; // most common sizes
10900 if( v == VariantUnknown || *engineVariant) return 0; // engine-defined name never needs prefix
10901 // correct the deviations default for each variant
10902 if( v == VariantXiangqi ) width = 9, height = 10;
10903 if( v == VariantShogi ) width = 9, height = 9, holdings = 7;
10904 if( v == VariantBughouse || v == VariantCrazyhouse) holdings = 5;
10905 if( v == VariantCapablanca || v == VariantCapaRandom ||
10906 v == VariantGothic || v == VariantFalcon || v == VariantJanus )
10908 if( v == VariantCourier ) width = 12;
10909 if( v == VariantSuper ) holdings = 8;
10910 if( v == VariantGreat ) width = 10, holdings = 8;
10911 if( v == VariantSChess ) holdings = 7;
10912 if( v == VariantGrand ) width = 10, height = 10, holdings = 7;
10913 if( v == VariantChuChess) width = 10, height = 10;
10914 if( v == VariantChu ) width = 12, height = 12;
10915 return boardWidth >= 0 && boardWidth != width || // -1 is default,
10916 boardHeight >= 0 && boardHeight != height || // and thus by definition OK
10917 holdingsSize >= 0 && holdingsSize != holdings;
10920 char variantError[MSG_SIZ];
10923 SupportedVariant (char *list, VariantClass v, int boardWidth, int boardHeight, int holdingsSize, int proto, char *engine)
10924 { // returns error message (recognizable by upper-case) if engine does not support the variant
10925 char *p, *variant = VariantName(v);
10926 static char b[MSG_SIZ];
10927 if(NonStandardBoardSize(v, boardWidth, boardHeight, holdingsSize)) { /* [HGM] make prefix for non-standard board size. */
10928 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", boardWidth, boardHeight,
10929 holdingsSize, variant); // cook up sized variant name
10930 /* [HGM] varsize: try first if this deviant size variant is specifically known */
10931 if(StrStr(list, b) == NULL) {
10932 // specific sized variant not known, check if general sizing allowed
10933 if(proto != 1 && StrStr(list, "boardsize") == NULL) {
10934 snprintf(variantError, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
10935 boardWidth, boardHeight, holdingsSize, engine);
10938 /* [HGM] here we really should compare with the maximum supported board size */
10940 } else snprintf(b, MSG_SIZ,"%s", variant);
10941 if(proto == 1) return b; // for protocol 1 we cannot check and hope for the best
10942 p = StrStr(list, b);
10943 while(p && (p != list && p[-1] != ',' || p[strlen(b)] && p[strlen(b)] != ',') ) p = StrStr(p+1, b);
10945 // occurs not at all in list, or only as sub-string
10946 snprintf(variantError, MSG_SIZ, _("Variant %s not supported by %s"), b, engine);
10947 if(p = StrStr(list, b)) { // handle requesting parent variant when only size-overridden is supported
10948 int l = strlen(variantError);
10950 while(p != list && p[-1] != ',') p--;
10951 q = strchr(p, ',');
10952 if(q) *q = NULLCHAR;
10953 snprintf(variantError + l, MSG_SIZ - l, _(", but %s is"), p);
10962 InitChessProgram (ChessProgramState *cps, int setup)
10963 /* setup needed to setup FRC opening position */
10965 char buf[MSG_SIZ], *b;
10966 if (appData.noChessProgram) return;
10967 hintRequested = FALSE;
10968 bookRequested = FALSE;
10970 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
10971 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
10972 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
10973 if(cps->memSize) { /* [HGM] memory */
10974 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
10975 SendToProgram(buf, cps);
10977 SendEgtPath(cps); /* [HGM] EGT */
10978 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
10979 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
10980 SendToProgram(buf, cps);
10983 setboardSpoiledMachineBlack = FALSE;
10984 SendToProgram(cps->initString, cps);
10985 if (gameInfo.variant != VariantNormal &&
10986 gameInfo.variant != VariantLoadable
10987 /* [HGM] also send variant if board size non-standard */
10988 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0) {
10990 b = SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
10991 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, cps->tidy);
10995 char c, *q = cps->variants, *p = strchr(q, ',');
10996 if(p) *p = NULLCHAR;
10997 v = StringToVariant(q);
10998 DisplayError(variantError, 0);
10999 if(v != VariantUnknown && cps == &first) {
11001 if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
11002 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
11003 ASSIGN(appData.variant, q);
11004 Reset(TRUE, FALSE);
11010 snprintf(buf, MSG_SIZ, "variant %s\n", b);
11011 SendToProgram(buf, cps);
11013 currentlyInitializedVariant = gameInfo.variant;
11015 /* [HGM] send opening position in FRC to first engine */
11017 SendToProgram("force\n", cps);
11019 /* engine is now in force mode! Set flag to wake it up after first move. */
11020 setboardSpoiledMachineBlack = 1;
11023 if (cps->sendICS) {
11024 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
11025 SendToProgram(buf, cps);
11027 cps->maybeThinking = FALSE;
11028 cps->offeredDraw = 0;
11029 if (!appData.icsActive) {
11030 SendTimeControl(cps, movesPerSession, timeControl,
11031 timeIncrement, appData.searchDepth,
11034 if (appData.showThinking
11035 // [HGM] thinking: four options require thinking output to be sent
11036 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
11038 SendToProgram("post\n", cps);
11040 SendToProgram("hard\n", cps);
11041 if (!appData.ponderNextMove) {
11042 /* Warning: "easy" is a toggle in GNU Chess, so don't send
11043 it without being sure what state we are in first. "hard"
11044 is not a toggle, so that one is OK.
11046 SendToProgram("easy\n", cps);
11048 if (cps->usePing) {
11049 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++cps->lastPing);
11050 SendToProgram(buf, cps);
11052 cps->initDone = TRUE;
11053 ClearEngineOutputPane(cps == &second);
11058 ResendOptions (ChessProgramState *cps, int toEngine)
11059 { // send the stored value of the options
11061 static char buf2[MSG_SIZ*10];
11062 char buf[MSG_SIZ], *p = buf2;
11063 Option *opt = cps->option;
11065 for(i=0; i<cps->nrOptions; i++, opt++) {
11067 switch(opt->type) {
11071 if(opt->value != *(int*) (opt->name + MSG_SIZ - 104))
11072 snprintf(buf, MSG_SIZ, "%s=%d", opt->name, opt->value);
11075 if(opt->value != *(int*) (opt->name + MSG_SIZ - 104))
11076 snprintf(buf, MSG_SIZ, "%s=%s", opt->name, opt->choice[opt->value]);
11079 if(strcmp(opt->textValue, opt->name + MSG_SIZ - 100))
11080 snprintf(buf, MSG_SIZ, "%s=%s", opt->name, opt->textValue);
11088 snprintf(buf2, MSG_SIZ, "option %s\n", buf);
11089 SendToProgram(buf2, cps);
11091 if(p != buf2) *p++ = ',';
11092 strncpy(p, buf, 10*MSG_SIZ-1 - (p - buf2));
11101 StartChessProgram (ChessProgramState *cps)
11106 if (appData.noChessProgram) return;
11107 cps->initDone = FALSE;
11109 if (strcmp(cps->host, "localhost") == 0) {
11110 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
11111 } else if (*appData.remoteShell == NULLCHAR) {
11112 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
11114 if (*appData.remoteUser == NULLCHAR) {
11115 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
11118 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
11119 cps->host, appData.remoteUser, cps->program);
11121 err = StartChildProcess(buf, "", &cps->pr);
11125 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
11126 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
11127 if(cps != &first) return;
11128 appData.noChessProgram = TRUE;
11131 // DisplayFatalError(buf, err, 1);
11132 // cps->pr = NoProc;
11133 // cps->isr = NULL;
11137 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
11138 if (cps->protocolVersion > 1) {
11139 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
11140 if(!cps->reload) { // do not clear options when reloading because of -xreuse
11141 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
11142 cps->comboCnt = 0; // and values of combo boxes
11144 SendToProgram(buf, cps);
11145 if(cps->reload) ResendOptions(cps, TRUE);
11147 SendToProgram("xboard\n", cps);
11152 TwoMachinesEventIfReady P((void))
11154 static int curMess = 0;
11155 if (first.lastPing != first.lastPong) {
11156 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
11157 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
11160 if (second.lastPing != second.lastPong) {
11161 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
11162 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
11165 DisplayMessage("", ""); curMess = 0;
11166 TwoMachinesEvent();
11170 MakeName (char *template)
11174 static char buf[MSG_SIZ];
11178 clock = time((time_t *)NULL);
11179 tm = localtime(&clock);
11181 while(*p++ = *template++) if(p[-1] == '%') {
11182 switch(*template++) {
11183 case 0: *p = 0; return buf;
11184 case 'Y': i = tm->tm_year+1900; break;
11185 case 'y': i = tm->tm_year-100; break;
11186 case 'M': i = tm->tm_mon+1; break;
11187 case 'd': i = tm->tm_mday; break;
11188 case 'h': i = tm->tm_hour; break;
11189 case 'm': i = tm->tm_min; break;
11190 case 's': i = tm->tm_sec; break;
11193 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
11199 CountPlayers (char *p)
11202 while(p = strchr(p, '\n')) p++, n++; // count participants
11207 WriteTourneyFile (char *results, FILE *f)
11208 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
11209 if(f == NULL) f = fopen(appData.tourneyFile, "w");
11210 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
11211 // create a file with tournament description
11212 fprintf(f, "-participants {%s}\n", appData.participants);
11213 fprintf(f, "-seedBase %d\n", appData.seedBase);
11214 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
11215 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
11216 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
11217 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
11218 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
11219 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
11220 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
11221 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
11222 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
11223 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
11224 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
11225 fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
11226 fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
11227 fprintf(f, "-bookDepth %d\n", appData.bookDepth);
11228 fprintf(f, "-bookVariation %d\n", appData.bookStrength);
11229 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
11230 fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
11231 fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
11232 fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
11233 fprintf(f, "-smpCores %d\n", appData.smpCores);
11235 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
11237 fprintf(f, "-mps %d\n", appData.movesPerSession);
11238 fprintf(f, "-tc %s\n", appData.timeControl);
11239 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
11241 fprintf(f, "-results \"%s\"\n", results);
11246 char *command[MAXENGINES], *mnemonic[MAXENGINES];
11249 Substitute (char *participants, int expunge)
11251 int i, changed, changes=0, nPlayers=0;
11252 char *p, *q, *r, buf[MSG_SIZ];
11253 if(participants == NULL) return;
11254 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
11255 r = p = participants; q = appData.participants;
11256 while(*p && *p == *q) {
11257 if(*p == '\n') r = p+1, nPlayers++;
11260 if(*p) { // difference
11261 while(*p && *p++ != '\n')
11263 while(*q && *q++ != '\n')
11265 changed = nPlayers;
11266 changes = 1 + (strcmp(p, q) != 0);
11268 if(changes == 1) { // a single engine mnemonic was changed
11269 q = r; while(*q) nPlayers += (*q++ == '\n');
11270 p = buf; while(*r && (*p = *r++) != '\n') p++;
11272 NamesToList(firstChessProgramNames, command, mnemonic, "all");
11273 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
11274 if(mnemonic[i]) { // The substitute is valid
11276 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
11277 flock(fileno(f), LOCK_EX);
11278 ParseArgsFromFile(f);
11279 fseek(f, 0, SEEK_SET);
11280 FREE(appData.participants); appData.participants = participants;
11281 if(expunge) { // erase results of replaced engine
11282 int len = strlen(appData.results), w, b, dummy;
11283 for(i=0; i<len; i++) {
11284 Pairing(i, nPlayers, &w, &b, &dummy);
11285 if((w == changed || b == changed) && appData.results[i] == '*') {
11286 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
11291 for(i=0; i<len; i++) {
11292 Pairing(i, nPlayers, &w, &b, &dummy);
11293 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
11296 WriteTourneyFile(appData.results, f);
11297 fclose(f); // release lock
11300 } else DisplayError(_("No engine with the name you gave is installed"), 0);
11302 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
11303 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
11304 free(participants);
11309 CheckPlayers (char *participants)
11312 char buf[MSG_SIZ], *p;
11313 NamesToList(firstChessProgramNames, command, mnemonic, "all");
11314 while(p = strchr(participants, '\n')) {
11316 for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
11318 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
11320 DisplayError(buf, 0);
11324 participants = p + 1;
11330 CreateTourney (char *name)
11333 if(matchMode && strcmp(name, appData.tourneyFile)) {
11334 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
11336 if(name[0] == NULLCHAR) {
11337 if(appData.participants[0])
11338 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
11341 f = fopen(name, "r");
11342 if(f) { // file exists
11343 ASSIGN(appData.tourneyFile, name);
11344 ParseArgsFromFile(f); // parse it
11346 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
11347 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
11348 DisplayError(_("Not enough participants"), 0);
11351 if(CheckPlayers(appData.participants)) return 0;
11352 ASSIGN(appData.tourneyFile, name);
11353 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
11354 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
11357 appData.noChessProgram = FALSE;
11358 appData.clockMode = TRUE;
11364 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
11366 char buf[2*MSG_SIZ], *p, *q;
11367 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
11368 insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
11369 skip = !all && group[0]; // if group requested, we start in skip mode
11370 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
11371 p = names; q = buf; header = 0;
11372 while(*p && *p != '\n') *q++ = *p++;
11374 if(*p == '\n') p++;
11375 if(buf[0] == '#') {
11376 if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
11377 depth++; // we must be entering a new group
11378 if(all) continue; // suppress printing group headers when complete list requested
11380 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
11382 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
11383 if(engineList[i]) free(engineList[i]);
11384 engineList[i] = strdup(buf);
11385 if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
11386 if(engineMnemonic[i]) free(engineMnemonic[i]);
11387 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
11389 sscanf(q + 8, "%s", buf + strlen(buf));
11392 engineMnemonic[i] = strdup(buf);
11395 engineList[i] = engineMnemonic[i] = NULL;
11400 SaveEngineSettings (int n)
11402 int len; char *p, *q, *s, buf[MSG_SIZ], *optionSettings;
11403 if(!currentEngine[n] || !currentEngine[n][0]) { DisplayMessage("saving failed: engine not from list", ""); return; } // no engine from list is loaded
11404 if(*engineListFile) ParseSettingsFile(engineListFile, &engineListFile); // update engine list
11405 p = strstr(firstChessProgramNames, currentEngine[n]);
11406 if(!p) { DisplayMessage("saving failed: engine not found in list", ""); return; } // sanity check; engine could be deleted from list after loading
11407 optionSettings = ResendOptions(n ? &second : &first, FALSE);
11408 len = strlen(currentEngine[n]);
11409 q = p + len; *p = 0; // cut list into head and tail piece
11410 s = strstr(currentEngine[n], "firstOptions");
11411 if(s && (s[-1] == '-' || s[-1] == '/') && (s[12] == ' ' || s[12] == '=') && (s[13] == '"' || s[13] == '\'')) {
11413 while(*r && *r != s[13]) r++;
11414 s[14] = 0; // cut currentEngine into head and tail part, removing old settings
11415 snprintf(buf, MSG_SIZ, "%s%s%s", currentEngine[n], optionSettings, *r ? r : "\""); // synthesize new engine line
11416 } else if(*optionSettings) {
11417 snprintf(buf, MSG_SIZ, "%s -firstOptions \"%s\"", currentEngine[n], optionSettings);
11419 ASSIGN(currentEngine[n], buf); // updated engine line
11420 len = p - firstChessProgramNames + strlen(q) + strlen(currentEngine[n]) + 1;
11422 snprintf(s, len, "%s%s%s", firstChessProgramNames, currentEngine[n], q);
11423 FREE(firstChessProgramNames); firstChessProgramNames = s; // new list
11424 if(*engineListFile) SaveEngineList();
11427 // following implemented as macro to avoid type limitations
11428 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
11431 SwapEngines (int n)
11432 { // swap settings for first engine and other engine (so far only some selected options)
11437 SWAP(chessProgram, p)
11439 SWAP(hasOwnBookUCI, h)
11440 SWAP(protocolVersion, h)
11442 SWAP(scoreIsAbsolute, h)
11447 SWAP(engOptions, p)
11448 SWAP(engInitString, p)
11449 SWAP(computerString, p)
11451 SWAP(fenOverride, p)
11453 SWAP(accumulateTC, h)
11460 GetEngineLine (char *s, int n)
11464 extern char *icsNames;
11465 if(!s || !*s) return 0;
11466 NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
11467 for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
11468 if(!mnemonic[i]) return 0;
11469 if(n == 11) return 1; // just testing if there was a match
11470 snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
11471 if(n == 1) SwapEngines(n);
11472 ParseArgsFromString(buf);
11473 if(n == 1) SwapEngines(n);
11474 if(n < 2) { ASSIGN(currentEngine[n], command[i]); }
11475 if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
11476 SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
11477 ParseArgsFromString(buf);
11483 SetPlayer (int player, char *p)
11484 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
11486 char buf[MSG_SIZ], *engineName;
11487 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
11488 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
11489 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
11491 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
11492 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
11493 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
11494 ParseArgsFromString(buf);
11495 } else { // no engine with this nickname is installed!
11496 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
11497 ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
11498 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
11500 DisplayError(buf, 0);
11507 char *recentEngines;
11510 RecentEngineEvent (int nr)
11513 // SwapEngines(1); // bump first to second
11514 // ReplaceEngine(&second, 1); // and load it there
11515 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11516 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
11517 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
11518 ReplaceEngine(&first, 0);
11519 FloatToFront(&appData.recentEngineList, command[n]);
11520 ASSIGN(currentEngine[0], command[n]);
11525 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
11526 { // determine players from game number
11527 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
11529 if(appData.tourneyType == 0) {
11530 roundsPerCycle = (nPlayers - 1) | 1;
11531 pairingsPerRound = nPlayers / 2;
11532 } else if(appData.tourneyType > 0) {
11533 roundsPerCycle = nPlayers - appData.tourneyType;
11534 pairingsPerRound = appData.tourneyType;
11536 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
11537 gamesPerCycle = gamesPerRound * roundsPerCycle;
11538 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
11539 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
11540 curRound = nr / gamesPerRound; nr %= gamesPerRound;
11541 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
11542 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
11543 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
11545 if(appData.cycleSync) *syncInterval = gamesPerCycle;
11546 if(appData.roundSync) *syncInterval = gamesPerRound;
11548 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
11550 if(appData.tourneyType == 0) {
11551 if(curPairing == (nPlayers-1)/2 ) {
11552 *whitePlayer = curRound;
11553 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
11555 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
11556 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
11557 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
11558 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
11560 } else if(appData.tourneyType > 1) {
11561 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
11562 *whitePlayer = curRound + appData.tourneyType;
11563 } else if(appData.tourneyType > 0) {
11564 *whitePlayer = curPairing;
11565 *blackPlayer = curRound + appData.tourneyType;
11568 // take care of white/black alternation per round.
11569 // For cycles and games this is already taken care of by default, derived from matchGame!
11570 return curRound & 1;
11574 NextTourneyGame (int nr, int *swapColors)
11575 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
11577 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
11579 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
11580 tf = fopen(appData.tourneyFile, "r");
11581 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
11582 ParseArgsFromFile(tf); fclose(tf);
11583 InitTimeControls(); // TC might be altered from tourney file
11585 nPlayers = CountPlayers(appData.participants); // count participants
11586 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
11587 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
11590 p = q = appData.results;
11591 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
11592 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
11593 DisplayMessage(_("Waiting for other game(s)"),"");
11594 waitingForGame = TRUE;
11595 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
11598 waitingForGame = FALSE;
11601 if(appData.tourneyType < 0) {
11602 if(nr>=0 && !pairingReceived) {
11604 if(pairing.pr == NoProc) {
11605 if(!appData.pairingEngine[0]) {
11606 DisplayFatalError(_("No pairing engine specified"), 0, 1);
11609 StartChessProgram(&pairing); // starts the pairing engine
11611 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
11612 SendToProgram(buf, &pairing);
11613 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
11614 SendToProgram(buf, &pairing);
11615 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
11617 pairingReceived = 0; // ... so we continue here
11619 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
11620 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
11621 matchGame = 1; roundNr = nr / syncInterval + 1;
11624 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
11626 // redefine engines, engine dir, etc.
11627 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11628 if(first.pr == NoProc) {
11629 if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
11630 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
11632 if(second.pr == NoProc) {
11634 if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
11635 SwapEngines(1); // and make that valid for second engine by swapping
11636 InitEngine(&second, 1);
11638 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
11639 UpdateLogos(FALSE); // leave display to ModeHiglight()
11645 { // performs game initialization that does not invoke engines, and then tries to start the game
11646 int res, firstWhite, swapColors = 0;
11647 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
11648 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
11650 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
11651 if(strcmp(buf, currentDebugFile)) { // name has changed
11652 FILE *f = fopen(buf, "w");
11653 if(f) { // if opening the new file failed, just keep using the old one
11654 ASSIGN(currentDebugFile, buf);
11658 if(appData.serverFileName) {
11659 if(serverFP) fclose(serverFP);
11660 serverFP = fopen(appData.serverFileName, "w");
11661 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
11662 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
11666 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
11667 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
11668 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
11669 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11670 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
11671 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
11672 Reset(FALSE, first.pr != NoProc);
11673 res = LoadGameOrPosition(matchGame); // setup game
11674 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
11675 if(!res) return; // abort when bad game/pos file
11676 if(appData.epd) {// in EPD mode we make sure first engine is to move
11677 firstWhite = !(forwardMostMove & 1);
11678 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
11679 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11681 TwoMachinesEvent();
11685 UserAdjudicationEvent (int result)
11687 ChessMove gameResult = GameIsDrawn;
11690 gameResult = WhiteWins;
11692 else if( result < 0 ) {
11693 gameResult = BlackWins;
11696 if( gameMode == TwoMachinesPlay ) {
11697 GameEnds( gameResult, "User adjudication", GE_XBOARD );
11702 // [HGM] save: calculate checksum of game to make games easily identifiable
11704 StringCheckSum (char *s)
11707 if(s==NULL) return 0;
11708 while(*s) i = i*259 + *s++;
11716 for(i=backwardMostMove; i<forwardMostMove; i++) {
11717 sum += pvInfoList[i].depth;
11718 sum += StringCheckSum(parseList[i]);
11719 sum += StringCheckSum(commentList[i]);
11722 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
11723 return sum + StringCheckSum(commentList[i]);
11724 } // end of save patch
11727 GameEnds (ChessMove result, char *resultDetails, int whosays)
11729 GameMode nextGameMode;
11731 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
11733 if(endingGame) return; /* [HGM] crash: forbid recursion */
11735 if(twoBoards) { // [HGM] dual: switch back to one board
11736 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
11737 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
11739 if (appData.debugMode) {
11740 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
11741 result, resultDetails ? resultDetails : "(null)", whosays);
11744 fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move the user is entering. // [HGM] lion
11746 if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
11748 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
11749 /* If we are playing on ICS, the server decides when the
11750 game is over, but the engine can offer to draw, claim
11754 if (appData.zippyPlay && first.initDone) {
11755 if (result == GameIsDrawn) {
11756 /* In case draw still needs to be claimed */
11757 SendToICS(ics_prefix);
11758 SendToICS("draw\n");
11759 } else if (StrCaseStr(resultDetails, "resign")) {
11760 SendToICS(ics_prefix);
11761 SendToICS("resign\n");
11765 endingGame = 0; /* [HGM] crash */
11769 /* If we're loading the game from a file, stop */
11770 if (whosays == GE_FILE) {
11771 (void) StopLoadGameTimer();
11775 /* Cancel draw offers */
11776 first.offeredDraw = second.offeredDraw = 0;
11778 /* If this is an ICS game, only ICS can really say it's done;
11779 if not, anyone can. */
11780 isIcsGame = (gameMode == IcsPlayingWhite ||
11781 gameMode == IcsPlayingBlack ||
11782 gameMode == IcsObserving ||
11783 gameMode == IcsExamining);
11785 if (!isIcsGame || whosays == GE_ICS) {
11786 /* OK -- not an ICS game, or ICS said it was done */
11788 if (!isIcsGame && !appData.noChessProgram)
11789 SetUserThinkingEnables();
11791 /* [HGM] if a machine claims the game end we verify this claim */
11792 if(gameMode == TwoMachinesPlay && appData.testClaims) {
11793 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
11795 ChessMove trueResult = (ChessMove) -1;
11797 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
11798 first.twoMachinesColor[0] :
11799 second.twoMachinesColor[0] ;
11801 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
11802 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
11803 /* [HGM] verify: engine mate claims accepted if they were flagged */
11804 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
11806 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
11807 /* [HGM] verify: engine mate claims accepted if they were flagged */
11808 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
11810 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
11811 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
11814 // now verify win claims, but not in drop games, as we don't understand those yet
11815 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11816 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
11817 (result == WhiteWins && claimer == 'w' ||
11818 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
11819 if (appData.debugMode) {
11820 fprintf(debugFP, "result=%d sp=%d move=%d\n",
11821 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
11823 if(result != trueResult) {
11824 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
11825 result = claimer == 'w' ? BlackWins : WhiteWins;
11826 resultDetails = buf;
11829 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
11830 && (forwardMostMove <= backwardMostMove ||
11831 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
11832 (claimer=='b')==(forwardMostMove&1))
11834 /* [HGM] verify: draws that were not flagged are false claims */
11835 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
11836 result = claimer == 'w' ? BlackWins : WhiteWins;
11837 resultDetails = buf;
11839 /* (Claiming a loss is accepted no questions asked!) */
11840 } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
11841 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
11842 result = GameUnfinished;
11843 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
11845 /* [HGM] bare: don't allow bare King to win */
11846 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11847 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
11848 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
11849 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
11850 && result != GameIsDrawn)
11851 { int i, j, k=0, oppoKings = 0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
11852 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
11853 int p = (int)boards[forwardMostMove][i][j] - color;
11854 if(p >= 0 && p <= (int)WhiteKing) k++;
11855 oppoKings += (p + color == WhiteKing + BlackPawn - color);
11857 if (appData.debugMode) {
11858 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
11859 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
11861 if(k <= 1 && oppoKings > 0) { // the latter needed in Atomic, where bare K wins if opponent King already destroyed
11862 result = GameIsDrawn;
11863 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
11864 resultDetails = buf;
11870 if(serverMoves != NULL && !loadFlag) { char c = '=';
11871 if(result==WhiteWins) c = '+';
11872 if(result==BlackWins) c = '-';
11873 if(resultDetails != NULL)
11874 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
11876 if (resultDetails != NULL) {
11877 gameInfo.result = result;
11878 gameInfo.resultDetails = StrSave(resultDetails);
11880 /* display last move only if game was not loaded from file */
11881 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
11882 DisplayMove(currentMove - 1);
11884 if (forwardMostMove != 0) {
11885 if (gameMode != PlayFromGameFile && gameMode != EditGame
11886 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
11888 if (*appData.saveGameFile != NULLCHAR) {
11889 if(result == GameUnfinished && matchMode && *appData.tourneyFile)
11890 AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
11892 SaveGameToFile(appData.saveGameFile, TRUE);
11893 } else if (appData.autoSaveGames) {
11894 if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
11896 if (*appData.savePositionFile != NULLCHAR) {
11897 SavePositionToFile(appData.savePositionFile);
11899 AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
11903 /* Tell program how game ended in case it is learning */
11904 /* [HGM] Moved this to after saving the PGN, just in case */
11905 /* engine died and we got here through time loss. In that */
11906 /* case we will get a fatal error writing the pipe, which */
11907 /* would otherwise lose us the PGN. */
11908 /* [HGM] crash: not needed anymore, but doesn't hurt; */
11909 /* output during GameEnds should never be fatal anymore */
11910 if (gameMode == MachinePlaysWhite ||
11911 gameMode == MachinePlaysBlack ||
11912 gameMode == TwoMachinesPlay ||
11913 gameMode == IcsPlayingWhite ||
11914 gameMode == IcsPlayingBlack ||
11915 gameMode == BeginningOfGame) {
11917 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
11919 if (first.pr != NoProc) {
11920 SendToProgram(buf, &first);
11922 if (second.pr != NoProc &&
11923 gameMode == TwoMachinesPlay) {
11924 SendToProgram(buf, &second);
11929 if (appData.icsActive) {
11930 if (appData.quietPlay &&
11931 (gameMode == IcsPlayingWhite ||
11932 gameMode == IcsPlayingBlack)) {
11933 SendToICS(ics_prefix);
11934 SendToICS("set shout 1\n");
11936 nextGameMode = IcsIdle;
11937 ics_user_moved = FALSE;
11938 /* clean up premove. It's ugly when the game has ended and the
11939 * premove highlights are still on the board.
11942 gotPremove = FALSE;
11943 ClearPremoveHighlights();
11944 DrawPosition(FALSE, boards[currentMove]);
11946 if (whosays == GE_ICS) {
11949 if (gameMode == IcsPlayingWhite)
11951 else if(gameMode == IcsPlayingBlack)
11952 PlayIcsLossSound();
11955 if (gameMode == IcsPlayingBlack)
11957 else if(gameMode == IcsPlayingWhite)
11958 PlayIcsLossSound();
11961 PlayIcsDrawSound();
11964 PlayIcsUnfinishedSound();
11967 if(appData.quitNext) { ExitEvent(0); return; }
11968 } else if (gameMode == EditGame ||
11969 gameMode == PlayFromGameFile ||
11970 gameMode == AnalyzeMode ||
11971 gameMode == AnalyzeFile) {
11972 nextGameMode = gameMode;
11974 nextGameMode = EndOfGame;
11979 nextGameMode = gameMode;
11982 if (appData.noChessProgram) {
11983 gameMode = nextGameMode;
11985 endingGame = 0; /* [HGM] crash */
11990 /* Put first chess program into idle state */
11991 if (first.pr != NoProc &&
11992 (gameMode == MachinePlaysWhite ||
11993 gameMode == MachinePlaysBlack ||
11994 gameMode == TwoMachinesPlay ||
11995 gameMode == IcsPlayingWhite ||
11996 gameMode == IcsPlayingBlack ||
11997 gameMode == BeginningOfGame)) {
11998 SendToProgram("force\n", &first);
11999 if (first.usePing) {
12001 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
12002 SendToProgram(buf, &first);
12005 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12006 /* Kill off first chess program */
12007 if (first.isr != NULL)
12008 RemoveInputSource(first.isr);
12011 if (first.pr != NoProc) {
12013 DoSleep( appData.delayBeforeQuit );
12014 SendToProgram("quit\n", &first);
12015 DestroyChildProcess(first.pr, 4 + first.useSigterm);
12016 first.reload = TRUE;
12020 if (second.reuse) {
12021 /* Put second chess program into idle state */
12022 if (second.pr != NoProc &&
12023 gameMode == TwoMachinesPlay) {
12024 SendToProgram("force\n", &second);
12025 if (second.usePing) {
12027 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
12028 SendToProgram(buf, &second);
12031 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
12032 /* Kill off second chess program */
12033 if (second.isr != NULL)
12034 RemoveInputSource(second.isr);
12037 if (second.pr != NoProc) {
12038 DoSleep( appData.delayBeforeQuit );
12039 SendToProgram("quit\n", &second);
12040 DestroyChildProcess(second.pr, 4 + second.useSigterm);
12041 second.reload = TRUE;
12043 second.pr = NoProc;
12046 if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
12047 char resChar = '=';
12051 if (first.twoMachinesColor[0] == 'w') {
12054 second.matchWins++;
12059 if (first.twoMachinesColor[0] == 'b') {
12062 second.matchWins++;
12065 case GameUnfinished:
12071 if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
12072 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
12073 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
12074 ReserveGame(nextGame, resChar); // sets nextGame
12075 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
12076 else ranking = strdup("busy"); //suppress popup when aborted but not finished
12077 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
12079 if (nextGame <= appData.matchGames && !abortMatch) {
12080 gameMode = nextGameMode;
12081 matchGame = nextGame; // this will be overruled in tourney mode!
12082 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
12083 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
12084 endingGame = 0; /* [HGM] crash */
12087 gameMode = nextGameMode;
12089 snprintf(buf, MSG_SIZ, "-------------------------------------- ");
12090 OutputKibitz(2, buf);
12091 snprintf(buf, MSG_SIZ, _("Average solving time %4.2f sec (total time %4.2f sec) "), totalTime/(100.*first.matchWins), totalTime/100.);
12092 OutputKibitz(2, buf);
12093 snprintf(buf, MSG_SIZ, _("%d avoid-moves played "), second.matchWins);
12094 if(second.matchWins) OutputKibitz(2, buf);
12095 snprintf(buf, MSG_SIZ, _("Solved %d out of %d (%3.1f%%) "), first.matchWins, nextGame-1, first.matchWins*100./(nextGame-1));
12096 OutputKibitz(2, buf);
12098 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
12099 first.tidy, second.tidy,
12100 first.matchWins, second.matchWins,
12101 appData.matchGames - (first.matchWins + second.matchWins));
12102 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
12103 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
12104 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
12105 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
12106 first.twoMachinesColor = "black\n";
12107 second.twoMachinesColor = "white\n";
12109 first.twoMachinesColor = "white\n";
12110 second.twoMachinesColor = "black\n";
12114 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
12115 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
12117 gameMode = nextGameMode;
12119 endingGame = 0; /* [HGM] crash */
12120 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
12121 if(matchMode == TRUE) { // match through command line: exit with or without popup
12123 ToNrEvent(forwardMostMove);
12124 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
12126 } else DisplayFatalError(buf, 0, 0);
12127 } else { // match through menu; just stop, with or without popup
12128 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
12131 if(strcmp(ranking, "busy")) DisplayNote(ranking);
12132 } else DisplayNote(buf);
12134 if(ranking) free(ranking);
12138 /* Assumes program was just initialized (initString sent).
12139 Leaves program in force mode. */
12141 FeedMovesToProgram (ChessProgramState *cps, int upto)
12145 if (appData.debugMode)
12146 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
12147 startedFromSetupPosition ? "position and " : "",
12148 backwardMostMove, upto, cps->which);
12149 if(currentlyInitializedVariant != gameInfo.variant) {
12151 // [HGM] variantswitch: make engine aware of new variant
12152 if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
12153 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
12154 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
12155 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
12156 SendToProgram(buf, cps);
12157 currentlyInitializedVariant = gameInfo.variant;
12159 SendToProgram("force\n", cps);
12160 if (startedFromSetupPosition) {
12161 SendBoard(cps, backwardMostMove);
12162 if (appData.debugMode) {
12163 fprintf(debugFP, "feedMoves\n");
12166 for (i = backwardMostMove; i < upto; i++) {
12167 SendMoveToProgram(i, cps);
12173 ResurrectChessProgram ()
12175 /* The chess program may have exited.
12176 If so, restart it and feed it all the moves made so far. */
12177 static int doInit = 0;
12179 if (appData.noChessProgram) return 1;
12181 if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
12182 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
12183 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
12184 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
12186 if (first.pr != NoProc) return 1;
12187 StartChessProgram(&first);
12189 InitChessProgram(&first, FALSE);
12190 FeedMovesToProgram(&first, currentMove);
12192 if (!first.sendTime) {
12193 /* can't tell gnuchess what its clock should read,
12194 so we bow to its notion. */
12196 timeRemaining[0][currentMove] = whiteTimeRemaining;
12197 timeRemaining[1][currentMove] = blackTimeRemaining;
12200 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
12201 appData.icsEngineAnalyze) && first.analysisSupport) {
12202 SendToProgram("analyze\n", &first);
12203 first.analyzing = TRUE;
12209 * Button procedures
12212 Reset (int redraw, int init)
12216 if (appData.debugMode) {
12217 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
12218 redraw, init, gameMode);
12220 pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
12221 deadRanks = 0; // assume entire board is used
12223 for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
12224 CleanupTail(); // [HGM] vari: delete any stored variations
12225 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
12226 pausing = pauseExamInvalid = FALSE;
12227 startedFromSetupPosition = blackPlaysFirst = FALSE;
12229 whiteFlag = blackFlag = FALSE;
12230 userOfferedDraw = FALSE;
12231 hintRequested = bookRequested = FALSE;
12232 first.maybeThinking = FALSE;
12233 second.maybeThinking = FALSE;
12234 first.bookSuspend = FALSE; // [HGM] book
12235 second.bookSuspend = FALSE;
12236 thinkOutput[0] = NULLCHAR;
12237 lastHint[0] = NULLCHAR;
12238 ClearGameInfo(&gameInfo);
12239 gameInfo.variant = StringToVariant(appData.variant);
12240 if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) {
12241 gameInfo.variant = VariantUnknown;
12242 strncpy(engineVariant, appData.variant, MSG_SIZ);
12244 ics_user_moved = ics_clock_paused = FALSE;
12245 ics_getting_history = H_FALSE;
12247 white_holding[0] = black_holding[0] = NULLCHAR;
12248 ClearProgramStats();
12249 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
12253 flipView = appData.flipView;
12254 ClearPremoveHighlights();
12255 gotPremove = FALSE;
12256 alarmSounded = FALSE;
12257 killX = killY = kill2X = kill2Y = -1; // [HGM] lion
12259 GameEnds(EndOfFile, NULL, GE_PLAYER);
12260 if(appData.serverMovesName != NULL) {
12261 /* [HGM] prepare to make moves file for broadcasting */
12262 clock_t t = clock();
12263 if(serverMoves != NULL) fclose(serverMoves);
12264 serverMoves = fopen(appData.serverMovesName, "r");
12265 if(serverMoves != NULL) {
12266 fclose(serverMoves);
12267 /* delay 15 sec before overwriting, so all clients can see end */
12268 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
12270 serverMoves = fopen(appData.serverMovesName, "w");
12274 gameMode = BeginningOfGame;
12276 if(appData.icsActive) gameInfo.variant = VariantNormal;
12277 currentMove = forwardMostMove = backwardMostMove = 0;
12278 MarkTargetSquares(1);
12279 InitPosition(redraw);
12280 for (i = 0; i < MAX_MOVES; i++) {
12281 if (commentList[i] != NULL) {
12282 free(commentList[i]);
12283 commentList[i] = NULL;
12287 timeRemaining[0][0] = whiteTimeRemaining;
12288 timeRemaining[1][0] = blackTimeRemaining;
12290 if (first.pr == NoProc) {
12291 StartChessProgram(&first);
12294 InitChessProgram(&first, startedFromSetupPosition);
12297 DisplayMessage("", "");
12298 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12299 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
12300 ClearMap(); // [HGM] exclude: invalidate map
12304 AutoPlayGameLoop ()
12307 if (!AutoPlayOneMove())
12309 if (matchMode || appData.timeDelay == 0)
12311 if (appData.timeDelay < 0)
12313 StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
12321 ReloadGame(1); // next game
12327 int fromX, fromY, toX, toY;
12329 if (appData.debugMode) {
12330 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
12333 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
12336 if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
12337 pvInfoList[currentMove].depth = programStats.depth;
12338 pvInfoList[currentMove].score = programStats.score;
12339 pvInfoList[currentMove].time = 0;
12340 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
12341 else { // append analysis of final position as comment
12343 snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
12344 AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
12346 programStats.depth = 0;
12349 if (currentMove >= forwardMostMove) {
12350 if(gameMode == AnalyzeFile) {
12351 if(appData.loadGameIndex == -1) {
12352 GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
12353 ScheduleDelayedEvent(AnalyzeNextGame, 10);
12355 ExitAnalyzeMode(); SendToProgram("force\n", &first);
12358 // gameMode = EndOfGame;
12359 // ModeHighlight();
12361 /* [AS] Clear current move marker at the end of a game */
12362 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
12367 toX = moveList[currentMove][2] - AAA;
12368 toY = moveList[currentMove][3] - ONE;
12370 if (moveList[currentMove][1] == '@') {
12371 if (appData.highlightLastMove) {
12372 SetHighlights(-1, -1, toX, toY);
12375 fromX = moveList[currentMove][0] - AAA;
12376 fromY = moveList[currentMove][1] - ONE;
12378 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
12380 if(moveList[currentMove][4] == ';') { // multi-leg
12381 killX = moveList[currentMove][5] - AAA;
12382 killY = moveList[currentMove][6] - ONE;
12384 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12385 killX = killY = -1;
12387 if (appData.highlightLastMove) {
12388 SetHighlights(fromX, fromY, toX, toY);
12391 DisplayMove(currentMove);
12392 SendMoveToProgram(currentMove++, &first);
12393 DisplayBothClocks();
12394 DrawPosition(FALSE, boards[currentMove]);
12395 // [HGM] PV info: always display, routine tests if empty
12396 DisplayComment(currentMove - 1, commentList[currentMove]);
12402 LoadGameOneMove (ChessMove readAhead)
12404 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
12405 char promoChar = NULLCHAR;
12406 ChessMove moveType;
12407 char move[MSG_SIZ];
12410 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
12411 gameMode != AnalyzeMode && gameMode != Training) {
12416 yyboardindex = forwardMostMove;
12417 if (readAhead != EndOfFile) {
12418 moveType = readAhead;
12420 if (gameFileFP == NULL)
12422 moveType = (ChessMove) Myylex();
12426 switch (moveType) {
12428 if (appData.debugMode)
12429 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12432 /* append the comment but don't display it */
12433 AppendComment(currentMove, p, FALSE);
12436 case WhiteCapturesEnPassant:
12437 case BlackCapturesEnPassant:
12438 case WhitePromotion:
12439 case BlackPromotion:
12440 case WhiteNonPromotion:
12441 case BlackNonPromotion:
12444 case WhiteKingSideCastle:
12445 case WhiteQueenSideCastle:
12446 case BlackKingSideCastle:
12447 case BlackQueenSideCastle:
12448 case WhiteKingSideCastleWild:
12449 case WhiteQueenSideCastleWild:
12450 case BlackKingSideCastleWild:
12451 case BlackQueenSideCastleWild:
12453 case WhiteHSideCastleFR:
12454 case WhiteASideCastleFR:
12455 case BlackHSideCastleFR:
12456 case BlackASideCastleFR:
12458 if (appData.debugMode)
12459 fprintf(debugFP, "Parsed %s into %s virgin=%x,%x\n", yy_text, currentMoveString, boards[forwardMostMove][TOUCHED_W], boards[forwardMostMove][TOUCHED_B]);
12460 fromX = currentMoveString[0] - AAA;
12461 fromY = currentMoveString[1] - ONE;
12462 toX = currentMoveString[2] - AAA;
12463 toY = currentMoveString[3] - ONE;
12464 promoChar = currentMoveString[4];
12465 if(promoChar == ';') promoChar = currentMoveString[7];
12470 if (appData.debugMode)
12471 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
12472 fromX = moveType == WhiteDrop ?
12473 (int) CharToPiece(ToUpper(currentMoveString[0])) :
12474 (int) CharToPiece(ToLower(currentMoveString[0]));
12476 toX = currentMoveString[2] - AAA;
12477 toY = currentMoveString[3] - ONE;
12483 case GameUnfinished:
12484 if (appData.debugMode)
12485 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
12486 p = strchr(yy_text, '{');
12487 if (p == NULL) p = strchr(yy_text, '(');
12490 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
12492 q = strchr(p, *p == '{' ? '}' : ')');
12493 if (q != NULL) *q = NULLCHAR;
12496 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
12497 GameEnds(moveType, p, GE_FILE);
12499 if (cmailMsgLoaded) {
12501 flipView = WhiteOnMove(currentMove);
12502 if (moveType == GameUnfinished) flipView = !flipView;
12503 if (appData.debugMode)
12504 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
12509 if (appData.debugMode)
12510 fprintf(debugFP, "Parser hit end of file\n");
12511 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12517 if (WhiteOnMove(currentMove)) {
12518 GameEnds(BlackWins, "Black mates", GE_FILE);
12520 GameEnds(WhiteWins, "White mates", GE_FILE);
12524 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12530 case MoveNumberOne:
12531 if (lastLoadGameStart == GNUChessGame) {
12532 /* GNUChessGames have numbers, but they aren't move numbers */
12533 if (appData.debugMode)
12534 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12535 yy_text, (int) moveType);
12536 return LoadGameOneMove(EndOfFile); /* tail recursion */
12538 /* else fall thru */
12543 /* Reached start of next game in file */
12544 if (appData.debugMode)
12545 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
12546 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12552 if (WhiteOnMove(currentMove)) {
12553 GameEnds(BlackWins, "Black mates", GE_FILE);
12555 GameEnds(WhiteWins, "White mates", GE_FILE);
12559 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12565 case PositionDiagram: /* should not happen; ignore */
12566 case ElapsedTime: /* ignore */
12567 case NAG: /* ignore */
12568 if (appData.debugMode)
12569 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12570 yy_text, (int) moveType);
12571 return LoadGameOneMove(EndOfFile); /* tail recursion */
12574 if (appData.testLegality) {
12575 if (appData.debugMode)
12576 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
12577 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12578 (forwardMostMove / 2) + 1,
12579 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12580 DisplayError(move, 0);
12583 if (appData.debugMode)
12584 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
12585 yy_text, currentMoveString);
12586 if(currentMoveString[1] == '@') {
12587 fromX = CharToPiece(WhiteOnMove(currentMove) ? ToUpper(currentMoveString[0]) : ToLower(currentMoveString[0]));
12590 fromX = currentMoveString[0] - AAA;
12591 fromY = currentMoveString[1] - ONE;
12593 toX = currentMoveString[2] - AAA;
12594 toY = currentMoveString[3] - ONE;
12595 promoChar = currentMoveString[4];
12599 case AmbiguousMove:
12600 if (appData.debugMode)
12601 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
12602 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
12603 (forwardMostMove / 2) + 1,
12604 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12605 DisplayError(move, 0);
12610 case ImpossibleMove:
12611 if (appData.debugMode)
12612 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
12613 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12614 (forwardMostMove / 2) + 1,
12615 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12616 DisplayError(move, 0);
12622 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
12623 DrawPosition(FALSE, boards[currentMove]);
12624 DisplayBothClocks();
12625 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
12626 DisplayComment(currentMove - 1, commentList[currentMove]);
12628 (void) StopLoadGameTimer();
12630 cmailOldMove = forwardMostMove;
12633 /* currentMoveString is set as a side-effect of yylex */
12635 thinkOutput[0] = NULLCHAR;
12636 MakeMove(fromX, fromY, toX, toY, promoChar);
12637 killX = killY = kill2X = kill2Y = -1; // [HGM] lion: used up
12638 currentMove = forwardMostMove;
12643 /* Load the nth game from the given file */
12645 LoadGameFromFile (char *filename, int n, char *title, int useList)
12650 if (strcmp(filename, "-") == 0) {
12654 f = fopen(filename, "rb");
12656 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12657 DisplayError(buf, errno);
12661 if (fseek(f, 0, 0) == -1) {
12662 /* f is not seekable; probably a pipe */
12665 if (useList && n == 0) {
12666 int error = GameListBuild(f);
12668 DisplayError(_("Cannot build game list"), error);
12669 } else if (!ListEmpty(&gameList) &&
12670 ((ListGame *) gameList.tailPred)->number > 1) {
12671 GameListPopUp(f, title);
12678 return LoadGame(f, n, title, FALSE);
12683 MakeRegisteredMove ()
12685 int fromX, fromY, toX, toY;
12687 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12688 switch (cmailMoveType[lastLoadGameNumber - 1]) {
12691 if (appData.debugMode)
12692 fprintf(debugFP, "Restoring %s for game %d\n",
12693 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12695 thinkOutput[0] = NULLCHAR;
12696 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
12697 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
12698 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
12699 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
12700 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
12701 promoChar = cmailMove[lastLoadGameNumber - 1][4];
12702 MakeMove(fromX, fromY, toX, toY, promoChar);
12703 ShowMove(fromX, fromY, toX, toY);
12705 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12712 if (WhiteOnMove(currentMove)) {
12713 GameEnds(BlackWins, "Black mates", GE_PLAYER);
12715 GameEnds(WhiteWins, "White mates", GE_PLAYER);
12720 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
12727 if (WhiteOnMove(currentMove)) {
12728 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12730 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12735 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12746 /* Wrapper around LoadGame for use when a Cmail message is loaded */
12748 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
12752 if (gameNumber > nCmailGames) {
12753 DisplayError(_("No more games in this message"), 0);
12756 if (f == lastLoadGameFP) {
12757 int offset = gameNumber - lastLoadGameNumber;
12759 cmailMsg[0] = NULLCHAR;
12760 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12761 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12762 nCmailMovesRegistered--;
12764 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12765 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
12766 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
12769 if (! RegisterMove()) return FALSE;
12773 retVal = LoadGame(f, gameNumber, title, useList);
12775 /* Make move registered during previous look at this game, if any */
12776 MakeRegisteredMove();
12778 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
12779 commentList[currentMove]
12780 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
12781 DisplayComment(currentMove - 1, commentList[currentMove]);
12787 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
12789 ReloadGame (int offset)
12791 int gameNumber = lastLoadGameNumber + offset;
12792 if (lastLoadGameFP == NULL) {
12793 DisplayError(_("No game has been loaded yet"), 0);
12796 if (gameNumber <= 0) {
12797 DisplayError(_("Can't back up any further"), 0);
12800 if (cmailMsgLoaded) {
12801 return CmailLoadGame(lastLoadGameFP, gameNumber,
12802 lastLoadGameTitle, lastLoadGameUseList);
12804 return LoadGame(lastLoadGameFP, gameNumber,
12805 lastLoadGameTitle, lastLoadGameUseList);
12809 int keys[EmptySquare+1];
12812 PositionMatches (Board b1, Board b2)
12815 switch(appData.searchMode) {
12816 case 1: return CompareWithRights(b1, b2);
12818 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12819 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
12823 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12824 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
12825 sum += keys[b1[r][f]] - keys[b2[r][f]];
12829 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12830 sum += keys[b1[r][f]] - keys[b2[r][f]];
12842 int pieceList[256], quickBoard[256];
12843 ChessSquare pieceType[256] = { EmptySquare };
12844 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
12845 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
12846 int soughtTotal, turn;
12847 Boolean epOK, flipSearch;
12850 unsigned char piece, to;
12853 #define DSIZE (250000)
12855 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
12856 Move *moveDatabase = initialSpace;
12857 unsigned int movePtr, dataSize = DSIZE;
12860 MakePieceList (Board board, int *counts)
12862 int r, f, n=Q_PROMO, total=0;
12863 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
12864 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12865 int sq = f + (r<<4);
12866 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
12867 quickBoard[sq] = ++n;
12869 pieceType[n] = board[r][f];
12870 counts[board[r][f]]++;
12871 if(board[r][f] == WhiteKing) pieceList[1] = n; else
12872 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
12876 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
12881 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
12883 int sq = fromX + (fromY<<4);
12884 int piece = quickBoard[sq], rook;
12885 quickBoard[sq] = 0;
12886 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
12887 if(piece == pieceList[1] && fromY == toY) {
12888 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12889 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
12890 moveDatabase[movePtr++].piece = Q_WCASTL;
12891 quickBoard[sq] = piece;
12892 piece = quickBoard[from]; quickBoard[from] = 0;
12893 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12894 } else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
12895 quickBoard[sq] = 0; // remove Rook
12896 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
12897 moveDatabase[movePtr++].piece = Q_WCASTL;
12898 quickBoard[sq] = pieceList[1]; // put King
12900 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12903 if(piece == pieceList[2] && fromY == toY) {
12904 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12905 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
12906 moveDatabase[movePtr++].piece = Q_BCASTL;
12907 quickBoard[sq] = piece;
12908 piece = quickBoard[from]; quickBoard[from] = 0;
12909 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12910 } else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
12911 quickBoard[sq] = 0; // remove Rook
12912 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
12913 moveDatabase[movePtr++].piece = Q_BCASTL;
12914 quickBoard[sq] = pieceList[2]; // put King
12916 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12919 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
12920 quickBoard[(fromY<<4)+toX] = 0;
12921 moveDatabase[movePtr].piece = Q_EP;
12922 moveDatabase[movePtr++].to = (fromY<<4)+toX;
12923 moveDatabase[movePtr].to = sq;
12925 if(promoPiece != pieceType[piece]) {
12926 moveDatabase[movePtr++].piece = Q_PROMO;
12927 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
12929 moveDatabase[movePtr].piece = piece;
12930 quickBoard[sq] = piece;
12935 PackGame (Board board)
12937 Move *newSpace = NULL;
12938 moveDatabase[movePtr].piece = 0; // terminate previous game
12939 if(movePtr > dataSize) {
12940 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
12941 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
12942 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
12945 Move *p = moveDatabase, *q = newSpace;
12946 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
12947 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
12948 moveDatabase = newSpace;
12949 } else { // calloc failed, we must be out of memory. Too bad...
12950 dataSize = 0; // prevent calloc events for all subsequent games
12951 return 0; // and signal this one isn't cached
12955 MakePieceList(board, counts);
12960 QuickCompare (Board board, int *minCounts, int *maxCounts)
12961 { // compare according to search mode
12963 switch(appData.searchMode)
12965 case 1: // exact position match
12966 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
12967 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12968 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12971 case 2: // can have extra material on empty squares
12972 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12973 if(board[r][f] == EmptySquare) continue;
12974 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12977 case 3: // material with exact Pawn structure
12978 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12979 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
12980 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12981 } // fall through to material comparison
12982 case 4: // exact material
12983 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
12985 case 6: // material range with given imbalance
12986 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
12987 // fall through to range comparison
12988 case 5: // material range
12989 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
12995 QuickScan (Board board, Move *move)
12996 { // reconstruct game,and compare all positions in it
12997 int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
12999 int piece = move->piece;
13000 int to = move->to, from = pieceList[piece];
13001 if(found < 0) { // if already found just scan to game end for final piece count
13002 if(QuickCompare(soughtBoard, minSought, maxSought) ||
13003 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
13004 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
13005 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
13007 static int lastCounts[EmptySquare+1];
13009 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
13010 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
13011 } else stretch = 0;
13012 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
13013 if(found >= 0 && !appData.minPieces) return found;
13015 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
13016 if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
13017 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
13018 piece = (++move)->piece;
13019 from = pieceList[piece];
13020 counts[pieceType[piece]]--;
13021 pieceType[piece] = (ChessSquare) move->to;
13022 counts[move->to]++;
13023 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
13024 counts[pieceType[quickBoard[to]]]--;
13025 quickBoard[to] = 0; total--;
13028 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
13029 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
13030 from = pieceList[piece]; // so this must be King
13031 quickBoard[from] = 0;
13032 pieceList[piece] = to;
13033 from = pieceList[(++move)->piece]; // for FRC this has to be done here
13034 quickBoard[from] = 0; // rook
13035 quickBoard[to] = piece;
13036 to = move->to; piece = move->piece;
13040 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
13041 if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
13042 quickBoard[from] = 0;
13044 quickBoard[to] = piece;
13045 pieceList[piece] = to;
13055 flipSearch = FALSE;
13056 CopyBoard(soughtBoard, boards[currentMove]);
13057 soughtTotal = MakePieceList(soughtBoard, maxSought);
13058 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
13059 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
13060 CopyBoard(reverseBoard, boards[currentMove]);
13061 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13062 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
13063 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
13064 reverseBoard[r][f] = piece;
13066 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
13067 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
13068 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
13069 || (boards[currentMove][CASTLING][2] == NoRights ||
13070 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
13071 && (boards[currentMove][CASTLING][5] == NoRights ||
13072 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
13075 CopyBoard(flipBoard, soughtBoard);
13076 CopyBoard(rotateBoard, reverseBoard);
13077 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
13078 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
13079 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
13082 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
13083 if(appData.searchMode >= 5) {
13084 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
13085 MakePieceList(soughtBoard, minSought);
13086 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
13088 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
13089 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
13092 GameInfo dummyInfo;
13093 static int creatingBook;
13096 GameContainsPosition (FILE *f, ListGame *lg)
13098 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
13099 int fromX, fromY, toX, toY;
13101 static int initDone=FALSE;
13103 // weed out games based on numerical tag comparison
13104 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
13105 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
13106 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
13107 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
13109 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
13112 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
13113 else CopyBoard(boards[scratch], initialPosition); // default start position
13116 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
13117 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
13120 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13121 fseek(f, lg->offset, 0);
13124 yyboardindex = scratch;
13125 quickFlag = plyNr+1;
13130 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
13136 if(plyNr) return -1; // after we have seen moves, this is for new game
13139 case AmbiguousMove: // we cannot reconstruct the game beyond these two
13140 case ImpossibleMove:
13141 case WhiteWins: // game ends here with these four
13144 case GameUnfinished:
13148 if(appData.testLegality) return -1;
13149 case WhiteCapturesEnPassant:
13150 case BlackCapturesEnPassant:
13151 case WhitePromotion:
13152 case BlackPromotion:
13153 case WhiteNonPromotion:
13154 case BlackNonPromotion:
13157 case WhiteKingSideCastle:
13158 case WhiteQueenSideCastle:
13159 case BlackKingSideCastle:
13160 case BlackQueenSideCastle:
13161 case WhiteKingSideCastleWild:
13162 case WhiteQueenSideCastleWild:
13163 case BlackKingSideCastleWild:
13164 case BlackQueenSideCastleWild:
13165 case WhiteHSideCastleFR:
13166 case WhiteASideCastleFR:
13167 case BlackHSideCastleFR:
13168 case BlackASideCastleFR:
13169 fromX = currentMoveString[0] - AAA;
13170 fromY = currentMoveString[1] - ONE;
13171 toX = currentMoveString[2] - AAA;
13172 toY = currentMoveString[3] - ONE;
13173 promoChar = currentMoveString[4];
13177 fromX = next == WhiteDrop ?
13178 (int) CharToPiece(ToUpper(currentMoveString[0])) :
13179 (int) CharToPiece(ToLower(currentMoveString[0]));
13181 toX = currentMoveString[2] - AAA;
13182 toY = currentMoveString[3] - ONE;
13186 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
13188 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
13189 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
13190 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
13191 if(appData.findMirror) {
13192 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
13193 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
13198 /* Load the nth game from open file f */
13200 LoadGame (FILE *f, int gameNumber, char *title, int useList)
13204 int gn = gameNumber;
13205 ListGame *lg = NULL;
13206 int numPGNTags = 0, i;
13208 GameMode oldGameMode;
13209 VariantClass v, oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
13210 char oldName[MSG_SIZ];
13212 safeStrCpy(oldName, engineVariant, MSG_SIZ); v = oldVariant;
13214 if (appData.debugMode)
13215 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
13217 if (gameMode == Training )
13218 SetTrainingModeOff();
13220 oldGameMode = gameMode;
13221 if (gameMode != BeginningOfGame) {
13222 Reset(FALSE, TRUE);
13224 killX = killY = kill2X = kill2Y = -1; // [HGM] lion: in case we did not Reset
13227 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
13228 fclose(lastLoadGameFP);
13232 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
13235 fseek(f, lg->offset, 0);
13236 GameListHighlight(gameNumber);
13237 pos = lg->position;
13241 if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
13242 appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
13244 DisplayError(_("Game number out of range"), 0);
13249 if (fseek(f, 0, 0) == -1) {
13250 if (f == lastLoadGameFP ?
13251 gameNumber == lastLoadGameNumber + 1 :
13255 DisplayError(_("Can't seek on game file"), 0);
13260 lastLoadGameFP = f;
13261 lastLoadGameNumber = gameNumber;
13262 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
13263 lastLoadGameUseList = useList;
13267 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
13268 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
13269 lg->gameInfo.black);
13271 } else if (*title != NULLCHAR) {
13272 if (gameNumber > 1) {
13273 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
13276 DisplayTitle(title);
13280 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
13281 gameMode = PlayFromGameFile;
13285 currentMove = forwardMostMove = backwardMostMove = 0;
13286 CopyBoard(boards[0], initialPosition);
13290 * Skip the first gn-1 games in the file.
13291 * Also skip over anything that precedes an identifiable
13292 * start of game marker, to avoid being confused by
13293 * garbage at the start of the file. Currently
13294 * recognized start of game markers are the move number "1",
13295 * the pattern "gnuchess .* game", the pattern
13296 * "^[#;%] [^ ]* game file", and a PGN tag block.
13297 * A game that starts with one of the latter two patterns
13298 * will also have a move number 1, possibly
13299 * following a position diagram.
13300 * 5-4-02: Let's try being more lenient and allowing a game to
13301 * start with an unnumbered move. Does that break anything?
13303 cm = lastLoadGameStart = EndOfFile;
13305 yyboardindex = forwardMostMove;
13306 cm = (ChessMove) Myylex();
13309 if (cmailMsgLoaded) {
13310 nCmailGames = CMAIL_MAX_GAMES - gn;
13313 DisplayError(_("Game not found in file"), 0);
13320 lastLoadGameStart = cm;
13323 case MoveNumberOne:
13324 switch (lastLoadGameStart) {
13329 case MoveNumberOne:
13331 gn--; /* count this game */
13332 lastLoadGameStart = cm;
13341 switch (lastLoadGameStart) {
13344 case MoveNumberOne:
13346 gn--; /* count this game */
13347 lastLoadGameStart = cm;
13350 lastLoadGameStart = cm; /* game counted already */
13358 yyboardindex = forwardMostMove;
13359 cm = (ChessMove) Myylex();
13360 } while (cm == PGNTag || cm == Comment);
13367 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
13368 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
13369 != CMAIL_OLD_RESULT) {
13371 cmailResult[ CMAIL_MAX_GAMES
13372 - gn - 1] = CMAIL_OLD_RESULT;
13379 /* Only a NormalMove can be at the start of a game
13380 * without a position diagram. */
13381 if (lastLoadGameStart == EndOfFile ) {
13383 lastLoadGameStart = MoveNumberOne;
13392 if (appData.debugMode)
13393 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
13395 for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; } // reset VariantMen
13397 if (cm == XBoardGame) {
13398 /* Skip any header junk before position diagram and/or move 1 */
13400 yyboardindex = forwardMostMove;
13401 cm = (ChessMove) Myylex();
13403 if (cm == EndOfFile ||
13404 cm == GNUChessGame || cm == XBoardGame) {
13405 /* Empty game; pretend end-of-file and handle later */
13410 if (cm == MoveNumberOne || cm == PositionDiagram ||
13411 cm == PGNTag || cm == Comment)
13414 } else if (cm == GNUChessGame) {
13415 if (gameInfo.event != NULL) {
13416 free(gameInfo.event);
13418 gameInfo.event = StrSave(yy_text);
13421 startedFromSetupPosition = startedFromPositionFile; // [HGM]
13422 while (cm == PGNTag) {
13423 if (appData.debugMode)
13424 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
13425 err = ParsePGNTag(yy_text, &gameInfo);
13426 if (!err) numPGNTags++;
13428 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
13429 if(gameInfo.variant != oldVariant && (gameInfo.variant != VariantNormal || gameInfo.variantName == NULL || *gameInfo.variantName == NULLCHAR)) {
13430 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
13431 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
13432 InitPosition(TRUE);
13433 oldVariant = gameInfo.variant;
13434 if (appData.debugMode)
13435 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
13439 if (gameInfo.fen != NULL) {
13440 Board initial_position;
13441 startedFromSetupPosition = TRUE;
13442 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
13444 DisplayError(_("Bad FEN position in file"), 0);
13447 CopyBoard(boards[0], initial_position);
13448 if(*engineVariant || gameInfo.variant == VariantFairy) // [HGM] for now, assume FEN in engine-defined variant game is default initial position
13449 CopyBoard(initialPosition, initial_position);
13450 if (blackPlaysFirst) {
13451 currentMove = forwardMostMove = backwardMostMove = 1;
13452 CopyBoard(boards[1], initial_position);
13453 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13454 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13455 timeRemaining[0][1] = whiteTimeRemaining;
13456 timeRemaining[1][1] = blackTimeRemaining;
13457 if (commentList[0] != NULL) {
13458 commentList[1] = commentList[0];
13459 commentList[0] = NULL;
13462 currentMove = forwardMostMove = backwardMostMove = 0;
13464 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
13466 initialRulePlies = FENrulePlies;
13467 for( i=0; i< nrCastlingRights; i++ )
13468 initialRights[i] = initial_position[CASTLING][i];
13470 yyboardindex = forwardMostMove;
13471 free(gameInfo.fen);
13472 gameInfo.fen = NULL;
13475 yyboardindex = forwardMostMove;
13476 cm = (ChessMove) Myylex();
13478 /* Handle comments interspersed among the tags */
13479 while (cm == Comment) {
13481 if (appData.debugMode)
13482 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13484 AppendComment(currentMove, p, FALSE);
13485 yyboardindex = forwardMostMove;
13486 cm = (ChessMove) Myylex();
13490 /* don't rely on existence of Event tag since if game was
13491 * pasted from clipboard the Event tag may not exist
13493 if (numPGNTags > 0){
13495 if (gameInfo.variant == VariantNormal) {
13496 VariantClass v = StringToVariant(gameInfo.event);
13497 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
13498 if(v < VariantShogi) gameInfo.variant = v;
13501 if( appData.autoDisplayTags ) {
13502 tags = PGNTags(&gameInfo);
13503 TagsPopUp(tags, CmailMsg());
13508 /* Make something up, but don't display it now */
13513 if (cm == PositionDiagram) {
13516 Board initial_position;
13518 if (appData.debugMode)
13519 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
13521 if (!startedFromSetupPosition) {
13523 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
13524 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
13535 initial_position[i][j++] = CharToPiece(*p);
13538 while (*p == ' ' || *p == '\t' ||
13539 *p == '\n' || *p == '\r') p++;
13541 if (strncmp(p, "black", strlen("black"))==0)
13542 blackPlaysFirst = TRUE;
13544 blackPlaysFirst = FALSE;
13545 startedFromSetupPosition = TRUE;
13547 CopyBoard(boards[0], initial_position);
13548 if (blackPlaysFirst) {
13549 currentMove = forwardMostMove = backwardMostMove = 1;
13550 CopyBoard(boards[1], initial_position);
13551 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13552 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13553 timeRemaining[0][1] = whiteTimeRemaining;
13554 timeRemaining[1][1] = blackTimeRemaining;
13555 if (commentList[0] != NULL) {
13556 commentList[1] = commentList[0];
13557 commentList[0] = NULL;
13560 currentMove = forwardMostMove = backwardMostMove = 0;
13563 yyboardindex = forwardMostMove;
13564 cm = (ChessMove) Myylex();
13567 if(!creatingBook) {
13568 if (first.pr == NoProc) {
13569 StartChessProgram(&first);
13571 InitChessProgram(&first, FALSE);
13572 if(gameInfo.variant == VariantUnknown && *oldName) {
13573 safeStrCpy(engineVariant, oldName, MSG_SIZ);
13574 gameInfo.variant = v;
13576 SendToProgram("force\n", &first);
13577 if (startedFromSetupPosition) {
13578 SendBoard(&first, forwardMostMove);
13579 if (appData.debugMode) {
13580 fprintf(debugFP, "Load Game\n");
13582 DisplayBothClocks();
13586 /* [HGM] server: flag to write setup moves in broadcast file as one */
13587 loadFlag = appData.suppressLoadMoves;
13589 while (cm == Comment) {
13591 if (appData.debugMode)
13592 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13594 AppendComment(currentMove, p, FALSE);
13595 yyboardindex = forwardMostMove;
13596 cm = (ChessMove) Myylex();
13599 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
13600 cm == WhiteWins || cm == BlackWins ||
13601 cm == GameIsDrawn || cm == GameUnfinished) {
13602 DisplayMessage("", _("No moves in game"));
13603 if (cmailMsgLoaded) {
13604 if (appData.debugMode)
13605 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
13609 DrawPosition(FALSE, boards[currentMove]);
13610 DisplayBothClocks();
13611 gameMode = EditGame;
13618 // [HGM] PV info: routine tests if comment empty
13619 if (!matchMode && (pausing || appData.timeDelay != 0)) {
13620 DisplayComment(currentMove - 1, commentList[currentMove]);
13622 if (!matchMode && appData.timeDelay != 0)
13623 DrawPosition(FALSE, boards[currentMove]);
13625 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
13626 programStats.ok_to_send = 1;
13629 /* if the first token after the PGN tags is a move
13630 * and not move number 1, retrieve it from the parser
13632 if (cm != MoveNumberOne)
13633 LoadGameOneMove(cm);
13635 /* load the remaining moves from the file */
13636 while (LoadGameOneMove(EndOfFile)) {
13637 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13638 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13641 /* rewind to the start of the game */
13642 currentMove = backwardMostMove;
13644 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13646 if (oldGameMode == AnalyzeFile) {
13647 appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
13648 AnalyzeFileEvent();
13650 if (oldGameMode == AnalyzeMode) {
13651 AnalyzeFileEvent();
13654 if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
13655 long int w, b; // [HGM] adjourn: restore saved clock times
13656 char *p = strstr(gameInfo.resultDetails, "(Clocks:");
13657 if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
13658 timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
13659 timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
13663 if(creatingBook) return TRUE;
13664 if (!matchMode && pos > 0) {
13665 ToNrEvent(pos); // [HGM] no autoplay if selected on position
13667 if (matchMode || appData.timeDelay == 0) {
13669 } else if (appData.timeDelay > 0) {
13670 AutoPlayGameLoop();
13673 if (appData.debugMode)
13674 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
13676 loadFlag = 0; /* [HGM] true game starts */
13680 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
13682 ReloadPosition (int offset)
13684 int positionNumber = lastLoadPositionNumber + offset;
13685 if (lastLoadPositionFP == NULL) {
13686 DisplayError(_("No position has been loaded yet"), 0);
13689 if (positionNumber <= 0) {
13690 DisplayError(_("Can't back up any further"), 0);
13693 return LoadPosition(lastLoadPositionFP, positionNumber,
13694 lastLoadPositionTitle);
13697 /* Load the nth position from the given file */
13699 LoadPositionFromFile (char *filename, int n, char *title)
13704 if (strcmp(filename, "-") == 0) {
13705 return LoadPosition(stdin, n, "stdin");
13707 f = fopen(filename, "rb");
13709 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13710 DisplayError(buf, errno);
13713 return LoadPosition(f, n, title);
13718 /* Load the nth position from the given open file, and close it */
13720 LoadPosition (FILE *f, int positionNumber, char *title)
13722 char *p, line[MSG_SIZ];
13723 Board initial_position;
13724 int i, j, fenMode, pn;
13726 if (gameMode == Training )
13727 SetTrainingModeOff();
13729 if (gameMode != BeginningOfGame) {
13730 Reset(FALSE, TRUE);
13732 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
13733 fclose(lastLoadPositionFP);
13735 if (positionNumber == 0) positionNumber = 1;
13736 lastLoadPositionFP = f;
13737 lastLoadPositionNumber = positionNumber;
13738 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
13739 if (first.pr == NoProc && !appData.noChessProgram) {
13740 StartChessProgram(&first);
13741 InitChessProgram(&first, FALSE);
13743 pn = positionNumber;
13744 if (positionNumber < 0) {
13745 /* Negative position number means to seek to that byte offset */
13746 if (fseek(f, -positionNumber, 0) == -1) {
13747 DisplayError(_("Can't seek on position file"), 0);
13752 if (fseek(f, 0, 0) == -1) {
13753 if (f == lastLoadPositionFP ?
13754 positionNumber == lastLoadPositionNumber + 1 :
13755 positionNumber == 1) {
13758 DisplayError(_("Can't seek on position file"), 0);
13763 /* See if this file is FEN or old-style xboard */
13764 if (fgets(line, MSG_SIZ, f) == NULL) {
13765 DisplayError(_("Position not found in file"), 0);
13768 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces (or * for blackout)
13769 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || line[0] == '*' || CharToPiece(line[0]) != EmptySquare;
13772 if (fenMode || line[0] == '#') pn--;
13774 /* skip positions before number pn */
13775 if (fgets(line, MSG_SIZ, f) == NULL) {
13777 DisplayError(_("Position not found in file"), 0);
13780 if (fenMode || line[0] == '#') pn--;
13786 if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
13787 DisplayError(_("Bad FEN position in file"), 0);
13790 if((strchr(line, ';')) && (p = strstr(line, " bm "))) { // EPD with best move
13791 sscanf(p+4, "%[^;]", bestMove);
13792 } else *bestMove = NULLCHAR;
13793 if((strchr(line, ';')) && (p = strstr(line, " am "))) { // EPD with avoid move
13794 sscanf(p+4, "%[^;]", avoidMove);
13795 } else *avoidMove = NULLCHAR;
13797 (void) fgets(line, MSG_SIZ, f);
13798 (void) fgets(line, MSG_SIZ, f);
13800 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13801 (void) fgets(line, MSG_SIZ, f);
13802 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
13805 initial_position[i][j++] = CharToPiece(*p);
13809 blackPlaysFirst = FALSE;
13811 (void) fgets(line, MSG_SIZ, f);
13812 if (strncmp(line, "black", strlen("black"))==0)
13813 blackPlaysFirst = TRUE;
13816 startedFromSetupPosition = TRUE;
13818 CopyBoard(boards[0], initial_position);
13819 if (blackPlaysFirst) {
13820 currentMove = forwardMostMove = backwardMostMove = 1;
13821 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13822 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13823 CopyBoard(boards[1], initial_position);
13824 DisplayMessage("", _("Black to play"));
13826 currentMove = forwardMostMove = backwardMostMove = 0;
13827 DisplayMessage("", _("White to play"));
13829 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
13830 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
13831 SendToProgram("force\n", &first);
13832 SendBoard(&first, forwardMostMove);
13834 if (appData.debugMode) {
13836 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
13837 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
13838 fprintf(debugFP, "Load Position\n");
13841 if (positionNumber > 1) {
13842 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
13843 DisplayTitle(line);
13845 DisplayTitle(title);
13847 gameMode = EditGame;
13850 timeRemaining[0][1] = whiteTimeRemaining;
13851 timeRemaining[1][1] = blackTimeRemaining;
13852 DrawPosition(FALSE, boards[currentMove]);
13859 CopyPlayerNameIntoFileName (char **dest, char *src)
13861 while (*src != NULLCHAR && *src != ',') {
13866 *(*dest)++ = *src++;
13872 DefaultFileName (char *ext)
13874 static char def[MSG_SIZ];
13877 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
13879 CopyPlayerNameIntoFileName(&p, gameInfo.white);
13881 CopyPlayerNameIntoFileName(&p, gameInfo.black);
13883 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
13890 /* Save the current game to the given file */
13892 SaveGameToFile (char *filename, int append)
13896 int result, i, t,tot=0;
13898 if (strcmp(filename, "-") == 0) {
13899 return SaveGame(stdout, 0, NULL);
13901 for(i=0; i<10; i++) { // upto 10 tries
13902 f = fopen(filename, append ? "a" : "w");
13903 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
13904 if(f || errno != 13) break;
13905 DoSleep(t = 5 + random()%11); // wait 5-15 msec
13909 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13910 DisplayError(buf, errno);
13913 safeStrCpy(buf, lastMsg, MSG_SIZ);
13914 DisplayMessage(_("Waiting for access to save file"), "");
13915 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
13916 DisplayMessage(_("Saving game"), "");
13917 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
13918 result = SaveGame(f, 0, NULL);
13919 DisplayMessage(buf, "");
13926 SavePart (char *str)
13928 static char buf[MSG_SIZ];
13931 p = strchr(str, ' ');
13932 if (p == NULL) return str;
13933 strncpy(buf, str, p - str);
13934 buf[p - str] = NULLCHAR;
13938 #define PGN_MAX_LINE 75
13940 #define PGN_SIDE_WHITE 0
13941 #define PGN_SIDE_BLACK 1
13944 FindFirstMoveOutOfBook (int side)
13948 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
13949 int index = backwardMostMove;
13950 int has_book_hit = 0;
13952 if( (index % 2) != side ) {
13956 while( index < forwardMostMove ) {
13957 /* Check to see if engine is in book */
13958 int depth = pvInfoList[index].depth;
13959 int score = pvInfoList[index].score;
13965 else if( score == 0 && depth == 63 ) {
13966 in_book = 1; /* Zappa */
13968 else if( score == 2 && depth == 99 ) {
13969 in_book = 1; /* Abrok */
13972 has_book_hit += in_book;
13988 GetOutOfBookInfo (char * buf)
13992 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13994 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
13995 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
13999 if( oob[0] >= 0 || oob[1] >= 0 ) {
14000 for( i=0; i<2; i++ ) {
14004 if( i > 0 && oob[0] >= 0 ) {
14005 strcat( buf, " " );
14008 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
14009 sprintf( buf+strlen(buf), "%s%.2f",
14010 pvInfoList[idx].score >= 0 ? "+" : "",
14011 pvInfoList[idx].score / 100.0 );
14017 /* Save game in PGN style */
14019 SaveGamePGN2 (FILE *f)
14021 int i, offset, linelen, newblock;
14024 int movelen, numlen, blank;
14025 char move_buffer[100]; /* [AS] Buffer for move+PV info */
14027 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14029 PrintPGNTags(f, &gameInfo);
14031 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
14033 if (backwardMostMove > 0 || startedFromSetupPosition) {
14034 char *fen = PositionToFEN(backwardMostMove, NULL, 1);
14035 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
14036 fprintf(f, "\n{--------------\n");
14037 PrintPosition(f, backwardMostMove);
14038 fprintf(f, "--------------}\n");
14042 /* [AS] Out of book annotation */
14043 if( appData.saveOutOfBookInfo ) {
14046 GetOutOfBookInfo( buf );
14048 if( buf[0] != '\0' ) {
14049 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
14056 i = backwardMostMove;
14060 while (i < forwardMostMove) {
14061 /* Print comments preceding this move */
14062 if (commentList[i] != NULL) {
14063 if (linelen > 0) fprintf(f, "\n");
14064 fprintf(f, "%s", commentList[i]);
14069 /* Format move number */
14071 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
14074 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
14076 numtext[0] = NULLCHAR;
14078 numlen = strlen(numtext);
14081 /* Print move number */
14082 blank = linelen > 0 && numlen > 0;
14083 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
14092 fprintf(f, "%s", numtext);
14096 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
14097 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
14100 blank = linelen > 0 && movelen > 0;
14101 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14110 fprintf(f, "%s", move_buffer);
14111 linelen += movelen;
14113 /* [AS] Add PV info if present */
14114 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
14115 /* [HGM] add time */
14116 char buf[MSG_SIZ]; int seconds;
14118 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
14124 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
14127 seconds = (seconds + 4)/10; // round to full seconds
14129 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
14131 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
14134 if(appData.cumulativeTimePGN) {
14135 snprintf(buf, MSG_SIZ, " %+ld", timeRemaining[i & 1][i+1]/1000);
14138 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
14139 pvInfoList[i].score >= 0 ? "+" : "",
14140 pvInfoList[i].score / 100.0,
14141 pvInfoList[i].depth,
14144 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
14146 /* Print score/depth */
14147 blank = linelen > 0 && movelen > 0;
14148 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
14157 fprintf(f, "%s", move_buffer);
14158 linelen += movelen;
14164 /* Start a new line */
14165 if (linelen > 0) fprintf(f, "\n");
14167 /* Print comments after last move */
14168 if (commentList[i] != NULL) {
14169 fprintf(f, "%s\n", commentList[i]);
14173 if (gameInfo.resultDetails != NULL &&
14174 gameInfo.resultDetails[0] != NULLCHAR) {
14175 char buf[MSG_SIZ], *p = gameInfo.resultDetails;
14176 if(gameInfo.result == GameUnfinished && appData.clockMode &&
14177 (gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
14178 snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
14179 fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
14181 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14185 /* Save game in PGN style and close the file */
14187 SaveGamePGN (FILE *f)
14191 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14195 /* Save game in old style and close the file */
14197 SaveGameOldStyle (FILE *f)
14202 tm = time((time_t *) NULL);
14204 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
14207 if (backwardMostMove > 0 || startedFromSetupPosition) {
14208 fprintf(f, "\n[--------------\n");
14209 PrintPosition(f, backwardMostMove);
14210 fprintf(f, "--------------]\n");
14215 i = backwardMostMove;
14216 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
14218 while (i < forwardMostMove) {
14219 if (commentList[i] != NULL) {
14220 fprintf(f, "[%s]\n", commentList[i]);
14223 if ((i % 2) == 1) {
14224 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
14227 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
14229 if (commentList[i] != NULL) {
14233 if (i >= forwardMostMove) {
14237 fprintf(f, "%s\n", parseList[i]);
14242 if (commentList[i] != NULL) {
14243 fprintf(f, "[%s]\n", commentList[i]);
14246 /* This isn't really the old style, but it's close enough */
14247 if (gameInfo.resultDetails != NULL &&
14248 gameInfo.resultDetails[0] != NULLCHAR) {
14249 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
14250 gameInfo.resultDetails);
14252 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
14259 /* Save the current game to open file f and close the file */
14261 SaveGame (FILE *f, int dummy, char *dummy2)
14263 if (gameMode == EditPosition) EditPositionDone(TRUE);
14264 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
14265 if (appData.oldSaveStyle)
14266 return SaveGameOldStyle(f);
14268 return SaveGamePGN(f);
14271 /* Save the current position to the given file */
14273 SavePositionToFile (char *filename)
14278 if (strcmp(filename, "-") == 0) {
14279 return SavePosition(stdout, 0, NULL);
14281 f = fopen(filename, "a");
14283 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
14284 DisplayError(buf, errno);
14287 safeStrCpy(buf, lastMsg, MSG_SIZ);
14288 DisplayMessage(_("Waiting for access to save file"), "");
14289 flock(fileno(f), LOCK_EX); // [HGM] lock
14290 DisplayMessage(_("Saving position"), "");
14291 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
14292 SavePosition(f, 0, NULL);
14293 DisplayMessage(buf, "");
14299 /* Save the current position to the given open file and close the file */
14301 SavePosition (FILE *f, int dummy, char *dummy2)
14306 if (gameMode == EditPosition) EditPositionDone(TRUE);
14307 if (appData.oldSaveStyle) {
14308 tm = time((time_t *) NULL);
14310 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
14312 fprintf(f, "[--------------\n");
14313 PrintPosition(f, currentMove);
14314 fprintf(f, "--------------]\n");
14316 fen = PositionToFEN(currentMove, NULL, 1);
14317 fprintf(f, "%s\n", fen);
14325 ReloadCmailMsgEvent (int unregister)
14328 static char *inFilename = NULL;
14329 static char *outFilename;
14331 struct stat inbuf, outbuf;
14334 /* Any registered moves are unregistered if unregister is set, */
14335 /* i.e. invoked by the signal handler */
14337 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14338 cmailMoveRegistered[i] = FALSE;
14339 if (cmailCommentList[i] != NULL) {
14340 free(cmailCommentList[i]);
14341 cmailCommentList[i] = NULL;
14344 nCmailMovesRegistered = 0;
14347 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
14348 cmailResult[i] = CMAIL_NOT_RESULT;
14352 if (inFilename == NULL) {
14353 /* Because the filenames are static they only get malloced once */
14354 /* and they never get freed */
14355 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
14356 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
14358 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
14359 sprintf(outFilename, "%s.out", appData.cmailGameName);
14362 status = stat(outFilename, &outbuf);
14364 cmailMailedMove = FALSE;
14366 status = stat(inFilename, &inbuf);
14367 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
14370 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
14371 counts the games, notes how each one terminated, etc.
14373 It would be nice to remove this kludge and instead gather all
14374 the information while building the game list. (And to keep it
14375 in the game list nodes instead of having a bunch of fixed-size
14376 parallel arrays.) Note this will require getting each game's
14377 termination from the PGN tags, as the game list builder does
14378 not process the game moves. --mann
14380 cmailMsgLoaded = TRUE;
14381 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
14383 /* Load first game in the file or popup game menu */
14384 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
14386 #endif /* !WIN32 */
14394 char string[MSG_SIZ];
14396 if ( cmailMailedMove
14397 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
14398 return TRUE; /* Allow free viewing */
14401 /* Unregister move to ensure that we don't leave RegisterMove */
14402 /* with the move registered when the conditions for registering no */
14404 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
14405 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
14406 nCmailMovesRegistered --;
14408 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
14410 free(cmailCommentList[lastLoadGameNumber - 1]);
14411 cmailCommentList[lastLoadGameNumber - 1] = NULL;
14415 if (cmailOldMove == -1) {
14416 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
14420 if (currentMove > cmailOldMove + 1) {
14421 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
14425 if (currentMove < cmailOldMove) {
14426 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
14430 if (forwardMostMove > currentMove) {
14431 /* Silently truncate extra moves */
14435 if ( (currentMove == cmailOldMove + 1)
14436 || ( (currentMove == cmailOldMove)
14437 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
14438 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
14439 if (gameInfo.result != GameUnfinished) {
14440 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
14443 if (commentList[currentMove] != NULL) {
14444 cmailCommentList[lastLoadGameNumber - 1]
14445 = StrSave(commentList[currentMove]);
14447 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
14449 if (appData.debugMode)
14450 fprintf(debugFP, "Saving %s for game %d\n",
14451 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
14453 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
14455 f = fopen(string, "w");
14456 if (appData.oldSaveStyle) {
14457 SaveGameOldStyle(f); /* also closes the file */
14459 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
14460 f = fopen(string, "w");
14461 SavePosition(f, 0, NULL); /* also closes the file */
14463 fprintf(f, "{--------------\n");
14464 PrintPosition(f, currentMove);
14465 fprintf(f, "--------------}\n\n");
14467 SaveGame(f, 0, NULL); /* also closes the file*/
14470 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
14471 nCmailMovesRegistered ++;
14472 } else if (nCmailGames == 1) {
14473 DisplayError(_("You have not made a move yet"), 0);
14484 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
14485 FILE *commandOutput;
14486 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
14487 int nBytes = 0; /* Suppress warnings on uninitialized variables */
14493 if (! cmailMsgLoaded) {
14494 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
14498 if (nCmailGames == nCmailResults) {
14499 DisplayError(_("No unfinished games"), 0);
14503 #if CMAIL_PROHIBIT_REMAIL
14504 if (cmailMailedMove) {
14505 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);
14506 DisplayError(msg, 0);
14511 if (! (cmailMailedMove || RegisterMove())) return;
14513 if ( cmailMailedMove
14514 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
14515 snprintf(string, MSG_SIZ, partCommandString,
14516 appData.debugMode ? " -v" : "", appData.cmailGameName);
14517 commandOutput = popen(string, "r");
14519 if (commandOutput == NULL) {
14520 DisplayError(_("Failed to invoke cmail"), 0);
14522 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
14523 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
14525 if (nBuffers > 1) {
14526 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
14527 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
14528 nBytes = MSG_SIZ - 1;
14530 (void) memcpy(msg, buffer, nBytes);
14532 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
14534 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
14535 cmailMailedMove = TRUE; /* Prevent >1 moves */
14538 for (i = 0; i < nCmailGames; i ++) {
14539 if (cmailResult[i] == CMAIL_NOT_RESULT) {
14544 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
14546 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
14548 appData.cmailGameName,
14550 LoadGameFromFile(buffer, 1, buffer, FALSE);
14551 cmailMsgLoaded = FALSE;
14555 DisplayInformation(msg);
14556 pclose(commandOutput);
14559 if ((*cmailMsg) != '\0') {
14560 DisplayInformation(cmailMsg);
14565 #endif /* !WIN32 */
14574 int prependComma = 0;
14576 char string[MSG_SIZ]; /* Space for game-list */
14579 if (!cmailMsgLoaded) return "";
14581 if (cmailMailedMove) {
14582 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
14584 /* Create a list of games left */
14585 snprintf(string, MSG_SIZ, "[");
14586 for (i = 0; i < nCmailGames; i ++) {
14587 if (! ( cmailMoveRegistered[i]
14588 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
14589 if (prependComma) {
14590 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
14592 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
14596 strcat(string, number);
14599 strcat(string, "]");
14601 if (nCmailMovesRegistered + nCmailResults == 0) {
14602 switch (nCmailGames) {
14604 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
14608 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
14612 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
14617 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
14619 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
14624 if (nCmailResults == nCmailGames) {
14625 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
14627 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
14632 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
14644 if (gameMode == Training)
14645 SetTrainingModeOff();
14648 cmailMsgLoaded = FALSE;
14649 if (appData.icsActive) {
14650 SendToICS(ics_prefix);
14651 SendToICS("refresh\n");
14656 ExitEvent (int status)
14660 /* Give up on clean exit */
14664 /* Keep trying for clean exit */
14668 if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
14669 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
14671 if (telnetISR != NULL) {
14672 RemoveInputSource(telnetISR);
14674 if (icsPR != NoProc) {
14675 DestroyChildProcess(icsPR, TRUE);
14678 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
14679 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
14681 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
14682 /* make sure this other one finishes before killing it! */
14683 if(endingGame) { int count = 0;
14684 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
14685 while(endingGame && count++ < 10) DoSleep(1);
14686 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
14689 /* Kill off chess programs */
14690 if (first.pr != NoProc) {
14693 DoSleep( appData.delayBeforeQuit );
14694 SendToProgram("quit\n", &first);
14695 DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
14697 if (second.pr != NoProc) {
14698 DoSleep( appData.delayBeforeQuit );
14699 SendToProgram("quit\n", &second);
14700 DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
14702 if (first.isr != NULL) {
14703 RemoveInputSource(first.isr);
14705 if (second.isr != NULL) {
14706 RemoveInputSource(second.isr);
14709 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
14710 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
14712 ShutDownFrontEnd();
14717 PauseEngine (ChessProgramState *cps)
14719 SendToProgram("pause\n", cps);
14724 UnPauseEngine (ChessProgramState *cps)
14726 SendToProgram("resume\n", cps);
14733 if (appData.debugMode)
14734 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
14738 if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
14740 if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
14741 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
14742 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
14744 if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
14745 HandleMachineMove(stashedInputMove, stalledEngine);
14746 stalledEngine = NULL;
14749 if (gameMode == MachinePlaysWhite ||
14750 gameMode == TwoMachinesPlay ||
14751 gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
14752 if(first.pause) UnPauseEngine(&first);
14753 else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
14754 if(second.pause) UnPauseEngine(&second);
14755 else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
14758 DisplayBothClocks();
14760 if (gameMode == PlayFromGameFile) {
14761 if (appData.timeDelay >= 0)
14762 AutoPlayGameLoop();
14763 } else if (gameMode == IcsExamining && pauseExamInvalid) {
14764 Reset(FALSE, TRUE);
14765 SendToICS(ics_prefix);
14766 SendToICS("refresh\n");
14767 } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
14768 ForwardInner(forwardMostMove);
14770 pauseExamInvalid = FALSE;
14772 switch (gameMode) {
14776 pauseExamForwardMostMove = forwardMostMove;
14777 pauseExamInvalid = FALSE;
14780 case IcsPlayingWhite:
14781 case IcsPlayingBlack:
14785 case PlayFromGameFile:
14786 (void) StopLoadGameTimer();
14790 case BeginningOfGame:
14791 if (appData.icsActive) return;
14792 /* else fall through */
14793 case MachinePlaysWhite:
14794 case MachinePlaysBlack:
14795 case TwoMachinesPlay:
14796 if (forwardMostMove == 0)
14797 return; /* don't pause if no one has moved */
14798 if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
14799 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
14800 if(onMove->pause) { // thinking engine can be paused
14801 PauseEngine(onMove); // do it
14802 if(onMove->other->pause) // pondering opponent can always be paused immediately
14803 PauseEngine(onMove->other);
14805 SendToProgram("easy\n", onMove->other);
14807 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
14808 } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
14810 PauseEngine(&first);
14812 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
14813 } else { // human on move, pause pondering by either method
14815 PauseEngine(&first);
14816 else if(appData.ponderNextMove)
14817 SendToProgram("easy\n", &first);
14820 // if no immediate pausing is possible, wait for engine to move, and stop clocks then
14830 EditCommentEvent ()
14832 char title[MSG_SIZ];
14834 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
14835 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
14837 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
14838 WhiteOnMove(currentMove - 1) ? " " : ".. ",
14839 parseList[currentMove - 1]);
14842 EditCommentPopUp(currentMove, title, commentList[currentMove]);
14849 char *tags = PGNTags(&gameInfo);
14851 EditTagsPopUp(tags, NULL);
14858 if(WaitForEngine(&second, StartSecond)) return;
14859 InitChessProgram(&second, FALSE);
14860 FeedMovesToProgram(&second, currentMove);
14862 SendToProgram("analyze\n", &second);
14863 second.analyzing = TRUE;
14870 if(second.analyzing) {
14871 SendToProgram("exit\n", &second);
14872 second.analyzing = FALSE;
14878 /* Toggle ShowThinking */
14880 ToggleShowThinking()
14882 appData.showThinking = !appData.showThinking;
14883 ShowThinkingEvent();
14887 AnalyzeModeEvent ()
14891 if (!first.analysisSupport) {
14892 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14893 DisplayError(buf, 0);
14896 /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
14897 if (appData.icsActive) {
14898 if (gameMode != IcsObserving) {
14899 snprintf(buf, MSG_SIZ, _("You are not observing a game"));
14900 DisplayError(buf, 0);
14902 if (appData.icsEngineAnalyze) {
14903 if (appData.debugMode)
14904 fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
14910 /* if enable, user wants to disable icsEngineAnalyze */
14911 if (appData.icsEngineAnalyze) {
14916 appData.icsEngineAnalyze = TRUE;
14917 if (appData.debugMode)
14918 fprintf(debugFP, "ICS engine analyze starting... \n");
14921 if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
14922 if (appData.noChessProgram || gameMode == AnalyzeMode)
14925 if (gameMode != AnalyzeFile) {
14926 if (!appData.icsEngineAnalyze) {
14928 if (gameMode != EditGame) return 0;
14930 if (!appData.showThinking) ToggleShowThinking();
14931 ResurrectChessProgram();
14932 SendToProgram("analyze\n", &first);
14933 first.analyzing = TRUE;
14934 /*first.maybeThinking = TRUE;*/
14935 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14936 EngineOutputPopUp();
14938 if (!appData.icsEngineAnalyze) {
14939 gameMode = AnalyzeMode;
14940 ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
14946 StartAnalysisClock();
14947 GetTimeMark(&lastNodeCountTime);
14953 AnalyzeFileEvent ()
14955 if (appData.noChessProgram || gameMode == AnalyzeFile)
14958 if (!first.analysisSupport) {
14960 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14961 DisplayError(buf, 0);
14965 if (gameMode != AnalyzeMode) {
14966 keepInfo = 1; // mere annotating should not alter PGN tags
14969 if (gameMode != EditGame) return;
14970 if (!appData.showThinking) ToggleShowThinking();
14971 ResurrectChessProgram();
14972 SendToProgram("analyze\n", &first);
14973 first.analyzing = TRUE;
14974 /*first.maybeThinking = TRUE;*/
14975 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14976 EngineOutputPopUp();
14978 gameMode = AnalyzeFile;
14982 StartAnalysisClock();
14983 GetTimeMark(&lastNodeCountTime);
14985 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
14986 AnalysisPeriodicEvent(1);
14990 MachineWhiteEvent ()
14993 char *bookHit = NULL;
14995 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
14999 if (gameMode == PlayFromGameFile ||
15000 gameMode == TwoMachinesPlay ||
15001 gameMode == Training ||
15002 gameMode == AnalyzeMode ||
15003 gameMode == EndOfGame)
15006 if (gameMode == EditPosition)
15007 EditPositionDone(TRUE);
15009 if (!WhiteOnMove(currentMove)) {
15010 DisplayError(_("It is not White's turn"), 0);
15014 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15017 if (gameMode == EditGame || gameMode == AnalyzeMode ||
15018 gameMode == AnalyzeFile)
15021 ResurrectChessProgram(); /* in case it isn't running */
15022 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
15023 gameMode = MachinePlaysWhite;
15026 gameMode = MachinePlaysWhite;
15030 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15032 if (first.sendName) {
15033 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
15034 SendToProgram(buf, &first);
15036 if (first.sendTime) {
15037 if (first.useColors) {
15038 SendToProgram("black\n", &first); /*gnu kludge*/
15040 SendTimeRemaining(&first, TRUE);
15042 if (first.useColors) {
15043 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
15045 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15046 SetMachineThinkingEnables();
15047 first.maybeThinking = TRUE;
15051 if (appData.autoFlipView && !flipView) {
15052 flipView = !flipView;
15053 DrawPosition(FALSE, NULL);
15054 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
15057 if(bookHit) { // [HGM] book: simulate book reply
15058 static char bookMove[MSG_SIZ]; // a bit generous?
15060 programStats.nodes = programStats.depth = programStats.time =
15061 programStats.score = programStats.got_only_move = 0;
15062 sprintf(programStats.movelist, "%s (xbook)", bookHit);
15064 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15065 strcat(bookMove, bookHit);
15066 savedMessage = bookMove; // args for deferred call
15067 savedState = &first;
15068 ScheduleDelayedEvent(DeferredBookMove, 1);
15073 MachineBlackEvent ()
15076 char *bookHit = NULL;
15078 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
15082 if (gameMode == PlayFromGameFile ||
15083 gameMode == TwoMachinesPlay ||
15084 gameMode == Training ||
15085 gameMode == AnalyzeMode ||
15086 gameMode == EndOfGame)
15089 if (gameMode == EditPosition)
15090 EditPositionDone(TRUE);
15092 if (WhiteOnMove(currentMove)) {
15093 DisplayError(_("It is not Black's turn"), 0);
15097 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
15100 if (gameMode == EditGame || gameMode == AnalyzeMode ||
15101 gameMode == AnalyzeFile)
15104 ResurrectChessProgram(); /* in case it isn't running */
15105 gameMode = MachinePlaysBlack;
15109 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15111 if (first.sendName) {
15112 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
15113 SendToProgram(buf, &first);
15115 if (first.sendTime) {
15116 if (first.useColors) {
15117 SendToProgram("white\n", &first); /*gnu kludge*/
15119 SendTimeRemaining(&first, FALSE);
15121 if (first.useColors) {
15122 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
15124 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
15125 SetMachineThinkingEnables();
15126 first.maybeThinking = TRUE;
15129 if (appData.autoFlipView && flipView) {
15130 flipView = !flipView;
15131 DrawPosition(FALSE, NULL);
15132 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
15134 if(bookHit) { // [HGM] book: simulate book reply
15135 static char bookMove[MSG_SIZ]; // a bit generous?
15137 programStats.nodes = programStats.depth = programStats.time =
15138 programStats.score = programStats.got_only_move = 0;
15139 sprintf(programStats.movelist, "%s (xbook)", bookHit);
15141 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15142 strcat(bookMove, bookHit);
15143 savedMessage = bookMove; // args for deferred call
15144 savedState = &first;
15145 ScheduleDelayedEvent(DeferredBookMove, 1);
15151 DisplayTwoMachinesTitle ()
15154 if (appData.matchGames > 0) {
15155 if(appData.tourneyFile[0]) {
15156 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
15157 gameInfo.white, _("vs."), gameInfo.black,
15158 nextGame+1, appData.matchGames+1,
15159 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
15161 if (first.twoMachinesColor[0] == 'w') {
15162 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15163 gameInfo.white, _("vs."), gameInfo.black,
15164 first.matchWins, second.matchWins,
15165 matchGame - 1 - (first.matchWins + second.matchWins));
15167 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
15168 gameInfo.white, _("vs."), gameInfo.black,
15169 second.matchWins, first.matchWins,
15170 matchGame - 1 - (first.matchWins + second.matchWins));
15173 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
15179 SettingsMenuIfReady ()
15181 if (second.lastPing != second.lastPong) {
15182 DisplayMessage("", _("Waiting for second chess program"));
15183 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
15187 DisplayMessage("", "");
15188 SettingsPopUp(&second);
15192 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
15195 if (cps->pr == NoProc) {
15196 StartChessProgram(cps);
15197 if (cps->protocolVersion == 1) {
15199 ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
15201 /* kludge: allow timeout for initial "feature" command */
15202 if(retry != TwoMachinesEventIfReady) FreezeUI();
15203 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
15204 DisplayMessage("", buf);
15205 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
15213 TwoMachinesEvent P((void))
15215 int i, move = forwardMostMove;
15217 ChessProgramState *onmove;
15218 char *bookHit = NULL;
15219 static int stalling = 0;
15223 if (appData.noChessProgram) return;
15225 switch (gameMode) {
15226 case TwoMachinesPlay:
15228 case MachinePlaysWhite:
15229 case MachinePlaysBlack:
15230 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15231 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
15235 case BeginningOfGame:
15236 case PlayFromGameFile:
15239 if (gameMode != EditGame) return;
15242 EditPositionDone(TRUE);
15253 // forwardMostMove = currentMove;
15254 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
15255 startingEngine = TRUE;
15257 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
15259 if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
15260 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
15261 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15265 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
15267 if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
15268 gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
15269 startingEngine = matchMode = FALSE;
15270 DisplayError("second engine does not play this", 0);
15271 gameMode = TwoMachinesPlay; ModeHighlight(); // Needed to make sure menu item is unchecked
15272 EditGameEvent(); // switch back to EditGame mode
15277 InitChessProgram(&second, FALSE); // unbalances ping of second engine
15278 SendToProgram("force\n", &second);
15280 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
15284 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
15285 if(appData.matchPause>10000 || appData.matchPause<10)
15286 appData.matchPause = 10000; /* [HGM] make pause adjustable */
15287 wait = SubtractTimeMarks(&now, &pauseStart);
15288 if(wait < appData.matchPause) {
15289 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
15292 // we are now committed to starting the game
15294 DisplayMessage("", "");
15296 if (startedFromSetupPosition) {
15297 SendBoard(&second, backwardMostMove);
15298 if (appData.debugMode) {
15299 fprintf(debugFP, "Two Machines\n");
15302 for (i = backwardMostMove; i < forwardMostMove; i++) {
15303 SendMoveToProgram(i, &second);
15307 gameMode = TwoMachinesPlay;
15308 pausing = startingEngine = FALSE;
15309 ModeHighlight(); // [HGM] logo: this triggers display update of logos
15311 DisplayTwoMachinesTitle();
15313 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
15318 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
15319 SendToProgram(first.computerString, &first);
15320 if (first.sendName) {
15321 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
15322 SendToProgram(buf, &first);
15325 SendToProgram(second.computerString, &second);
15326 if (second.sendName) {
15327 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
15328 SendToProgram(buf, &second);
15332 if (!first.sendTime || !second.sendTime || move == 0) { // [HGM] first engine changed sides from Reset, so recalc time odds
15334 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15335 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15337 if (onmove->sendTime) {
15338 if (onmove->useColors) {
15339 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
15341 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
15343 if (onmove->useColors) {
15344 SendToProgram(onmove->twoMachinesColor, onmove);
15346 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
15347 // SendToProgram("go\n", onmove);
15348 onmove->maybeThinking = TRUE;
15349 SetMachineThinkingEnables();
15353 if(bookHit) { // [HGM] book: simulate book reply
15354 static char bookMove[MSG_SIZ]; // a bit generous?
15356 programStats.nodes = programStats.depth = programStats.time =
15357 programStats.score = programStats.got_only_move = 0;
15358 sprintf(programStats.movelist, "%s (xbook)", bookHit);
15360 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
15361 strcat(bookMove, bookHit);
15362 savedMessage = bookMove; // args for deferred call
15363 savedState = onmove;
15364 ScheduleDelayedEvent(DeferredBookMove, 1);
15371 if (gameMode == Training) {
15372 SetTrainingModeOff();
15373 gameMode = PlayFromGameFile;
15374 DisplayMessage("", _("Training mode off"));
15376 gameMode = Training;
15377 animateTraining = appData.animate;
15379 /* make sure we are not already at the end of the game */
15380 if (currentMove < forwardMostMove) {
15381 SetTrainingModeOn();
15382 DisplayMessage("", _("Training mode on"));
15384 gameMode = PlayFromGameFile;
15385 DisplayError(_("Already at end of game"), 0);
15394 if (!appData.icsActive) return;
15395 switch (gameMode) {
15396 case IcsPlayingWhite:
15397 case IcsPlayingBlack:
15400 case BeginningOfGame:
15408 EditPositionDone(TRUE);
15421 gameMode = IcsIdle;
15431 switch (gameMode) {
15433 SetTrainingModeOff();
15435 case MachinePlaysWhite:
15436 case MachinePlaysBlack:
15437 case BeginningOfGame:
15438 SendToProgram("force\n", &first);
15439 if(gameMode == (forwardMostMove & 1 ? MachinePlaysBlack : MachinePlaysWhite)) { // engine is thinking
15440 if (first.usePing) { // [HGM] always send ping when we might interrupt machine thinking
15442 abortEngineThink = TRUE;
15443 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++first.lastPing);
15444 SendToProgram(buf, &first);
15445 DisplayMessage("Aborting engine think", "");
15449 SetUserThinkingEnables();
15451 case PlayFromGameFile:
15452 (void) StopLoadGameTimer();
15453 if (gameFileFP != NULL) {
15458 EditPositionDone(TRUE);
15463 SendToProgram("force\n", &first);
15465 case TwoMachinesPlay:
15466 GameEnds(EndOfFile, NULL, GE_PLAYER);
15467 ResurrectChessProgram();
15468 SetUserThinkingEnables();
15471 ResurrectChessProgram();
15473 case IcsPlayingBlack:
15474 case IcsPlayingWhite:
15475 DisplayError(_("Warning: You are still playing a game"), 0);
15478 DisplayError(_("Warning: You are still observing a game"), 0);
15481 DisplayError(_("Warning: You are still examining a game"), 0);
15492 first.offeredDraw = second.offeredDraw = 0;
15494 if (gameMode == PlayFromGameFile) {
15495 whiteTimeRemaining = timeRemaining[0][currentMove];
15496 blackTimeRemaining = timeRemaining[1][currentMove];
15500 if (gameMode == MachinePlaysWhite ||
15501 gameMode == MachinePlaysBlack ||
15502 gameMode == TwoMachinesPlay ||
15503 gameMode == EndOfGame) {
15504 i = forwardMostMove;
15505 while (i > currentMove) {
15506 SendToProgram("undo\n", &first);
15509 if(!adjustedClock) {
15510 whiteTimeRemaining = timeRemaining[0][currentMove];
15511 blackTimeRemaining = timeRemaining[1][currentMove];
15512 DisplayBothClocks();
15514 if (whiteFlag || blackFlag) {
15515 whiteFlag = blackFlag = 0;
15520 gameMode = EditGame;
15526 EditPositionEvent ()
15529 if (gameMode == EditPosition) {
15535 if (gameMode != EditGame) return;
15537 gameMode = EditPosition;
15540 CopyBoard(rightsBoard, nullBoard);
15541 if (currentMove > 0)
15542 CopyBoard(boards[0], boards[currentMove]);
15543 for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15544 rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15546 blackPlaysFirst = !WhiteOnMove(currentMove);
15548 currentMove = forwardMostMove = backwardMostMove = 0;
15549 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15551 if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
15557 /* [DM] icsEngineAnalyze - possible call from other functions */
15558 if (appData.icsEngineAnalyze) {
15559 appData.icsEngineAnalyze = FALSE;
15561 DisplayMessage("",_("Close ICS engine analyze..."));
15563 if (first.analysisSupport && first.analyzing) {
15564 SendToBoth("exit\n");
15565 first.analyzing = second.analyzing = FALSE;
15567 thinkOutput[0] = NULLCHAR;
15571 EditPositionDone (Boolean fakeRights)
15573 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
15575 startedFromSetupPosition = TRUE;
15576 InitChessProgram(&first, FALSE);
15577 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
15579 boards[0][EP_STATUS] = EP_NONE;
15580 for(f=0; f<=nrCastlingRights; f++) boards[0][CASTLING][f] = NoRights;
15581 for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // first pass: Kings & e.p.
15582 if(rightsBoard[r][f]) {
15583 ChessSquare p = boards[0][r][f];
15584 if(p == (blackPlaysFirst ? WhitePawn : BlackPawn)) boards[0][EP_STATUS] = f;
15585 else if(p == king) boards[0][CASTLING][2] = f;
15586 else if(p == WHITE_TO_BLACK king) boards[0][CASTLING][5] = f;
15587 else rightsBoard[r][f] = 2; // mark for second pass
15590 for(r=BOARD_HEIGHT-1; r>=0; r--) for(f=BOARD_RGHT-1; f>=BOARD_LEFT; f--) { // second pass: Rooks
15591 if(rightsBoard[r][f] == 2) {
15592 ChessSquare p = boards[0][r][f];
15593 if(p == WhiteRook) boards[0][CASTLING][(f < boards[0][CASTLING][2])] = f; else
15594 if(p == BlackRook) boards[0][CASTLING][(f < boards[0][CASTLING][5])+3] = f;
15598 SendToProgram("force\n", &first);
15599 if (blackPlaysFirst) {
15600 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
15601 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
15602 currentMove = forwardMostMove = backwardMostMove = 1;
15603 CopyBoard(boards[1], boards[0]);
15605 currentMove = forwardMostMove = backwardMostMove = 0;
15607 SendBoard(&first, forwardMostMove);
15608 if (appData.debugMode) {
15609 fprintf(debugFP, "EditPosDone\n");
15612 DisplayMessage("", "");
15613 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15614 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15615 gameMode = EditGame;
15617 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15618 ClearHighlights(); /* [AS] */
15621 /* Pause for `ms' milliseconds */
15622 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15624 TimeDelay (long ms)
15631 } while (SubtractTimeMarks(&m2, &m1) < ms);
15634 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15636 SendMultiLineToICS (char *buf)
15638 char temp[MSG_SIZ+1], *p;
15645 strncpy(temp, buf, len);
15650 if (*p == '\n' || *p == '\r')
15655 strcat(temp, "\n");
15657 SendToPlayer(temp, strlen(temp));
15661 SetWhiteToPlayEvent ()
15663 if (gameMode == EditPosition) {
15664 blackPlaysFirst = FALSE;
15665 DisplayBothClocks(); /* works because currentMove is 0 */
15666 } else if (gameMode == IcsExamining) {
15667 SendToICS(ics_prefix);
15668 SendToICS("tomove white\n");
15673 SetBlackToPlayEvent ()
15675 if (gameMode == EditPosition) {
15676 blackPlaysFirst = TRUE;
15677 currentMove = 1; /* kludge */
15678 DisplayBothClocks();
15680 } else if (gameMode == IcsExamining) {
15681 SendToICS(ics_prefix);
15682 SendToICS("tomove black\n");
15687 EditPositionMenuEvent (ChessSquare selection, int x, int y)
15690 ChessSquare piece = boards[0][y][x];
15691 static Board erasedBoard, currentBoard, menuBoard, nullBoard;
15692 static int lastVariant;
15693 int baseRank = BOARD_HEIGHT-1, hasRights = 0;
15695 if (gameMode != EditPosition && gameMode != IcsExamining) return;
15697 switch (selection) {
15699 fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
15700 MarkTargetSquares(1);
15701 CopyBoard(currentBoard, boards[0]);
15702 CopyBoard(menuBoard, initialPosition);
15703 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
15704 SendToICS(ics_prefix);
15705 SendToICS("bsetup clear\n");
15706 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
15707 SendToICS(ics_prefix);
15708 SendToICS("clearboard\n");
15711 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
15712 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
15713 for (y = 0; y < BOARD_HEIGHT; y++) {
15714 if (gameMode == IcsExamining) {
15715 if (boards[currentMove][y][x] != EmptySquare) {
15716 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
15720 } else if(boards[0][y][x] != DarkSquare) {
15721 if(boards[0][y][x] != p) nonEmpty++;
15722 boards[0][y][x] = p;
15726 CopyBoard(rightsBoard, nullBoard);
15727 if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
15729 for(r = 0; r < BOARD_HEIGHT; r++) {
15730 for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates
15731 ChessSquare p = menuBoard[r][x];
15732 for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
15735 menuBoard[CASTLING][0] = menuBoard[CASTLING][3] = NoRights; // h-side Rook was deleted
15736 DisplayMessage("Clicking clock again restores position", "");
15737 if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
15738 if(!nonEmpty) { // asked to clear an empty board
15739 CopyBoard(boards[0], menuBoard);
15741 if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
15742 CopyBoard(boards[0], initialPosition);
15744 if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
15745 && !CompareBoards(nullBoard, erasedBoard)) {
15746 CopyBoard(boards[0], erasedBoard);
15748 CopyBoard(erasedBoard, currentBoard);
15750 for(i=0; i<nrCastlingRights; i++) if(boards[0][CASTLING][i] != NoRights)
15751 rightsBoard[castlingRank[i]][boards[0][CASTLING][i]] = 1; // copy remaining rights
15754 if (gameMode == EditPosition) {
15755 DrawPosition(FALSE, boards[0]);
15760 SetWhiteToPlayEvent();
15764 SetBlackToPlayEvent();
15768 if (gameMode == IcsExamining) {
15769 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15770 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
15773 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15774 if(x == BOARD_LEFT-2) {
15775 if(y < handSize-1-gameInfo.holdingsSize) break;
15776 boards[0][y][1] = 0;
15778 if(x == BOARD_RGHT+1) {
15779 if(y >= gameInfo.holdingsSize) break;
15780 boards[0][y][BOARD_WIDTH-2] = 0;
15783 boards[0][y][x] = EmptySquare;
15784 DrawPosition(FALSE, boards[0]);
15789 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
15790 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
15791 selection = (ChessSquare) (PROMOTED(piece));
15792 } else if(piece == EmptySquare) selection = WhiteSilver;
15793 else selection = (ChessSquare)((int)piece - 1);
15797 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
15798 piece > (int)BlackMan && piece <= (int)BlackKing ) {
15799 selection = (ChessSquare) (DEMOTED(piece));
15800 } else if(piece == EmptySquare) selection = BlackSilver;
15801 else selection = (ChessSquare)((int)piece + 1);
15806 if(gameInfo.variant == VariantShatranj ||
15807 gameInfo.variant == VariantXiangqi ||
15808 gameInfo.variant == VariantCourier ||
15809 gameInfo.variant == VariantASEAN ||
15810 gameInfo.variant == VariantMakruk )
15811 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
15817 if(y == baseRank && (x == BOARD_LEFT || x == BOARD_RGHT-1 || appData.fischerCastling)) hasRights = 1;
15818 if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15824 if(gameInfo.variant == VariantXiangqi)
15825 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
15826 if(gameInfo.variant == VariantKnightmate)
15827 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
15828 if(y == baseRank && (x == BOARD_WIDTH>>1 || appData.fischerCastling)) hasRights = 1;
15831 if (gameMode == IcsExamining) {
15832 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15833 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
15834 PieceToChar(selection), AAA + x, ONE + y);
15837 rightsBoard[y][x] = hasRights;
15838 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15840 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
15841 n = PieceToNumber(selection - BlackPawn);
15842 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
15843 boards[0][handSize-1-n][0] = selection;
15844 boards[0][handSize-1-n][1]++;
15846 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
15847 n = PieceToNumber(selection);
15848 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
15849 boards[0][n][BOARD_WIDTH-1] = selection;
15850 boards[0][n][BOARD_WIDTH-2]++;
15853 boards[0][y][x] = selection;
15854 DrawPosition(TRUE, boards[0]);
15856 fromX = fromY = -1;
15864 DropMenuEvent (ChessSquare selection, int x, int y)
15866 ChessMove moveType;
15868 switch (gameMode) {
15869 case IcsPlayingWhite:
15870 case MachinePlaysBlack:
15871 if (!WhiteOnMove(currentMove)) {
15872 DisplayMoveError(_("It is Black's turn"));
15875 moveType = WhiteDrop;
15877 case IcsPlayingBlack:
15878 case MachinePlaysWhite:
15879 if (WhiteOnMove(currentMove)) {
15880 DisplayMoveError(_("It is White's turn"));
15883 moveType = BlackDrop;
15886 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
15892 if (moveType == BlackDrop && selection < BlackPawn) {
15893 selection = (ChessSquare) ((int) selection
15894 + (int) BlackPawn - (int) WhitePawn);
15896 if (boards[currentMove][y][x] != EmptySquare) {
15897 DisplayMoveError(_("That square is occupied"));
15901 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
15907 /* Accept a pending offer of any kind from opponent */
15909 if (appData.icsActive) {
15910 SendToICS(ics_prefix);
15911 SendToICS("accept\n");
15912 } else if (cmailMsgLoaded) {
15913 if (currentMove == cmailOldMove &&
15914 commentList[cmailOldMove] != NULL &&
15915 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15916 "Black offers a draw" : "White offers a draw")) {
15918 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15919 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15921 DisplayError(_("There is no pending offer on this move"), 0);
15922 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15925 /* Not used for offers from chess program */
15932 /* Decline a pending offer of any kind from opponent */
15934 if (appData.icsActive) {
15935 SendToICS(ics_prefix);
15936 SendToICS("decline\n");
15937 } else if (cmailMsgLoaded) {
15938 if (currentMove == cmailOldMove &&
15939 commentList[cmailOldMove] != NULL &&
15940 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15941 "Black offers a draw" : "White offers a draw")) {
15943 AppendComment(cmailOldMove, "Draw declined", TRUE);
15944 DisplayComment(cmailOldMove - 1, "Draw declined");
15947 DisplayError(_("There is no pending offer on this move"), 0);
15950 /* Not used for offers from chess program */
15957 /* Issue ICS rematch command */
15958 if (appData.icsActive) {
15959 SendToICS(ics_prefix);
15960 SendToICS("rematch\n");
15967 /* Call your opponent's flag (claim a win on time) */
15968 if (appData.icsActive) {
15969 SendToICS(ics_prefix);
15970 SendToICS("flag\n");
15972 switch (gameMode) {
15975 case MachinePlaysWhite:
15978 GameEnds(GameIsDrawn, "Both players ran out of time",
15981 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
15983 DisplayError(_("Your opponent is not out of time"), 0);
15986 case MachinePlaysBlack:
15989 GameEnds(GameIsDrawn, "Both players ran out of time",
15992 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
15994 DisplayError(_("Your opponent is not out of time"), 0);
16002 ClockClick (int which)
16003 { // [HGM] code moved to back-end from winboard.c
16004 if(which) { // black clock
16005 if (gameMode == EditPosition || gameMode == IcsExamining) {
16006 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16007 SetBlackToPlayEvent();
16008 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16009 gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
16010 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
16011 } else if (shiftKey) {
16012 AdjustClock(which, -1);
16013 } else if (gameMode == IcsPlayingWhite ||
16014 gameMode == MachinePlaysBlack) {
16017 } else { // white clock
16018 if (gameMode == EditPosition || gameMode == IcsExamining) {
16019 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
16020 SetWhiteToPlayEvent();
16021 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
16022 gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
16023 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
16024 } else if (shiftKey) {
16025 AdjustClock(which, -1);
16026 } else if (gameMode == IcsPlayingBlack ||
16027 gameMode == MachinePlaysWhite) {
16036 /* Offer draw or accept pending draw offer from opponent */
16038 if (appData.icsActive) {
16039 /* Note: tournament rules require draw offers to be
16040 made after you make your move but before you punch
16041 your clock. Currently ICS doesn't let you do that;
16042 instead, you immediately punch your clock after making
16043 a move, but you can offer a draw at any time. */
16045 SendToICS(ics_prefix);
16046 SendToICS("draw\n");
16047 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
16048 } else if (cmailMsgLoaded) {
16049 if (currentMove == cmailOldMove &&
16050 commentList[cmailOldMove] != NULL &&
16051 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
16052 "Black offers a draw" : "White offers a draw")) {
16053 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
16054 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
16055 } else if (currentMove == cmailOldMove + 1) {
16056 char *offer = WhiteOnMove(cmailOldMove) ?
16057 "White offers a draw" : "Black offers a draw";
16058 AppendComment(currentMove, offer, TRUE);
16059 DisplayComment(currentMove - 1, offer);
16060 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
16062 DisplayError(_("You must make your move before offering a draw"), 0);
16063 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
16065 } else if (first.offeredDraw) {
16066 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
16068 if (first.sendDrawOffers) {
16069 SendToProgram("draw\n", &first);
16070 userOfferedDraw = TRUE;
16078 /* Offer Adjourn or accept pending Adjourn offer from opponent */
16080 if (appData.icsActive) {
16081 SendToICS(ics_prefix);
16082 SendToICS("adjourn\n");
16084 /* Currently GNU Chess doesn't offer or accept Adjourns */
16092 /* Offer Abort or accept pending Abort offer from opponent */
16094 if (appData.icsActive) {
16095 SendToICS(ics_prefix);
16096 SendToICS("abort\n");
16098 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
16105 /* Resign. You can do this even if it's not your turn. */
16107 if (appData.icsActive) {
16108 SendToICS(ics_prefix);
16109 SendToICS("resign\n");
16111 switch (gameMode) {
16112 case MachinePlaysWhite:
16113 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16115 case MachinePlaysBlack:
16116 GameEnds(BlackWins, "White resigns", GE_PLAYER);
16119 if (cmailMsgLoaded) {
16121 if (WhiteOnMove(cmailOldMove)) {
16122 GameEnds(BlackWins, "White resigns", GE_PLAYER);
16124 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
16126 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
16137 StopObservingEvent ()
16139 /* Stop observing current games */
16140 SendToICS(ics_prefix);
16141 SendToICS("unobserve\n");
16145 StopExaminingEvent ()
16147 /* Stop observing current game */
16148 SendToICS(ics_prefix);
16149 SendToICS("unexamine\n");
16153 ForwardInner (int target)
16155 int limit; int oldSeekGraphUp = seekGraphUp;
16157 if (appData.debugMode)
16158 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
16159 target, currentMove, forwardMostMove);
16161 if (gameMode == EditPosition)
16164 seekGraphUp = FALSE;
16165 MarkTargetSquares(1);
16166 fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16168 if (gameMode == PlayFromGameFile && !pausing)
16171 if (gameMode == IcsExamining && pausing)
16172 limit = pauseExamForwardMostMove;
16174 limit = forwardMostMove;
16176 if (target > limit) target = limit;
16178 if (target > 0 && moveList[target - 1][0]) {
16179 int fromX, fromY, toX, toY;
16180 toX = moveList[target - 1][2] - AAA;
16181 toY = moveList[target - 1][3] - ONE;
16182 if (moveList[target - 1][1] == '@') {
16183 if (appData.highlightLastMove) {
16184 SetHighlights(-1, -1, toX, toY);
16187 fromX = moveList[target - 1][0] - AAA;
16188 fromY = moveList[target - 1][1] - ONE;
16189 if (target == currentMove + 1) {
16190 if(moveList[target - 1][4] == ';') { // multi-leg
16191 killX = moveList[target - 1][5] - AAA;
16192 killY = moveList[target - 1][6] - ONE;
16194 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
16195 killX = killY = -1;
16197 if (appData.highlightLastMove) {
16198 SetHighlights(fromX, fromY, toX, toY);
16202 if (gameMode == EditGame || gameMode == AnalyzeMode ||
16203 gameMode == Training || gameMode == PlayFromGameFile ||
16204 gameMode == AnalyzeFile) {
16205 while (currentMove < target) {
16206 if(second.analyzing) SendMoveToProgram(currentMove, &second);
16207 SendMoveToProgram(currentMove++, &first);
16210 currentMove = target;
16213 if (gameMode == EditGame || gameMode == EndOfGame) {
16214 whiteTimeRemaining = timeRemaining[0][currentMove];
16215 blackTimeRemaining = timeRemaining[1][currentMove];
16217 DisplayBothClocks();
16218 DisplayMove(currentMove - 1);
16219 DrawPosition(oldSeekGraphUp, boards[currentMove]);
16220 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16221 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
16222 DisplayComment(currentMove - 1, commentList[currentMove]);
16224 ClearMap(); // [HGM] exclude: invalidate map
16231 if (gameMode == IcsExamining && !pausing) {
16232 SendToICS(ics_prefix);
16233 SendToICS("forward\n");
16235 ForwardInner(currentMove + 1);
16242 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16243 /* to optimze, we temporarily turn off analysis mode while we feed
16244 * the remaining moves to the engine. Otherwise we get analysis output
16247 if (first.analysisSupport) {
16248 SendToProgram("exit\nforce\n", &first);
16249 first.analyzing = FALSE;
16253 if (gameMode == IcsExamining && !pausing) {
16254 SendToICS(ics_prefix);
16255 SendToICS("forward 999999\n");
16257 ForwardInner(forwardMostMove);
16260 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16261 /* we have fed all the moves, so reactivate analysis mode */
16262 SendToProgram("analyze\n", &first);
16263 first.analyzing = TRUE;
16264 /*first.maybeThinking = TRUE;*/
16265 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16270 BackwardInner (int target)
16272 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
16274 if (appData.debugMode)
16275 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
16276 target, currentMove, forwardMostMove);
16278 if (gameMode == EditPosition) return;
16279 seekGraphUp = FALSE;
16280 MarkTargetSquares(1);
16281 fromX = fromY = killX = killY = kill2X = kill2Y = -1; // [HGM] abort any move entry in progress
16282 if (currentMove <= backwardMostMove) {
16284 DrawPosition(full_redraw, boards[currentMove]);
16287 if (gameMode == PlayFromGameFile && !pausing)
16290 if (moveList[target][0]) {
16291 int fromX, fromY, toX, toY;
16292 toX = moveList[target][2] - AAA;
16293 toY = moveList[target][3] - ONE;
16294 if (moveList[target][1] == '@') {
16295 if (appData.highlightLastMove) {
16296 SetHighlights(-1, -1, toX, toY);
16299 fromX = moveList[target][0] - AAA;
16300 fromY = moveList[target][1] - ONE;
16301 if (target == currentMove - 1) {
16302 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
16304 if (appData.highlightLastMove) {
16305 SetHighlights(fromX, fromY, toX, toY);
16309 if (gameMode == EditGame || gameMode==AnalyzeMode ||
16310 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
16311 while (currentMove > target) {
16312 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
16313 // null move cannot be undone. Reload program with move history before it.
16315 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
16316 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
16318 SendBoard(&first, i);
16319 if(second.analyzing) SendBoard(&second, i);
16320 for(currentMove=i; currentMove<target; currentMove++) {
16321 SendMoveToProgram(currentMove, &first);
16322 if(second.analyzing) SendMoveToProgram(currentMove, &second);
16326 SendToBoth("undo\n");
16330 currentMove = target;
16333 if (gameMode == EditGame || gameMode == EndOfGame) {
16334 whiteTimeRemaining = timeRemaining[0][currentMove];
16335 blackTimeRemaining = timeRemaining[1][currentMove];
16337 DisplayBothClocks();
16338 DisplayMove(currentMove - 1);
16339 DrawPosition(full_redraw, boards[currentMove]);
16340 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
16341 // [HGM] PV info: routine tests if comment empty
16342 DisplayComment(currentMove - 1, commentList[currentMove]);
16343 ClearMap(); // [HGM] exclude: invalidate map
16349 if (gameMode == IcsExamining && !pausing) {
16350 SendToICS(ics_prefix);
16351 SendToICS("backward\n");
16353 BackwardInner(currentMove - 1);
16360 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16361 /* to optimize, we temporarily turn off analysis mode while we undo
16362 * all the moves. Otherwise we get analysis output after each undo.
16364 if (first.analysisSupport) {
16365 SendToProgram("exit\nforce\n", &first);
16366 first.analyzing = FALSE;
16370 if (gameMode == IcsExamining && !pausing) {
16371 SendToICS(ics_prefix);
16372 SendToICS("backward 999999\n");
16374 BackwardInner(backwardMostMove);
16377 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16378 /* we have fed all the moves, so reactivate analysis mode */
16379 SendToProgram("analyze\n", &first);
16380 first.analyzing = TRUE;
16381 /*first.maybeThinking = TRUE;*/
16382 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
16389 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
16390 if (to >= forwardMostMove) to = forwardMostMove;
16391 if (to <= backwardMostMove) to = backwardMostMove;
16392 if (to < currentMove) {
16400 RevertEvent (Boolean annotate)
16402 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
16405 if (gameMode != IcsExamining) {
16406 DisplayError(_("You are not examining a game"), 0);
16410 DisplayError(_("You can't revert while pausing"), 0);
16413 SendToICS(ics_prefix);
16414 SendToICS("revert\n");
16418 RetractMoveEvent ()
16420 switch (gameMode) {
16421 case MachinePlaysWhite:
16422 case MachinePlaysBlack:
16423 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
16424 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
16427 if (forwardMostMove < 2) return;
16428 currentMove = forwardMostMove = forwardMostMove - 2;
16429 whiteTimeRemaining = timeRemaining[0][currentMove];
16430 blackTimeRemaining = timeRemaining[1][currentMove];
16431 DisplayBothClocks();
16432 DisplayMove(currentMove - 1);
16433 ClearHighlights();/*!! could figure this out*/
16434 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
16435 SendToProgram("remove\n", &first);
16436 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
16439 case BeginningOfGame:
16443 case IcsPlayingWhite:
16444 case IcsPlayingBlack:
16445 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
16446 SendToICS(ics_prefix);
16447 SendToICS("takeback 2\n");
16449 SendToICS(ics_prefix);
16450 SendToICS("takeback 1\n");
16459 ChessProgramState *cps;
16461 switch (gameMode) {
16462 case MachinePlaysWhite:
16463 if (!WhiteOnMove(forwardMostMove)) {
16464 DisplayError(_("It is your turn"), 0);
16469 case MachinePlaysBlack:
16470 if (WhiteOnMove(forwardMostMove)) {
16471 DisplayError(_("It is your turn"), 0);
16476 case TwoMachinesPlay:
16477 if (WhiteOnMove(forwardMostMove) ==
16478 (first.twoMachinesColor[0] == 'w')) {
16484 case BeginningOfGame:
16488 SendToProgram("?\n", cps);
16492 TruncateGameEvent ()
16495 if (gameMode != EditGame) return;
16502 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
16503 if (forwardMostMove > currentMove) {
16504 if (gameInfo.resultDetails != NULL) {
16505 free(gameInfo.resultDetails);
16506 gameInfo.resultDetails = NULL;
16507 gameInfo.result = GameUnfinished;
16509 forwardMostMove = currentMove;
16510 HistorySet(parseList, backwardMostMove, forwardMostMove,
16518 if (appData.noChessProgram) return;
16519 switch (gameMode) {
16520 case MachinePlaysWhite:
16521 if (WhiteOnMove(forwardMostMove)) {
16522 DisplayError(_("Wait until your turn."), 0);
16526 case BeginningOfGame:
16527 case MachinePlaysBlack:
16528 if (!WhiteOnMove(forwardMostMove)) {
16529 DisplayError(_("Wait until your turn."), 0);
16534 DisplayError(_("No hint available"), 0);
16537 SendToProgram("hint\n", &first);
16538 hintRequested = TRUE;
16542 SaveSelected (FILE *g, int dummy, char *dummy2)
16544 ListGame * lg = (ListGame *) gameList.head;
16548 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16549 DisplayError(_("Game list not loaded or empty"), 0);
16553 creatingBook = TRUE; // suppresses stuff during load game
16555 /* Get list size */
16556 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16557 if(lg->position >= 0) { // selected?
16558 LoadGame(f, nItem, "", TRUE);
16559 SaveGamePGN2(g); // leaves g open
16562 lg = (ListGame *) lg->node.succ;
16566 creatingBook = FALSE;
16574 ListGame * lg = (ListGame *) gameList.head;
16577 static int secondTime = FALSE;
16579 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
16580 DisplayError(_("Game list not loaded or empty"), 0);
16584 if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
16587 DisplayNote(_("Book file exists! Try again for overwrite."));
16591 creatingBook = TRUE;
16592 secondTime = FALSE;
16594 /* Get list size */
16595 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16596 if(lg->position >= 0) {
16597 LoadGame(f, nItem, "", TRUE);
16598 AddGameToBook(TRUE);
16601 lg = (ListGame *) lg->node.succ;
16604 creatingBook = FALSE;
16611 if (appData.noChessProgram) return;
16612 switch (gameMode) {
16613 case MachinePlaysWhite:
16614 if (WhiteOnMove(forwardMostMove)) {
16615 DisplayError(_("Wait until your turn."), 0);
16619 case BeginningOfGame:
16620 case MachinePlaysBlack:
16621 if (!WhiteOnMove(forwardMostMove)) {
16622 DisplayError(_("Wait until your turn."), 0);
16627 EditPositionDone(TRUE);
16629 case TwoMachinesPlay:
16634 SendToProgram("bk\n", &first);
16635 bookOutput[0] = NULLCHAR;
16636 bookRequested = TRUE;
16642 char *tags = PGNTags(&gameInfo);
16643 TagsPopUp(tags, CmailMsg());
16647 /* end button procedures */
16650 PrintPosition (FILE *fp, int move)
16654 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16655 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16656 char c = PieceToChar(boards[move][i][j]);
16657 fputc(c == '?' ? '.' : c, fp);
16658 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
16661 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
16662 fprintf(fp, "white to play\n");
16664 fprintf(fp, "black to play\n");
16668 PrintOpponents (FILE *fp)
16670 if (gameInfo.white != NULL) {
16671 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
16677 /* Find last component of program's own name, using some heuristics */
16679 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
16682 int local = (strcmp(host, "localhost") == 0);
16683 while (!local && (p = strchr(prog, ';')) != NULL) {
16685 while (*p == ' ') p++;
16688 if (*prog == '"' || *prog == '\'') {
16689 q = strchr(prog + 1, *prog);
16691 q = strchr(prog, ' ');
16693 if (q == NULL) q = prog + strlen(prog);
16695 while (p >= prog && *p != '/' && *p != '\\') p--;
16697 if(p == prog && *p == '"') p++;
16699 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
16700 memcpy(buf, p, q - p);
16701 buf[q - p] = NULLCHAR;
16709 TimeControlTagValue ()
16712 if (!appData.clockMode) {
16713 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
16714 } else if (movesPerSession > 0) {
16715 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
16716 } else if (timeIncrement == 0) {
16717 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
16719 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
16721 return StrSave(buf);
16727 /* This routine is used only for certain modes */
16728 VariantClass v = gameInfo.variant;
16729 ChessMove r = GameUnfinished;
16732 if(keepInfo) return;
16734 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
16735 r = gameInfo.result;
16736 p = gameInfo.resultDetails;
16737 gameInfo.resultDetails = NULL;
16739 ClearGameInfo(&gameInfo);
16740 gameInfo.variant = v;
16742 switch (gameMode) {
16743 case MachinePlaysWhite:
16744 gameInfo.event = StrSave( appData.pgnEventHeader );
16745 gameInfo.site = StrSave(HostName());
16746 gameInfo.date = PGNDate();
16747 gameInfo.round = StrSave("-");
16748 gameInfo.white = StrSave(first.tidy);
16749 gameInfo.black = StrSave(UserName());
16750 gameInfo.timeControl = TimeControlTagValue();
16753 case MachinePlaysBlack:
16754 gameInfo.event = StrSave( appData.pgnEventHeader );
16755 gameInfo.site = StrSave(HostName());
16756 gameInfo.date = PGNDate();
16757 gameInfo.round = StrSave("-");
16758 gameInfo.white = StrSave(UserName());
16759 gameInfo.black = StrSave(first.tidy);
16760 gameInfo.timeControl = TimeControlTagValue();
16763 case TwoMachinesPlay:
16764 gameInfo.event = StrSave( appData.pgnEventHeader );
16765 gameInfo.site = StrSave(HostName());
16766 gameInfo.date = PGNDate();
16769 snprintf(buf, MSG_SIZ, "%d", roundNr);
16770 gameInfo.round = StrSave(buf);
16772 gameInfo.round = StrSave("-");
16774 if (first.twoMachinesColor[0] == 'w') {
16775 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16776 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16778 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16779 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16781 gameInfo.timeControl = TimeControlTagValue();
16785 gameInfo.event = StrSave("Edited game");
16786 gameInfo.site = StrSave(HostName());
16787 gameInfo.date = PGNDate();
16788 gameInfo.round = StrSave("-");
16789 gameInfo.white = StrSave("-");
16790 gameInfo.black = StrSave("-");
16791 gameInfo.result = r;
16792 gameInfo.resultDetails = p;
16796 gameInfo.event = StrSave("Edited position");
16797 gameInfo.site = StrSave(HostName());
16798 gameInfo.date = PGNDate();
16799 gameInfo.round = StrSave("-");
16800 gameInfo.white = StrSave("-");
16801 gameInfo.black = StrSave("-");
16804 case IcsPlayingWhite:
16805 case IcsPlayingBlack:
16810 case PlayFromGameFile:
16811 gameInfo.event = StrSave("Game from non-PGN file");
16812 gameInfo.site = StrSave(HostName());
16813 gameInfo.date = PGNDate();
16814 gameInfo.round = StrSave("-");
16815 gameInfo.white = StrSave("?");
16816 gameInfo.black = StrSave("?");
16825 ReplaceComment (int index, char *text)
16831 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
16832 pvInfoList[index-1].depth == len &&
16833 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
16834 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
16835 while (*text == '\n') text++;
16836 len = strlen(text);
16837 while (len > 0 && text[len - 1] == '\n') len--;
16839 if (commentList[index] != NULL)
16840 free(commentList[index]);
16843 commentList[index] = NULL;
16846 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
16847 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
16848 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
16849 commentList[index] = (char *) malloc(len + 2);
16850 strncpy(commentList[index], text, len);
16851 commentList[index][len] = '\n';
16852 commentList[index][len + 1] = NULLCHAR;
16854 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
16856 commentList[index] = (char *) malloc(len + 7);
16857 safeStrCpy(commentList[index], "{\n", 3);
16858 safeStrCpy(commentList[index]+2, text, len+1);
16859 commentList[index][len+2] = NULLCHAR;
16860 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
16861 strcat(commentList[index], "\n}\n");
16866 CrushCRs (char *text)
16874 if (ch == '\r') continue;
16876 } while (ch != '\0');
16880 AppendComment (int index, char *text, Boolean addBraces)
16881 /* addBraces tells if we should add {} */
16886 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
16887 if(addBraces == 3) addBraces = 0; else // force appending literally
16888 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
16891 while (*text == '\n') text++;
16892 len = strlen(text);
16893 while (len > 0 && text[len - 1] == '\n') len--;
16894 text[len] = NULLCHAR;
16896 if (len == 0) return;
16898 if (commentList[index] != NULL) {
16899 Boolean addClosingBrace = addBraces;
16900 old = commentList[index];
16901 oldlen = strlen(old);
16902 while(commentList[index][oldlen-1] == '\n')
16903 commentList[index][--oldlen] = NULLCHAR;
16904 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
16905 safeStrCpy(commentList[index], old, oldlen + len + 6);
16907 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
16908 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
16909 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
16910 while (*text == '\n') { text++; len--; }
16911 commentList[index][--oldlen] = NULLCHAR;
16913 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
16914 else strcat(commentList[index], "\n");
16915 strcat(commentList[index], text);
16916 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
16917 else strcat(commentList[index], "\n");
16919 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
16921 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
16922 else commentList[index][0] = NULLCHAR;
16923 strcat(commentList[index], text);
16924 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
16925 if(addBraces == TRUE) strcat(commentList[index], "}\n");
16930 FindStr (char * text, char * sub_text)
16932 char * result = strstr( text, sub_text );
16934 if( result != NULL ) {
16935 result += strlen( sub_text );
16941 /* [AS] Try to extract PV info from PGN comment */
16942 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
16944 GetInfoFromComment (int index, char * text)
16946 char * sep = text, *p;
16948 if( text != NULL && index > 0 ) {
16951 int time = -1, sec = 0, deci;
16952 char * s_eval = FindStr( text, "[%eval " );
16953 char * s_emt = FindStr( text, "[%emt " );
16955 if( s_eval != NULL || s_emt != NULL ) {
16957 if(0) { // [HGM] this code is not finished, and could actually be detrimental
16962 if( s_eval != NULL ) {
16963 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
16967 if( delim != ']' ) {
16972 if( s_emt != NULL ) {
16977 /* We expect something like: [+|-]nnn.nn/dd */
16980 if(*text != '{') return text; // [HGM] braces: must be normal comment
16982 sep = strchr( text, '/' );
16983 if( sep == NULL || sep < (text+4) ) {
16988 if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
16989 if(p[1] == '(') { // comment starts with PV
16990 p = strchr(p, ')'); // locate end of PV
16991 if(p == NULL || sep < p+5) return text;
16992 // at this point we have something like "{(.*) +0.23/6 ..."
16993 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
16994 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
16995 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
16997 time = -1; sec = -1; deci = -1;
16998 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
16999 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
17000 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
17001 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
17005 if( score_lo < 0 || score_lo >= 100 ) {
17009 if(sec >= 0) time = 600*time + 10*sec; else
17010 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
17012 score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
17014 /* [HGM] PV time: now locate end of PV info */
17015 while( *++sep >= '0' && *sep <= '9'); // strip depth
17017 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
17019 while( *++sep >= '0' && *sep <= '9'); // strip seconds
17021 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
17022 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
17033 pvInfoList[index-1].depth = depth;
17034 pvInfoList[index-1].score = score;
17035 pvInfoList[index-1].time = 10*time; // centi-sec
17036 if(*sep == '}') *sep = 0; else *--sep = '{';
17038 while(*p++ = *sep++)
17041 } // squeeze out space between PV and comment, and return both
17047 SendToProgram (char *message, ChessProgramState *cps)
17049 int count, outCount, error;
17052 if (cps->pr == NoProc) return;
17055 if (appData.debugMode) {
17058 fprintf(debugFP, "%ld >%-6s: %s",
17059 SubtractTimeMarks(&now, &programStartTime),
17060 cps->which, message);
17062 fprintf(serverFP, "%ld >%-6s: %s",
17063 SubtractTimeMarks(&now, &programStartTime),
17064 cps->which, message), fflush(serverFP);
17067 count = strlen(message);
17068 outCount = OutputToProcess(cps->pr, message, count, &error);
17069 if (outCount < count && !exiting
17070 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
17071 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
17072 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
17073 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17074 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17075 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17076 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17077 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17079 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17080 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17081 gameInfo.result = res;
17083 gameInfo.resultDetails = StrSave(buf);
17085 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17086 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17091 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
17095 ChessProgramState *cps = (ChessProgramState *)closure;
17097 if (isr != cps->isr) return; /* Killed intentionally */
17100 RemoveInputSource(cps->isr);
17101 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
17102 _(cps->which), cps->program);
17103 if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
17104 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
17105 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
17106 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
17107 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
17108 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
17110 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
17111 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
17112 gameInfo.result = res;
17114 gameInfo.resultDetails = StrSave(buf);
17116 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
17117 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
17119 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
17120 _(cps->which), cps->program);
17121 RemoveInputSource(cps->isr);
17123 /* [AS] Program is misbehaving badly... kill it */
17124 if( count == -2 ) {
17125 DestroyChildProcess( cps->pr, 9 );
17129 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
17134 if ((end_str = strchr(message, '\r')) != NULL)
17135 *end_str = NULLCHAR;
17136 if ((end_str = strchr(message, '\n')) != NULL)
17137 *end_str = NULLCHAR;
17139 if (appData.debugMode) {
17140 TimeMark now; int print = 1;
17141 char *quote = ""; char c; int i;
17143 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
17144 char start = message[0];
17145 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
17146 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
17147 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
17148 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
17149 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
17150 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
17151 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
17152 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
17153 sscanf(message, "hint: %c", &c)!=1 &&
17154 sscanf(message, "pong %c", &c)!=1 && start != '#') {
17155 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
17156 print = (appData.engineComments >= 2);
17158 message[0] = start; // restore original message
17162 fprintf(debugFP, "%ld <%-6s: %s%s\n",
17163 SubtractTimeMarks(&now, &programStartTime), cps->which,
17167 fprintf(serverFP, "%ld <%-6s: %s%s\n",
17168 SubtractTimeMarks(&now, &programStartTime), cps->which,
17170 message), fflush(serverFP);
17174 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
17175 if (appData.icsEngineAnalyze) {
17176 if (strstr(message, "whisper") != NULL ||
17177 strstr(message, "kibitz") != NULL ||
17178 strstr(message, "tellics") != NULL) return;
17181 HandleMachineMove(message, cps);
17186 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
17191 if( timeControl_2 > 0 ) {
17192 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
17193 tc = timeControl_2;
17196 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
17197 inc /= cps->timeOdds;
17198 st /= cps->timeOdds;
17200 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
17203 /* Set exact time per move, normally using st command */
17204 if (cps->stKludge) {
17205 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
17207 if (seconds == 0) {
17208 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
17210 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
17213 snprintf(buf, MSG_SIZ, "st %d\n", st);
17216 /* Set conventional or incremental time control, using level command */
17217 if (seconds == 0) {
17218 /* Note old gnuchess bug -- minutes:seconds used to not work.
17219 Fixed in later versions, but still avoid :seconds
17220 when seconds is 0. */
17221 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
17223 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
17224 seconds, inc/1000.);
17227 SendToProgram(buf, cps);
17229 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
17230 /* Orthogonally, limit search to given depth */
17232 if (cps->sdKludge) {
17233 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
17235 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
17237 SendToProgram(buf, cps);
17240 if(cps->nps >= 0) { /* [HGM] nps */
17241 if(cps->supportsNPS == FALSE)
17242 cps->nps = -1; // don't use if engine explicitly says not supported!
17244 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
17245 SendToProgram(buf, cps);
17250 ChessProgramState *
17252 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
17254 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
17255 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
17261 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
17263 char message[MSG_SIZ];
17266 /* Note: this routine must be called when the clocks are stopped
17267 or when they have *just* been set or switched; otherwise
17268 it will be off by the time since the current tick started.
17270 if (machineWhite) {
17271 time = whiteTimeRemaining / 10;
17272 otime = blackTimeRemaining / 10;
17274 time = blackTimeRemaining / 10;
17275 otime = whiteTimeRemaining / 10;
17277 /* [HGM] translate opponent's time by time-odds factor */
17278 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
17280 if (time <= 0) time = 1;
17281 if (otime <= 0) otime = 1;
17283 snprintf(message, MSG_SIZ, "time %ld\n", time);
17284 SendToProgram(message, cps);
17286 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
17287 SendToProgram(message, cps);
17291 EngineDefinedVariant (ChessProgramState *cps, int n)
17292 { // return name of n-th unknown variant that engine supports
17293 static char buf[MSG_SIZ];
17294 char *p, *s = cps->variants;
17295 if(!s) return NULL;
17296 do { // parse string from variants feature
17298 p = strchr(s, ',');
17299 if(p) *p = NULLCHAR;
17300 v = StringToVariant(s);
17301 if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
17302 if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
17303 if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
17304 !strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
17305 !strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
17306 !strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
17307 if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
17310 if(n < 0) return buf;
17316 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17319 int len = strlen(name);
17322 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17324 sscanf(*p, "%d", &val);
17326 while (**p && **p != ' ')
17328 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17329 SendToProgram(buf, cps);
17336 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
17339 int len = strlen(name);
17340 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
17342 sscanf(*p, "%d", loc);
17343 while (**p && **p != ' ') (*p)++;
17344 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17345 SendToProgram(buf, cps);
17352 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
17355 int len = strlen(name);
17356 if (strncmp((*p), name, len) == 0
17357 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
17359 len = strlen(*p) + 1; if(len < MSG_SIZ && !strcmp(name, "option")) len = MSG_SIZ; // make sure string options have enough space to change their value
17360 FREE(*loc); *loc = malloc(len);
17361 strncpy(*loc, *p, len);
17362 sscanf(*p, "%[^\"]", *loc); // should always fit, because we allocated at least strlen(*p)
17363 while (**p && **p != '\"') (*p)++;
17364 if (**p == '\"') (*p)++;
17365 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
17366 SendToProgram(buf, cps);
17373 ParseOption (Option *opt, ChessProgramState *cps)
17374 // [HGM] options: process the string that defines an engine option, and determine
17375 // name, type, default value, and allowed value range
17377 char *p, *q, buf[MSG_SIZ];
17378 int n, min = (-1)<<31, max = 1<<31, def;
17380 opt->target = &opt->value; // OK for spin/slider and checkbox
17381 if(p = strstr(opt->name, " -spin ")) {
17382 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17383 if(max < min) max = min; // enforce consistency
17384 if(def < min) def = min;
17385 if(def > max) def = max;
17390 } else if((p = strstr(opt->name, " -slider "))) {
17391 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
17392 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
17393 if(max < min) max = min; // enforce consistency
17394 if(def < min) def = min;
17395 if(def > max) def = max;
17399 opt->type = Spin; // Slider;
17400 } else if((p = strstr(opt->name, " -string "))) {
17401 opt->textValue = p+9;
17402 opt->type = TextBox;
17403 opt->target = &opt->textValue;
17404 } else if((p = strstr(opt->name, " -file "))) {
17405 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17406 opt->target = opt->textValue = p+7;
17407 opt->type = FileName; // FileName;
17408 opt->target = &opt->textValue;
17409 } else if((p = strstr(opt->name, " -path "))) {
17410 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
17411 opt->target = opt->textValue = p+7;
17412 opt->type = PathName; // PathName;
17413 opt->target = &opt->textValue;
17414 } else if(p = strstr(opt->name, " -check ")) {
17415 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
17416 opt->value = (def != 0);
17417 opt->type = CheckBox;
17418 } else if(p = strstr(opt->name, " -combo ")) {
17419 opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
17420 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
17421 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
17422 opt->value = n = 0;
17423 while(q = StrStr(q, " /// ")) {
17424 n++; *q = 0; // count choices, and null-terminate each of them
17426 if(*q == '*') { // remember default, which is marked with * prefix
17430 cps->comboList[cps->comboCnt++] = q;
17432 cps->comboList[cps->comboCnt++] = NULL;
17434 opt->type = ComboBox;
17435 } else if(p = strstr(opt->name, " -button")) {
17436 opt->type = Button;
17437 } else if(p = strstr(opt->name, " -save")) {
17438 opt->type = SaveButton;
17439 } else return FALSE;
17440 *p = 0; // terminate option name
17441 *(int*) (opt->name + MSG_SIZ - 104) = opt->value; // hide default values somewhere
17442 if(opt->target == &opt->textValue) strncpy(opt->name + MSG_SIZ - 100, opt->textValue, 99);
17443 // now look if the command-line options define a setting for this engine option.
17444 if(cps->optionSettings && cps->optionSettings[0])
17445 p = strstr(cps->optionSettings, opt->name); else p = NULL;
17446 if(p && (p == cps->optionSettings || p[-1] == ',')) {
17447 snprintf(buf, MSG_SIZ, "option %s", p);
17448 if(p = strstr(buf, ",")) *p = 0;
17449 if(q = strchr(buf, '=')) switch(opt->type) {
17451 for(n=0; n<opt->max; n++)
17452 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
17457 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
17461 opt->value = atoi(q+1);
17466 SendToProgram(buf, cps);
17472 FeatureDone (ChessProgramState *cps, int val)
17474 DelayedEventCallback cb = GetDelayedEvent();
17475 if ((cb == InitBackEnd3 && cps == &first) ||
17476 (cb == SettingsMenuIfReady && cps == &second) ||
17477 (cb == LoadEngine) || (cb == StartSecond) ||
17478 (cb == TwoMachinesEventIfReady)) {
17479 CancelDelayedEvent();
17480 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
17481 } else if(!val && !cps->reload) ClearOptions(cps); // let 'spurious' done=0 clear engine's option list
17482 cps->initDone = val;
17483 if(val) cps->reload = FALSE, RefreshSettingsDialog(cps, val);
17486 /* Parse feature command from engine */
17488 ParseFeatures (char *args, ChessProgramState *cps)
17496 while (*p == ' ') p++;
17497 if (*p == NULLCHAR) return;
17499 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
17500 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
17501 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
17502 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
17503 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
17504 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
17505 if (BoolFeature(&p, "reuse", &val, cps)) {
17506 /* Engine can disable reuse, but can't enable it if user said no */
17507 if (!val) cps->reuse = FALSE;
17510 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
17511 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
17512 if (gameMode == TwoMachinesPlay) {
17513 DisplayTwoMachinesTitle();
17519 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
17520 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
17521 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
17522 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
17523 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
17524 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
17525 if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
17526 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
17527 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
17528 if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
17529 if (IntFeature(&p, "done", &val, cps)) {
17530 FeatureDone(cps, val);
17533 /* Added by Tord: */
17534 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
17535 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
17536 /* End of additions by Tord */
17538 /* [HGM] added features: */
17539 if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
17540 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
17541 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
17542 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
17543 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
17544 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
17545 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
17546 if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
17547 if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
17548 if(cps->nrOptions == 0) { ASSIGN(cps->option[0].name, _("Make Persistent -save")); ParseOption(&(cps->option[cps->nrOptions++]), cps); }
17549 FREE(cps->option[cps->nrOptions].name);
17550 cps->option[cps->nrOptions].name = q; q = NULL;
17551 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
17552 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
17553 SendToProgram(buf, cps);
17556 if(cps->nrOptions >= MAX_OPTIONS) {
17558 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
17559 DisplayError(buf, 0);
17563 /* End of additions by HGM */
17565 /* unknown feature: complain and skip */
17567 while (*q && *q != '=') q++;
17568 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
17569 SendToProgram(buf, cps);
17575 while (*p && *p != '\"') p++;
17576 if (*p == '\"') p++;
17578 while (*p && *p != ' ') p++;
17586 PeriodicUpdatesEvent (int newState)
17588 if (newState == appData.periodicUpdates)
17591 appData.periodicUpdates=newState;
17593 /* Display type changes, so update it now */
17594 // DisplayAnalysis();
17596 /* Get the ball rolling again... */
17598 AnalysisPeriodicEvent(1);
17599 StartAnalysisClock();
17604 PonderNextMoveEvent (int newState)
17606 if (newState == appData.ponderNextMove) return;
17607 if (gameMode == EditPosition) EditPositionDone(TRUE);
17609 SendToProgram("hard\n", &first);
17610 if (gameMode == TwoMachinesPlay) {
17611 SendToProgram("hard\n", &second);
17614 SendToProgram("easy\n", &first);
17615 thinkOutput[0] = NULLCHAR;
17616 if (gameMode == TwoMachinesPlay) {
17617 SendToProgram("easy\n", &second);
17620 appData.ponderNextMove = newState;
17624 NewSettingEvent (int option, int *feature, char *command, int value)
17628 if (gameMode == EditPosition) EditPositionDone(TRUE);
17629 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
17630 if(feature == NULL || *feature) SendToProgram(buf, &first);
17631 if (gameMode == TwoMachinesPlay) {
17632 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
17637 ShowThinkingEvent ()
17638 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
17640 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
17641 int newState = appData.showThinking
17642 // [HGM] thinking: other features now need thinking output as well
17643 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
17645 if (oldState == newState) return;
17646 oldState = newState;
17647 if (gameMode == EditPosition) EditPositionDone(TRUE);
17649 SendToProgram("post\n", &first);
17650 if (gameMode == TwoMachinesPlay) {
17651 SendToProgram("post\n", &second);
17654 SendToProgram("nopost\n", &first);
17655 thinkOutput[0] = NULLCHAR;
17656 if (gameMode == TwoMachinesPlay) {
17657 SendToProgram("nopost\n", &second);
17660 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
17664 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
17666 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
17667 if (pr == NoProc) return;
17668 AskQuestion(title, question, replyPrefix, pr);
17672 TypeInEvent (char firstChar)
17674 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
17675 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
17676 gameMode == AnalyzeMode || gameMode == EditGame ||
17677 gameMode == EditPosition || gameMode == IcsExamining ||
17678 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
17679 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
17680 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
17681 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
17682 gameMode == Training) PopUpMoveDialog(firstChar);
17686 TypeInDoneEvent (char *move)
17689 int n, fromX, fromY, toX, toY;
17691 ChessMove moveType;
17694 if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
17695 EditPositionPasteFEN(move);
17698 // [HGM] movenum: allow move number to be typed in any mode
17699 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
17703 // undocumented kludge: allow command-line option to be typed in!
17704 // (potentially fatal, and does not implement the effect of the option.)
17705 // should only be used for options that are values on which future decisions will be made,
17706 // and definitely not on options that would be used during initialization.
17707 if(strstr(move, "!!! -") == move) {
17708 ParseArgsFromString(move+4);
17712 if (gameMode != EditGame && currentMove != forwardMostMove &&
17713 gameMode != Training) {
17714 DisplayMoveError(_("Displayed move is not current"));
17716 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17717 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
17718 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
17719 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17720 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
17721 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
17723 DisplayMoveError(_("Could not parse move"));
17729 DisplayMove (int moveNumber)
17731 char message[MSG_SIZ];
17733 char cpThinkOutput[MSG_SIZ];
17735 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
17737 if (moveNumber == forwardMostMove - 1 ||
17738 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
17740 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
17742 if (strchr(cpThinkOutput, '\n')) {
17743 *strchr(cpThinkOutput, '\n') = NULLCHAR;
17746 *cpThinkOutput = NULLCHAR;
17749 /* [AS] Hide thinking from human user */
17750 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
17751 *cpThinkOutput = NULLCHAR;
17752 if( thinkOutput[0] != NULLCHAR ) {
17755 for( i=0; i<=hiddenThinkOutputState; i++ ) {
17756 cpThinkOutput[i] = '.';
17758 cpThinkOutput[i] = NULLCHAR;
17759 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
17763 if (moveNumber == forwardMostMove - 1 &&
17764 gameInfo.resultDetails != NULL) {
17765 if (gameInfo.resultDetails[0] == NULLCHAR) {
17766 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
17768 snprintf(res, MSG_SIZ, " {%s} %s",
17769 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
17775 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17776 DisplayMessage(res, cpThinkOutput);
17778 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
17779 WhiteOnMove(moveNumber) ? " " : ".. ",
17780 parseList[moveNumber], res);
17781 DisplayMessage(message, cpThinkOutput);
17786 DisplayComment (int moveNumber, char *text)
17788 char title[MSG_SIZ];
17790 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17791 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
17793 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
17794 WhiteOnMove(moveNumber) ? " " : ".. ",
17795 parseList[moveNumber]);
17797 if (text != NULL && (appData.autoDisplayComment || commentUp))
17798 CommentPopUp(title, text);
17801 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
17802 * might be busy thinking or pondering. It can be omitted if your
17803 * gnuchess is configured to stop thinking immediately on any user
17804 * input. However, that gnuchess feature depends on the FIONREAD
17805 * ioctl, which does not work properly on some flavors of Unix.
17808 Attention (ChessProgramState *cps)
17811 if (!cps->useSigint) return;
17812 if (appData.noChessProgram || (cps->pr == NoProc)) return;
17813 switch (gameMode) {
17814 case MachinePlaysWhite:
17815 case MachinePlaysBlack:
17816 case TwoMachinesPlay:
17817 case IcsPlayingWhite:
17818 case IcsPlayingBlack:
17821 /* Skip if we know it isn't thinking */
17822 if (!cps->maybeThinking) return;
17823 if (appData.debugMode)
17824 fprintf(debugFP, "Interrupting %s\n", cps->which);
17825 InterruptChildProcess(cps->pr);
17826 cps->maybeThinking = FALSE;
17831 #endif /*ATTENTION*/
17837 if (whiteTimeRemaining <= 0) {
17840 if (appData.icsActive) {
17841 if (appData.autoCallFlag &&
17842 gameMode == IcsPlayingBlack && !blackFlag) {
17843 SendToICS(ics_prefix);
17844 SendToICS("flag\n");
17848 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17850 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
17851 if (appData.autoCallFlag) {
17852 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
17859 if (blackTimeRemaining <= 0) {
17862 if (appData.icsActive) {
17863 if (appData.autoCallFlag &&
17864 gameMode == IcsPlayingWhite && !whiteFlag) {
17865 SendToICS(ics_prefix);
17866 SendToICS("flag\n");
17870 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17872 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
17873 if (appData.autoCallFlag) {
17874 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
17885 CheckTimeControl ()
17887 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
17888 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
17891 * add time to clocks when time control is achieved ([HGM] now also used for increment)
17893 if ( !WhiteOnMove(forwardMostMove) ) {
17894 /* White made time control */
17895 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
17896 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
17897 /* [HGM] time odds: correct new time quota for time odds! */
17898 / WhitePlayer()->timeOdds;
17899 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
17901 lastBlack -= blackTimeRemaining;
17902 /* Black made time control */
17903 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
17904 / WhitePlayer()->other->timeOdds;
17905 lastWhite = whiteTimeRemaining;
17910 DisplayBothClocks ()
17912 int wom = gameMode == EditPosition ?
17913 !blackPlaysFirst : WhiteOnMove(currentMove);
17914 DisplayWhiteClock(whiteTimeRemaining, wom);
17915 DisplayBlackClock(blackTimeRemaining, !wom);
17919 /* Timekeeping seems to be a portability nightmare. I think everyone
17920 has ftime(), but I'm really not sure, so I'm including some ifdefs
17921 to use other calls if you don't. Clocks will be less accurate if
17922 you have neither ftime nor gettimeofday.
17925 /* VS 2008 requires the #include outside of the function */
17926 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
17927 #include <sys/timeb.h>
17930 /* Get the current time as a TimeMark */
17932 GetTimeMark (TimeMark *tm)
17934 #if HAVE_GETTIMEOFDAY
17936 struct timeval timeVal;
17937 struct timezone timeZone;
17939 gettimeofday(&timeVal, &timeZone);
17940 tm->sec = (long) timeVal.tv_sec;
17941 tm->ms = (int) (timeVal.tv_usec / 1000L);
17943 #else /*!HAVE_GETTIMEOFDAY*/
17946 // include <sys/timeb.h> / moved to just above start of function
17947 struct timeb timeB;
17950 tm->sec = (long) timeB.time;
17951 tm->ms = (int) timeB.millitm;
17953 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
17954 tm->sec = (long) time(NULL);
17960 /* Return the difference in milliseconds between two
17961 time marks. We assume the difference will fit in a long!
17964 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
17966 return 1000L*(tm2->sec - tm1->sec) +
17967 (long) (tm2->ms - tm1->ms);
17972 * Code to manage the game clocks.
17974 * In tournament play, black starts the clock and then white makes a move.
17975 * We give the human user a slight advantage if he is playing white---the
17976 * clocks don't run until he makes his first move, so it takes zero time.
17977 * Also, we don't account for network lag, so we could get out of sync
17978 * with GNU Chess's clock -- but then, referees are always right.
17981 static TimeMark tickStartTM;
17982 static long intendedTickLength;
17985 NextTickLength (long timeRemaining)
17987 long nominalTickLength, nextTickLength;
17989 if (timeRemaining > 0L && timeRemaining <= 10000L)
17990 nominalTickLength = 100L;
17992 nominalTickLength = 1000L;
17993 nextTickLength = timeRemaining % nominalTickLength;
17994 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
17996 return nextTickLength;
17999 /* Adjust clock one minute up or down */
18001 AdjustClock (Boolean which, int dir)
18003 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
18004 if(which) blackTimeRemaining += 60000*dir;
18005 else whiteTimeRemaining += 60000*dir;
18006 DisplayBothClocks();
18007 adjustedClock = TRUE;
18010 /* Stop clocks and reset to a fresh time control */
18014 (void) StopClockTimer();
18015 if (appData.icsActive) {
18016 whiteTimeRemaining = blackTimeRemaining = 0;
18017 } else if (searchTime) {
18018 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18019 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18020 } else { /* [HGM] correct new time quote for time odds */
18021 whiteTC = blackTC = fullTimeControlString;
18022 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
18023 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
18025 if (whiteFlag || blackFlag) {
18027 whiteFlag = blackFlag = FALSE;
18029 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
18030 DisplayBothClocks();
18031 adjustedClock = FALSE;
18034 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
18036 static int timeSuffix; // [HGM] This should realy be a passed parameter, but it has to pass through too many levels for my laziness...
18038 /* Decrement running clock by amount of time that has passed */
18043 long lastTickLength, fudge;
18046 if (!appData.clockMode) return;
18047 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
18051 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18053 /* Fudge if we woke up a little too soon */
18054 fudge = intendedTickLength - lastTickLength;
18055 if (fudge < 0 || fudge > FUDGE) fudge = 0;
18057 if (WhiteOnMove(forwardMostMove)) {
18058 if(whiteNPS >= 0) lastTickLength = 0;
18059 tRemaining = whiteTimeRemaining -= lastTickLength;
18060 if( tRemaining < 0 && !appData.icsActive) {
18061 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
18062 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
18063 whiteStartMove = forwardMostMove; whiteTC = nextSession;
18064 lastWhite= tRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
18067 if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[0][forwardMostMove-1] - tRemaining;
18068 DisplayWhiteClock(whiteTimeRemaining - fudge,
18069 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18072 if(blackNPS >= 0) lastTickLength = 0;
18073 tRemaining = blackTimeRemaining -= lastTickLength;
18074 if( tRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
18075 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
18077 blackStartMove = forwardMostMove;
18078 lastBlack = tRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
18081 if(forwardMostMove && appData.moveTime) timeSuffix = timeRemaining[1][forwardMostMove-1] - tRemaining;
18082 DisplayBlackClock(blackTimeRemaining - fudge,
18083 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
18086 if (CheckFlags()) return;
18088 if(twoBoards) { // count down secondary board's clocks as well
18089 activePartnerTime -= lastTickLength;
18091 if(activePartner == 'W')
18092 DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
18094 DisplayBlackClock(activePartnerTime, TRUE);
18099 intendedTickLength = NextTickLength( tRemaining - fudge) + fudge;
18100 StartClockTimer(intendedTickLength);
18102 /* if the time remaining has fallen below the alarm threshold, sound the
18103 * alarm. if the alarm has sounded and (due to a takeback or time control
18104 * with increment) the time remaining has increased to a level above the
18105 * threshold, reset the alarm so it can sound again.
18108 if (appData.icsActive && appData.icsAlarm) {
18110 /* make sure we are dealing with the user's clock */
18111 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
18112 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
18115 if (alarmSounded && ( tRemaining > appData.icsAlarmTime)) {
18116 alarmSounded = FALSE;
18117 } else if (!alarmSounded && ( tRemaining <= appData.icsAlarmTime)) {
18119 alarmSounded = TRUE;
18125 /* A player has just moved, so stop the previously running
18126 clock and (if in clock mode) start the other one.
18127 We redisplay both clocks in case we're in ICS mode, because
18128 ICS gives us an update to both clocks after every move.
18129 Note that this routine is called *after* forwardMostMove
18130 is updated, so the last fractional tick must be subtracted
18131 from the color that is *not* on move now.
18134 SwitchClocks (int newMoveNr)
18136 long lastTickLength;
18138 int flagged = FALSE;
18142 if (StopClockTimer() && appData.clockMode) {
18143 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18144 if (!WhiteOnMove(forwardMostMove)) {
18145 if(blackNPS >= 0) lastTickLength = 0;
18146 blackTimeRemaining -= lastTickLength;
18147 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18148 // if(pvInfoList[forwardMostMove].time == -1)
18149 pvInfoList[forwardMostMove].time = // use GUI time
18150 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
18152 if(whiteNPS >= 0) lastTickLength = 0;
18153 whiteTimeRemaining -= lastTickLength;
18154 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
18155 // if(pvInfoList[forwardMostMove].time == -1)
18156 pvInfoList[forwardMostMove].time =
18157 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
18159 flagged = CheckFlags();
18161 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
18162 CheckTimeControl();
18164 if (flagged || !appData.clockMode) return;
18166 switch (gameMode) {
18167 case MachinePlaysBlack:
18168 case MachinePlaysWhite:
18169 case BeginningOfGame:
18170 if (pausing) return;
18174 case PlayFromGameFile:
18182 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
18183 if(WhiteOnMove(forwardMostMove))
18184 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
18185 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
18189 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18190 whiteTimeRemaining : blackTimeRemaining);
18191 StartClockTimer(intendedTickLength);
18195 /* Stop both clocks */
18199 long lastTickLength;
18202 if (!StopClockTimer()) return;
18203 if (!appData.clockMode) return;
18207 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
18208 if (WhiteOnMove(forwardMostMove)) {
18209 if(whiteNPS >= 0) lastTickLength = 0;
18210 whiteTimeRemaining -= lastTickLength;
18211 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
18213 if(blackNPS >= 0) lastTickLength = 0;
18214 blackTimeRemaining -= lastTickLength;
18215 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
18220 /* Start clock of player on move. Time may have been reset, so
18221 if clock is already running, stop and restart it. */
18225 (void) StopClockTimer(); /* in case it was running already */
18226 DisplayBothClocks();
18227 if (CheckFlags()) return;
18229 if (!appData.clockMode) return;
18230 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
18232 GetTimeMark(&tickStartTM);
18233 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
18234 whiteTimeRemaining : blackTimeRemaining);
18236 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
18237 whiteNPS = blackNPS = -1;
18238 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
18239 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
18240 whiteNPS = first.nps;
18241 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
18242 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
18243 blackNPS = first.nps;
18244 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
18245 whiteNPS = second.nps;
18246 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
18247 blackNPS = second.nps;
18248 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
18250 StartClockTimer(intendedTickLength);
18254 TimeString (long ms)
18256 long second, minute, hour, day;
18258 static char buf[40], moveTime[8];
18260 if (ms > 0 && ms <= 9900) {
18261 /* convert milliseconds to tenths, rounding up */
18262 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
18264 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
18268 /* convert milliseconds to seconds, rounding up */
18269 /* use floating point to avoid strangeness of integer division
18270 with negative dividends on many machines */
18271 second = (long) floor(((double) (ms + 999L)) / 1000.0);
18278 day = second / (60 * 60 * 24);
18279 second = second % (60 * 60 * 24);
18280 hour = second / (60 * 60);
18281 second = second % (60 * 60);
18282 minute = second / 60;
18283 second = second % 60;
18285 if(timeSuffix) snprintf(moveTime, 8, " (%d)", timeSuffix/1000); // [HGM] kludge alert; fraction contains move time
18286 else *moveTime = NULLCHAR;
18289 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld%s ",
18290 sign, day, hour, minute, second, moveTime);
18292 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld%s ", sign, hour, minute, second, moveTime);
18294 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld%s ", sign, minute, second, moveTime);
18301 * This is necessary because some C libraries aren't ANSI C compliant yet.
18304 StrStr (char *string, char *match)
18308 length = strlen(match);
18310 for (i = strlen(string) - length; i >= 0; i--, string++)
18311 if (!strncmp(match, string, length))
18318 StrCaseStr (char *string, char *match)
18322 length = strlen(match);
18324 for (i = strlen(string) - length; i >= 0; i--, string++) {
18325 for (j = 0; j < length; j++) {
18326 if (ToLower(match[j]) != ToLower(string[j]))
18329 if (j == length) return string;
18337 StrCaseCmp (char *s1, char *s2)
18342 c1 = ToLower(*s1++);
18343 c2 = ToLower(*s2++);
18344 if (c1 > c2) return 1;
18345 if (c1 < c2) return -1;
18346 if (c1 == NULLCHAR) return 0;
18354 return isupper(c) ? tolower(c) : c;
18361 return islower(c) ? toupper(c) : c;
18363 #endif /* !_amigados */
18370 if ((ret = (char *) malloc(strlen(s) + 1)))
18372 safeStrCpy(ret, s, strlen(s)+1);
18378 StrSavePtr (char *s, char **savePtr)
18383 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
18384 safeStrCpy(*savePtr, s, strlen(s)+1);
18396 clock = time((time_t *)NULL);
18397 tm = localtime(&clock);
18398 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
18399 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
18400 return StrSave(buf);
18405 PositionToFEN (int move, char *overrideCastling, int moveCounts)
18407 int i, j, fromX, fromY, toX, toY;
18408 int whiteToPlay, haveRights = nrCastlingRights;
18414 whiteToPlay = (gameMode == EditPosition) ?
18415 !blackPlaysFirst : (move % 2 == 0);
18418 /* Piece placement data */
18419 for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18420 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
18422 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
18423 if (boards[move][i][j] == EmptySquare) {
18425 } else { ChessSquare piece = boards[move][i][j];
18426 if (emptycount > 0) {
18427 if(emptycount<10) /* [HGM] can be >= 10 */
18428 *p++ = '0' + emptycount;
18429 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18432 if(PieceToChar(piece) == '+') {
18433 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
18435 piece = (ChessSquare)(CHUDEMOTED(piece));
18437 *p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
18438 if(*p = PieceSuffix(piece)) p++;
18440 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
18441 p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED(piece)));
18446 if (emptycount > 0) {
18447 if(emptycount<10) /* [HGM] can be >= 10 */
18448 *p++ = '0' + emptycount;
18449 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
18456 /* [HGM] print Crazyhouse or Shogi holdings */
18457 if( gameInfo.holdingsWidth ) {
18458 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
18460 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
18461 piece = boards[move][i][BOARD_WIDTH-1];
18462 if( piece != EmptySquare )
18463 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
18464 *p++ = PieceToChar(piece);
18466 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
18467 piece = boards[move][handSize-i-1][0];
18468 if( piece != EmptySquare )
18469 for(j=0; j<(int) boards[move][handSize-i-1][1]; j++)
18470 *p++ = PieceToChar(piece);
18473 if( q == p ) *p++ = '-';
18479 *p++ = whiteToPlay ? 'w' : 'b';
18482 if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18483 haveRights = 0; q = p;
18484 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18485 piece = boards[move][0][i];
18486 if(piece >= WhitePawn && piece <= WhiteKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18487 if(!(boards[move][TOUCHED_W] & 1<<i)) *p++ = 'A' + i; // print file ID if it has not moved
18490 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--) {
18491 piece = boards[move][BOARD_HEIGHT-1][i];
18492 if(piece >= BlackPawn && piece <= BlackKing && pieceDesc[piece] && strchr(pieceDesc[piece], 'i')) { // piece with initial move
18493 if(!(boards[move][TOUCHED_B] & 1<<i)) *p++ = 'a' + i; // print file ID if it has not moved
18496 if(p == q) *p++ = '-';
18500 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
18503 if(q != overrideCastling+1) p[-1] = ' '; else --p;
18506 int handW=0, handB=0;
18507 if(gameInfo.variant == VariantSChess) { // for S-Chess, all virgin backrank pieces must be listed
18508 for(i=0; i<BOARD_HEIGHT; i++) handW += boards[move][i][BOARD_RGHT]; // count white held pieces
18509 for(i=0; i<BOARD_HEIGHT; i++) handB += boards[move][i][BOARD_LEFT-1]; // count black held pieces
18512 if(appData.fischerCastling) {
18513 if(handW) { // in shuffle S-Chess simply dump all virgin pieces
18514 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18515 if(boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18517 /* [HGM] write directly from rights */
18518 if(boards[move][CASTLING][2] != NoRights &&
18519 boards[move][CASTLING][0] != NoRights )
18520 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
18521 if(boards[move][CASTLING][2] != NoRights &&
18522 boards[move][CASTLING][1] != NoRights )
18523 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
18526 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
18527 if(boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18529 if(boards[move][CASTLING][5] != NoRights &&
18530 boards[move][CASTLING][3] != NoRights )
18531 *p++ = boards[move][CASTLING][3] + AAA;
18532 if(boards[move][CASTLING][5] != NoRights &&
18533 boards[move][CASTLING][4] != NoRights )
18534 *p++ = boards[move][CASTLING][4] + AAA;
18538 /* [HGM] write true castling rights */
18539 if( nrCastlingRights == 6 ) {
18541 if(boards[move][CASTLING][0] != NoRights &&
18542 boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
18543 q = (boards[move][CASTLING][1] != NoRights &&
18544 boards[move][CASTLING][2] != NoRights );
18545 if(handW) { // for S-Chess with pieces in hand, list virgin pieces between K and Q
18546 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18547 if((boards[move][0][i] != WhiteKing || k+q == 0) &&
18548 boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
18552 if(boards[move][CASTLING][3] != NoRights &&
18553 boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
18554 q = (boards[move][CASTLING][4] != NoRights &&
18555 boards[move][CASTLING][5] != NoRights );
18557 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
18558 if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
18559 boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
18564 if (q == p) *p++ = '-'; /* No castling rights */
18568 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
18569 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18570 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18571 /* En passant target square */
18572 if (move > backwardMostMove) {
18573 fromX = moveList[move - 1][0] - AAA;
18574 fromY = moveList[move - 1][1] - ONE;
18575 toX = moveList[move - 1][2] - AAA;
18576 toY = moveList[move - 1][3] - ONE;
18577 if ((whiteToPlay ? toY < fromY - 1 : toY > fromY + 1) &&
18578 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) ) {
18579 /* 2-square pawn move just happened */
18580 *p++ = (3*toX + 5*fromX + 4)/8 + AAA;
18581 *p++ = (3*toY + 5*fromY + 4)/8 + ONE;
18582 if(gameInfo.variant == VariantBerolina) {
18589 } else if(move == backwardMostMove) {
18590 // [HGM] perhaps we should always do it like this, and forget the above?
18591 if((signed char)boards[move][EP_STATUS] >= 0) {
18592 *p++ = boards[move][EP_STATUS] + AAA;
18593 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
18604 i = boards[move][CHECK_COUNT];
18606 sprintf(p, "%d+%d ", i&255, i>>8);
18611 { int i = 0, j=move;
18613 /* [HGM] find reversible plies */
18614 if (appData.debugMode) { int k;
18615 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
18616 for(k=backwardMostMove; k<=forwardMostMove; k++)
18617 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
18621 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
18622 if( j == backwardMostMove ) i += initialRulePlies;
18623 sprintf(p, "%d ", i);
18624 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
18626 /* Fullmove number */
18627 sprintf(p, "%d", (move / 2) + 1);
18628 } else *--p = NULLCHAR;
18630 return StrSave(buf);
18634 ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
18636 int i, j, k, w=0, subst=0, shuffle=0, wKingRank = -1, bKingRank = -1;
18638 int emptycount, virgin[BOARD_FILES];
18639 ChessSquare piece, king = (gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing);
18643 for(i=1; i<=deadRanks; i++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) board[BOARD_HEIGHT-i][j] = DarkSquare;
18645 /* Piece placement data */
18646 for (i = BOARD_HEIGHT - 1 - deadRanks; i >= 0; i--) {
18649 if (*p == '/' || *p == ' ' || *p == '[' ) {
18651 emptycount = gameInfo.boardWidth - j;
18652 while (emptycount--)
18653 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18654 if (*p == '/') p++;
18655 else if(autoSize && i != BOARD_HEIGHT-1) { // we stumbled unexpectedly into end of board
18656 for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
18657 for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
18659 appData.NrRanks = gameInfo.boardHeight - i; i=0;
18662 #if(BOARD_FILES >= 10)*0
18663 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
18664 p++; emptycount=10;
18665 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18666 while (emptycount--)
18667 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18669 } else if (*p == '*') {
18670 board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
18671 } else if (isdigit(*p)) {
18672 emptycount = *p++ - '0';
18673 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
18674 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18675 while (emptycount--)
18676 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18677 } else if (*p == '<') {
18678 if(i == BOARD_HEIGHT-1) shuffle = 1;
18679 else if (i != 0 || !shuffle) return FALSE;
18681 } else if (shuffle && *p == '>') {
18682 p++; // for now ignore closing shuffle range, and assume rank-end
18683 } else if (*p == '?') {
18684 if (j >= gameInfo.boardWidth) return FALSE;
18685 if (i != 0 && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
18686 board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
18687 } else if (*p == '+' || isalpha(*p)) {
18688 char *q, *s = SUFFIXES;
18689 if (j >= gameInfo.boardWidth) return FALSE;
18692 if(q = strchr(s, p[1])) p++;
18693 piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18694 if(piece == EmptySquare) return FALSE; /* unknown piece */
18695 piece = (ChessSquare) (CHUPROMOTED(piece)); p++;
18696 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
18699 if(q = strchr(s, *p)) p++;
18700 piece = CharToPiece(c + (q ? 64*(q - s + 1) : 0));
18703 if(piece==EmptySquare) return FALSE; /* unknown piece */
18704 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
18705 piece = (ChessSquare) (PROMOTED(piece));
18706 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
18709 board[i][(j++)+gameInfo.holdingsWidth] = piece;
18710 if(piece == king) wKingRank = i;
18711 if(piece == WHITE_TO_BLACK king) bKingRank = i;
18717 while (*p == '/' || *p == ' ') p++;
18719 if(autoSize && w != 0) appData.NrFiles = w, InitPosition(TRUE);
18721 /* [HGM] by default clear Crazyhouse holdings, if present */
18722 if(gameInfo.holdingsWidth) {
18723 for(i=0; i<handSize; i++) {
18724 board[i][0] = EmptySquare; /* black holdings */
18725 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
18726 board[i][1] = (ChessSquare) 0; /* black counts */
18727 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
18731 /* [HGM] look for Crazyhouse holdings here */
18732 while(*p==' ') p++;
18733 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
18734 int swap=0, wcnt=0, bcnt=0;
18736 if(*p == '<') swap++, p++;
18737 if(*p == '-' ) p++; /* empty holdings */ else {
18738 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
18739 /* if we would allow FEN reading to set board size, we would */
18740 /* have to add holdings and shift the board read so far here */
18741 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
18743 if((int) piece >= (int) BlackPawn ) {
18744 i = (int)piece - (int)BlackPawn;
18745 i = PieceToNumber((ChessSquare)i);
18746 if( i >= gameInfo.holdingsSize ) return FALSE;
18747 board[handSize-1-i][0] = piece; /* black holdings */
18748 board[handSize-1-i][1]++; /* black counts */
18751 i = (int)piece - (int)WhitePawn;
18752 i = PieceToNumber((ChessSquare)i);
18753 if( i >= gameInfo.holdingsSize ) return FALSE;
18754 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
18755 board[i][BOARD_WIDTH-2]++; /* black holdings */
18759 if(subst) { // substitute back-rank question marks by holdings pieces
18760 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
18761 int k, m, n = bcnt + 1;
18762 if(board[0][j] == ClearBoard) {
18763 if(!wcnt) return FALSE;
18765 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
18766 board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
18767 if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
18771 if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
18772 if(!bcnt) return FALSE;
18773 if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
18774 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[handSize-1-k][1]) < 0) {
18775 board[BOARD_HEIGHT-1][j] = board[handSize-1-k][0]; bcnt--;
18776 if(--board[handSize-1-k][1] == 0) board[handSize-1-k][0] = EmptySquare;
18787 if(subst) return FALSE; // substitution requested, but no holdings
18789 while(*p == ' ') p++;
18793 if(appData.colorNickNames) {
18794 if( c == appData.colorNickNames[0] ) c = 'w'; else
18795 if( c == appData.colorNickNames[1] ) c = 'b';
18799 *blackPlaysFirst = FALSE;
18802 *blackPlaysFirst = TRUE;
18808 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
18809 /* return the extra info in global variiables */
18811 while(*p==' ') p++;
18813 if(!isdigit(*p) && *p != '-') { // we seem to have castling rights. Make sure they are on the rank the King actually is.
18814 if(wKingRank >= 0) for(i=0; i<3; i++) castlingRank[i] = wKingRank;
18815 if(bKingRank >= 0) for(i=3; i<6; i++) castlingRank[i] = bKingRank;
18818 /* set defaults in case FEN is incomplete */
18819 board[EP_STATUS] = EP_UNKNOWN;
18820 board[TOUCHED_W] = board[TOUCHED_B] = 0;
18821 for(i=0; i<nrCastlingRights; i++ ) {
18822 board[CASTLING][i] =
18823 appData.fischerCastling ? NoRights : initialRights[i];
18824 } /* assume possible unless obviously impossible */
18825 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
18826 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
18827 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
18828 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
18829 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
18830 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
18831 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
18832 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
18835 if(pieceDesc[WhiteKing] && strchr(pieceDesc[WhiteKing], 'i') && !strchr(pieceDesc[WhiteKing], 'O')) { // redefined without castling
18838 while(isalpha(*p)) {
18839 if(isupper(*p)) w |= 1 << (*p++ - 'A');
18840 if(islower(*p)) b |= 1 << (*p++ - 'a');
18844 board[TOUCHED_W] = ~w;
18845 board[TOUCHED_B] = ~b;
18846 while(*p == ' ') p++;
18850 if(nrCastlingRights) {
18852 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
18853 if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
18854 /* castling indicator present, so default becomes no castlings */
18855 for(i=0; i<nrCastlingRights; i++ ) {
18856 board[CASTLING][i] = NoRights;
18859 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
18860 (appData.fischerCastling || gameInfo.variant == VariantSChess) &&
18861 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
18862 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
18863 int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
18865 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
18866 if(board[castlingRank[5]][i] == BlackKing) blackKingFile = i;
18867 if(board[castlingRank[2]][i] == WhiteKing) whiteKingFile = i;
18869 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
18870 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
18871 if(whiteKingFile == NoRights || board[castlingRank[2]][whiteKingFile] != WhiteUnicorn
18872 && board[castlingRank[2]][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
18873 if(blackKingFile == NoRights || board[castlingRank[5]][blackKingFile] != BlackUnicorn
18874 && board[castlingRank[5]][blackKingFile] != BlackKing) blackKingFile = NoRights;
18877 for(i=BOARD_RGHT-1; board[castlingRank[2]][i]!=WhiteRook && i>whiteKingFile; i--);
18878 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
18879 board[CASTLING][2] = whiteKingFile;
18880 if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
18881 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18882 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18885 for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[2]][i]!=WhiteRook && i<whiteKingFile; i++);
18886 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
18887 board[CASTLING][2] = whiteKingFile;
18888 if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
18889 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18890 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18893 for(i=BOARD_RGHT-1; board[castlingRank[5]][i]!=BlackRook && i>blackKingFile; i--);
18894 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
18895 board[CASTLING][5] = blackKingFile;
18896 if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
18897 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18898 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18901 for(i=BOARD_LEFT; i<BOARD_RGHT && board[castlingRank[5]][i]!=BlackRook && i<blackKingFile; i++);
18902 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
18903 board[CASTLING][5] = blackKingFile;
18904 if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
18905 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18906 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18909 default: /* FRC castlings */
18910 if(c >= 'a') { /* black rights */
18911 if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
18912 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18913 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
18914 if(i == BOARD_RGHT) break;
18915 board[CASTLING][5] = i;
18917 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
18918 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
18920 board[CASTLING][3] = c;
18922 board[CASTLING][4] = c;
18923 } else { /* white rights */
18924 if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
18925 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18926 if(board[0][i] == WhiteKing) break;
18927 if(i == BOARD_RGHT) break;
18928 board[CASTLING][2] = i;
18929 c -= AAA - 'a' + 'A';
18930 if(board[0][c] >= WhiteKing) break;
18932 board[CASTLING][0] = c;
18934 board[CASTLING][1] = c;
18938 for(i=0; i<nrCastlingRights; i++)
18939 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
18940 if(gameInfo.variant == VariantSChess)
18941 for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
18942 if(fischer && shuffle) appData.fischerCastling = TRUE;
18943 if (appData.debugMode) {
18944 fprintf(debugFP, "FEN castling rights:");
18945 for(i=0; i<nrCastlingRights; i++)
18946 fprintf(debugFP, " %d", board[CASTLING][i]);
18947 fprintf(debugFP, "\n");
18950 while(*p==' ') p++;
18953 if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
18955 /* read e.p. field in games that know e.p. capture */
18956 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
18957 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18958 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18960 p++; board[EP_STATUS] = EP_NONE;
18962 int d, r, c = *p - AAA;
18964 if(c >= BOARD_LEFT && c < BOARD_RGHT) {
18966 board[EP_STATUS] = board[EP_FILE] = c; r = 0;
18967 if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18968 d = (r < BOARD_HEIGHT << 1 ? 1 : -1); // assume double-push (P next to e.p. square nearer center)
18969 if(board[r+d][c] == EmptySquare) d *= 2; // but if no Pawn there, triple push
18970 board[LAST_TO] = 256*(r + d) + c;
18972 if(c >= BOARD_LEFT && c < BOARD_RGHT) { // mover explicitly mentioned
18973 if(*p >= '0' && *p <='9') r = board[EP_RANK] = *p++ - ONE;
18974 board[LAST_TO] = 256*r + c;
18975 if(!(board[EP_RANK]-r & 1)) board[EP_RANK] |= 128;
18981 while(*p == ' ') p++;
18983 board[CHECK_COUNT] = 0; // [HGM] 3check: check-count field
18984 if(sscanf(p, "%d+%d", &i, &j) == 2) {
18985 board[CHECK_COUNT] = i + 256*j;
18986 while(*p && *p != ' ') p++;
18989 c = sscanf(p, "%d%*d +%d+%d", &i, &j, &k);
18991 FENrulePlies = i; /* 50-move ply counter */
18992 /* (The move number is still ignored) */
18993 if(c == 3 && !board[CHECK_COUNT]) board[CHECK_COUNT] = (3 - j) + 256*(3 - k); // SCIDB-style check count
19000 EditPositionPasteFEN (char *fen)
19003 Board initial_position;
19005 if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
19006 DisplayError(_("Bad FEN position in clipboard"), 0);
19009 int savedBlackPlaysFirst = blackPlaysFirst;
19010 EditPositionEvent();
19011 blackPlaysFirst = savedBlackPlaysFirst;
19012 CopyBoard(boards[0], initial_position);
19013 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
19014 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
19015 DisplayBothClocks();
19016 DrawPosition(FALSE, boards[currentMove]);
19021 static char cseq[12] = "\\ ";
19024 set_cont_sequence (char *new_seq)
19029 // handle bad attempts to set the sequence
19031 return 0; // acceptable error - no debug
19033 len = strlen(new_seq);
19034 ret = (len > 0) && (len < sizeof(cseq));
19036 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
19037 else if (appData.debugMode)
19038 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
19043 reformat a source message so words don't cross the width boundary. internal
19044 newlines are not removed. returns the wrapped size (no null character unless
19045 included in source message). If dest is NULL, only calculate the size required
19046 for the dest buffer. lp argument indicats line position upon entry, and it's
19047 passed back upon exit.
19050 wrap (char *dest, char *src, int count, int width, int *lp)
19052 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
19054 cseq_len = strlen(cseq);
19055 old_line = line = *lp;
19056 ansi = len = clen = 0;
19058 for (i=0; i < count; i++)
19060 if (src[i] == '\033')
19063 // if we hit the width, back up
19064 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
19066 // store i & len in case the word is too long
19067 old_i = i, old_len = len;
19069 // find the end of the last word
19070 while (i && src[i] != ' ' && src[i] != '\n')
19076 // word too long? restore i & len before splitting it
19077 if ((old_i-i+clen) >= width)
19084 if (i && src[i-1] == ' ')
19087 if (src[i] != ' ' && src[i] != '\n')
19094 // now append the newline and continuation sequence
19099 strncpy(dest+len, cseq, cseq_len);
19107 dest[len] = src[i];
19111 if (src[i] == '\n')
19116 if (dest && appData.debugMode)
19118 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
19119 count, width, line, len, *lp);
19120 show_bytes(debugFP, src, count);
19121 fprintf(debugFP, "\ndest: ");
19122 show_bytes(debugFP, dest, len);
19123 fprintf(debugFP, "\n");
19125 *lp = dest ? line : old_line;
19130 // [HGM] vari: routines for shelving variations
19131 Boolean modeRestore = FALSE;
19134 PushInner (int firstMove, int lastMove)
19136 int i, j, nrMoves = lastMove - firstMove;
19138 // push current tail of game on stack
19139 savedResult[storedGames] = gameInfo.result;
19140 savedDetails[storedGames] = gameInfo.resultDetails;
19141 gameInfo.resultDetails = NULL;
19142 savedFirst[storedGames] = firstMove;
19143 savedLast [storedGames] = lastMove;
19144 savedFramePtr[storedGames] = framePtr;
19145 framePtr -= nrMoves; // reserve space for the boards
19146 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
19147 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
19148 for(j=0; j<MOVE_LEN; j++)
19149 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
19150 for(j=0; j<2*MOVE_LEN; j++)
19151 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
19152 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
19153 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
19154 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
19155 pvInfoList[firstMove+i-1].depth = 0;
19156 commentList[framePtr+i] = commentList[firstMove+i];
19157 commentList[firstMove+i] = NULL;
19161 forwardMostMove = firstMove; // truncate game so we can start variation
19165 PushTail (int firstMove, int lastMove)
19167 if(appData.icsActive) { // only in local mode
19168 forwardMostMove = currentMove; // mimic old ICS behavior
19171 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
19173 PushInner(firstMove, lastMove);
19174 if(storedGames == 1) GreyRevert(FALSE);
19175 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
19179 PopInner (Boolean annotate)
19182 char buf[8000], moveBuf[20];
19184 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
19185 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
19186 nrMoves = savedLast[storedGames] - currentMove;
19189 if(!WhiteOnMove(currentMove))
19190 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
19191 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
19192 for(i=currentMove; i<forwardMostMove; i++) {
19194 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
19195 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
19196 strcat(buf, moveBuf);
19197 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
19198 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
19202 for(i=1; i<=nrMoves; i++) { // copy last variation back
19203 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
19204 for(j=0; j<MOVE_LEN; j++)
19205 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
19206 for(j=0; j<2*MOVE_LEN; j++)
19207 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
19208 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
19209 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
19210 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
19211 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
19212 commentList[currentMove+i] = commentList[framePtr+i];
19213 commentList[framePtr+i] = NULL;
19215 if(annotate) AppendComment(currentMove+1, buf, FALSE);
19216 framePtr = savedFramePtr[storedGames];
19217 gameInfo.result = savedResult[storedGames];
19218 if(gameInfo.resultDetails != NULL) {
19219 free(gameInfo.resultDetails);
19221 gameInfo.resultDetails = savedDetails[storedGames];
19222 forwardMostMove = currentMove + nrMoves;
19226 PopTail (Boolean annotate)
19228 if(appData.icsActive) return FALSE; // only in local mode
19229 if(!storedGames) return FALSE; // sanity
19230 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
19232 PopInner(annotate);
19233 if(currentMove < forwardMostMove) ForwardEvent(); else
19234 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
19236 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
19242 { // remove all shelved variations
19244 for(i=0; i<storedGames; i++) {
19245 if(savedDetails[i])
19246 free(savedDetails[i]);
19247 savedDetails[i] = NULL;
19249 for(i=framePtr; i<MAX_MOVES; i++) {
19250 if(commentList[i]) free(commentList[i]);
19251 commentList[i] = NULL;
19253 framePtr = MAX_MOVES-1;
19258 LoadVariation (int index, char *text)
19259 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
19260 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
19261 int level = 0, move;
19263 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
19264 // first find outermost bracketing variation
19265 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
19266 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
19267 if(*p == '{') wait = '}'; else
19268 if(*p == '[') wait = ']'; else
19269 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
19270 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
19272 if(*p == wait) wait = NULLCHAR; // closing ]} found
19275 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
19276 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
19277 end[1] = NULLCHAR; // clip off comment beyond variation
19278 ToNrEvent(currentMove-1);
19279 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
19280 // kludge: use ParsePV() to append variation to game
19281 move = currentMove;
19282 ParsePV(start, TRUE, TRUE);
19283 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
19284 ClearPremoveHighlights();
19286 ToNrEvent(currentMove+1);
19289 int transparency[2];
19294 #define BUF_SIZ (2*MSG_SIZ)
19295 char *p, *q, buf[BUF_SIZ];
19296 if(engineLine && engineLine[0]) { // a theme was selected from the listbox
19297 snprintf(buf, BUF_SIZ, "-theme %s", engineLine);
19298 ParseArgsFromString(buf);
19299 ActivateTheme(TRUE); // also redo colors
19303 if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
19306 q = appData.themeNames;
19307 snprintf(buf, BUF_SIZ, "\"%s\"", nickName);
19308 if(appData.useBitmaps) {
19309 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt true -lbtf \"%s\"",
19310 Shorten(appData.liteBackTextureFile));
19311 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dbtf \"%s\" -lbtm %d -dbtm %d",
19312 Shorten(appData.darkBackTextureFile),
19313 appData.liteBackTextureMode,
19314 appData.darkBackTextureMode );
19316 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ubt false");
19318 if(!appData.useBitmaps || transparency[0]) {
19319 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -lsc %s", Col2Text(2) ); // lightSquareColor
19321 if(!appData.useBitmaps || transparency[1]) {
19322 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -dsc %s", Col2Text(3) ); // darkSquareColor
19324 if(appData.useBorder) {
19325 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub true -border \"%s\"",
19328 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -ub false");
19330 if(appData.useFont) {
19331 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
19332 appData.renderPiecesWithFont,
19333 appData.fontToPieceTable,
19334 Col2Text(9), // appData.fontBackColorWhite
19335 Col2Text(10) ); // appData.fontForeColorBlack
19337 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -upf false");
19338 if(appData.pieceDirectory[0]) {
19339 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -pid \"%s\"", Shorten(appData.pieceDirectory));
19340 if(appData.trueColors != 2) // 2 is a kludge to suppress this in WinBoard
19341 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -trueColors %s", appData.trueColors ? "true" : "false");
19343 if(!appData.pieceDirectory[0] || !appData.trueColors)
19344 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -wpc %s -bpc %s",
19345 Col2Text(0), // whitePieceColor
19346 Col2Text(1) ); // blackPieceColor
19348 snprintf(buf+strlen(buf), BUF_SIZ-strlen(buf), " -hsc %s -phc %s\n",
19349 Col2Text(4), // highlightSquareColor
19350 Col2Text(5) ); // premoveHighlightColor
19351 appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
19352 if(insert != q) insert[-1] = NULLCHAR;
19353 snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
19356 ActivateTheme(FALSE);