2 * backend.c -- Common back end for X and Windows NT versions of
4 * Copyright 1991 by Digital Equipment Corporation, Maynard,
7 * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8 * 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
10 * Enhancements Copyright 2005 Alessandro Scotti
12 * The following terms apply to Digital Equipment Corporation's copyright
14 * ------------------------------------------------------------------------
17 * Permission to use, copy, modify, and distribute this software and its
18 * documentation for any purpose and without fee is hereby granted,
19 * provided that the above copyright notice appear in all copies and that
20 * both that copyright notice and this permission notice appear in
21 * supporting documentation, and that the name of Digital not be
22 * used in advertising or publicity pertaining to distribution of the
23 * software without specific, written prior permission.
25 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32 * ------------------------------------------------------------------------
34 * The following terms apply to the enhanced version of XBoard
35 * distributed by the Free Software Foundation:
36 * ------------------------------------------------------------------------
38 * GNU XBoard is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or (at
41 * your option) any later version.
43 * GNU XBoard is distributed in the hope that it will be useful, but
44 * WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see http://www.gnu.org/licenses/. *
51 *------------------------------------------------------------------------
52 ** See the file ChangeLog for a revision history. */
54 /* [AS] Also useful here for debugging */
58 int flock(int f, int code);
63 # define EGBB_NAME "egbbdll64.dll"
65 # define EGBB_NAME "egbbdll.dll"
70 # include <sys/file.h>
75 # define EGBB_NAME "egbbso64.so"
77 # define EGBB_NAME "egbbso.so"
79 // kludge to allow Windows code in back-end by converting it to corresponding Linux code
81 # define HMODULE void *
82 # define LoadLibrary(x) dlopen(x, RTLD_LAZY)
83 # define GetProcAddress dlsym
93 #include <sys/types.h>
102 #else /* not STDC_HEADERS */
105 # else /* not HAVE_STRING_H */
106 # include <strings.h>
107 # endif /* not HAVE_STRING_H */
108 #endif /* not STDC_HEADERS */
111 # include <sys/fcntl.h>
112 #else /* not HAVE_SYS_FCNTL_H */
115 # endif /* HAVE_FCNTL_H */
116 #endif /* not HAVE_SYS_FCNTL_H */
118 #if TIME_WITH_SYS_TIME
119 # include <sys/time.h>
123 # include <sys/time.h>
129 #if defined(_amigados) && !defined(__GNUC__)
134 extern int gettimeofday(struct timeval *, struct timezone *);
142 #include "frontend.h"
149 #include "backendz.h"
150 #include "evalgraph.h"
151 #include "engineoutput.h"
155 # define _(s) gettext (s)
156 # define N_(s) gettext_noop (s)
157 # define T_(s) gettext(s)
170 int establish P((void));
171 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
172 char *buf, int count, int error));
173 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
174 char *buf, int count, int error));
175 void SendToICS P((char *s));
176 void SendToICSDelayed P((char *s, long msdelay));
177 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
178 void HandleMachineMove P((char *message, ChessProgramState *cps));
179 int AutoPlayOneMove P((void));
180 int LoadGameOneMove P((ChessMove readAhead));
181 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
182 int LoadPositionFromFile P((char *filename, int n, char *title));
183 int SavePositionToFile P((char *filename));
184 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
185 void ShowMove P((int fromX, int fromY, int toX, int toY));
186 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
187 /*char*/int promoChar));
188 void BackwardInner P((int target));
189 void ForwardInner P((int target));
190 int Adjudicate P((ChessProgramState *cps));
191 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
192 void EditPositionDone P((Boolean fakeRights));
193 void PrintOpponents P((FILE *fp));
194 void PrintPosition P((FILE *fp, int move));
195 void StartChessProgram P((ChessProgramState *cps));
196 void SendToProgram P((char *message, ChessProgramState *cps));
197 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
198 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
199 char *buf, int count, int error));
200 void SendTimeControl P((ChessProgramState *cps,
201 int mps, long tc, int inc, int sd, int st));
202 char *TimeControlTagValue P((void));
203 void Attention P((ChessProgramState *cps));
204 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
205 int ResurrectChessProgram P((void));
206 void DisplayComment P((int moveNumber, char *text));
207 void DisplayMove P((int moveNumber));
209 void ParseGameHistory P((char *game));
210 void ParseBoard12 P((char *string));
211 void KeepAlive P((void));
212 void StartClocks P((void));
213 void SwitchClocks P((int nr));
214 void StopClocks P((void));
215 void ResetClocks P((void));
216 char *PGNDate P((void));
217 void SetGameInfo P((void));
218 int RegisterMove P((void));
219 void MakeRegisteredMove P((void));
220 void TruncateGame P((void));
221 int looking_at P((char *, int *, char *));
222 void CopyPlayerNameIntoFileName P((char **, char *));
223 char *SavePart P((char *));
224 int SaveGameOldStyle P((FILE *));
225 int SaveGamePGN P((FILE *));
226 int CheckFlags P((void));
227 long NextTickLength P((long));
228 void CheckTimeControl P((void));
229 void show_bytes P((FILE *, char *, int));
230 int string_to_rating P((char *str));
231 void ParseFeatures P((char* args, ChessProgramState *cps));
232 void InitBackEnd3 P((void));
233 void FeatureDone P((ChessProgramState* cps, int val));
234 void InitChessProgram P((ChessProgramState *cps, int setup));
235 void OutputKibitz(int window, char *text);
236 int PerpetualChase(int first, int last);
237 int EngineOutputIsUp();
238 void InitDrawingSizes(int x, int y);
239 void NextMatchGame P((void));
240 int NextTourneyGame P((int nr, int *swap));
241 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
242 FILE *WriteTourneyFile P((char *results, FILE *f));
243 void DisplayTwoMachinesTitle P(());
244 static void ExcludeClick P((int index));
245 void ToggleSecond P((void));
246 void PauseEngine P((ChessProgramState *cps));
247 static int NonStandardBoardSize P((VariantClass v, int w, int h, int s));
250 extern void ConsoleCreate();
253 ChessProgramState *WhitePlayer();
254 int VerifyDisplayMode P(());
256 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
257 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
258 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
259 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
260 void ics_update_width P((int new_width));
261 extern char installDir[MSG_SIZ];
262 VariantClass startVariant; /* [HGM] nicks: initial variant */
265 extern int tinyLayout, smallLayout;
266 ChessProgramStats programStats;
267 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
269 static int exiting = 0; /* [HGM] moved to top */
270 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
271 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
272 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
273 int partnerHighlight[2];
274 Boolean partnerBoardValid = 0;
275 char partnerStatus[MSG_SIZ];
277 Boolean originalFlip;
278 Boolean twoBoards = 0;
279 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
280 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
281 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
282 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
283 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
284 int opponentKibitzes;
285 int lastSavedGame; /* [HGM] save: ID of game */
286 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
287 extern int chatCount;
289 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
290 char legal[BOARD_RANKS][BOARD_FILES]; /* [HGM] legal target squares */
291 char lastMsg[MSG_SIZ];
292 char lastTalker[MSG_SIZ];
293 ChessSquare pieceSweep = EmptySquare;
294 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
295 int promoDefaultAltered;
296 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
297 static int initPing = -1;
298 static Boolean pieceDefs;
300 /* States for ics_getting_history */
302 #define H_REQUESTED 1
303 #define H_GOT_REQ_HEADER 2
304 #define H_GOT_UNREQ_HEADER 3
305 #define H_GETTING_MOVES 4
306 #define H_GOT_UNWANTED_HEADER 5
308 /* whosays values for GameEnds */
317 /* Maximum number of games in a cmail message */
318 #define CMAIL_MAX_GAMES 20
320 /* Different types of move when calling RegisterMove */
322 #define CMAIL_RESIGN 1
324 #define CMAIL_ACCEPT 3
326 /* Different types of result to remember for each game */
327 #define CMAIL_NOT_RESULT 0
328 #define CMAIL_OLD_RESULT 1
329 #define CMAIL_NEW_RESULT 2
331 /* Telnet protocol constants */
342 safeStrCpy (char *dst, const char *src, size_t count)
345 assert( dst != NULL );
346 assert( src != NULL );
349 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
350 if( i == count && dst[count-1] != NULLCHAR)
352 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
353 if(appData.debugMode)
354 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
360 /* Some compiler can't cast u64 to double
361 * This function do the job for us:
363 * We use the highest bit for cast, this only
364 * works if the highest bit is not
365 * in use (This should not happen)
367 * We used this for all compiler
370 u64ToDouble (u64 value)
373 u64 tmp = value & u64Const(0x7fffffffffffffff);
374 r = (double)(s64)tmp;
375 if (value & u64Const(0x8000000000000000))
376 r += 9.2233720368547758080e18; /* 2^63 */
380 /* Fake up flags for now, as we aren't keeping track of castling
381 availability yet. [HGM] Change of logic: the flag now only
382 indicates the type of castlings allowed by the rule of the game.
383 The actual rights themselves are maintained in the array
384 castlingRights, as part of the game history, and are not probed
390 int flags = F_ALL_CASTLE_OK;
391 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
392 switch (gameInfo.variant) {
394 flags &= ~F_ALL_CASTLE_OK;
395 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
396 flags |= F_IGNORE_CHECK;
398 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
401 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
403 case VariantKriegspiel:
404 flags |= F_KRIEGSPIEL_CAPTURE;
406 case VariantCapaRandom:
407 case VariantFischeRandom:
408 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
409 case VariantNoCastle:
410 case VariantShatranj:
415 flags &= ~F_ALL_CASTLE_OK;
418 case VariantChuChess:
420 flags |= F_NULL_MOVE;
425 if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
429 FILE *gameFileFP, *debugFP, *serverFP;
430 char *currentDebugFile; // [HGM] debug split: to remember name
433 [AS] Note: sometimes, the sscanf() function is used to parse the input
434 into a fixed-size buffer. Because of this, we must be prepared to
435 receive strings as long as the size of the input buffer, which is currently
436 set to 4K for Windows and 8K for the rest.
437 So, we must either allocate sufficiently large buffers here, or
438 reduce the size of the input buffer in the input reading part.
441 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
442 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
443 char thinkOutput1[MSG_SIZ*10];
445 ChessProgramState first, second, pairing;
447 /* premove variables */
450 int premoveFromX = 0;
451 int premoveFromY = 0;
452 int premovePromoChar = 0;
454 Boolean alarmSounded;
455 /* end premove variables */
457 char *ics_prefix = "$";
458 enum ICS_TYPE ics_type = ICS_GENERIC;
460 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
461 int pauseExamForwardMostMove = 0;
462 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
463 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
464 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
465 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
466 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
467 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
468 int whiteFlag = FALSE, blackFlag = FALSE;
469 int userOfferedDraw = FALSE;
470 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
471 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
472 int cmailMoveType[CMAIL_MAX_GAMES];
473 long ics_clock_paused = 0;
474 ProcRef icsPR = NoProc, cmailPR = NoProc;
475 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
476 GameMode gameMode = BeginningOfGame;
477 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
478 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
479 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
480 int hiddenThinkOutputState = 0; /* [AS] */
481 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
482 int adjudicateLossPlies = 6;
483 char white_holding[64], black_holding[64];
484 TimeMark lastNodeCountTime;
485 long lastNodeCount=0;
486 int shiftKey, controlKey; // [HGM] set by mouse handler
488 int have_sent_ICS_logon = 0;
490 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
491 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
492 Boolean adjustedClock;
493 long timeControl_2; /* [AS] Allow separate time controls */
494 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
495 long timeRemaining[2][MAX_MOVES];
496 int matchGame = 0, nextGame = 0, roundNr = 0;
497 Boolean waitingForGame = FALSE, startingEngine = FALSE;
498 TimeMark programStartTime, pauseStart;
499 char ics_handle[MSG_SIZ];
500 int have_set_title = 0;
502 /* animateTraining preserves the state of appData.animate
503 * when Training mode is activated. This allows the
504 * response to be animated when appData.animate == TRUE and
505 * appData.animateDragging == TRUE.
507 Boolean animateTraining;
513 Board boards[MAX_MOVES];
514 /* [HGM] Following 7 needed for accurate legality tests: */
515 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
516 signed char initialRights[BOARD_FILES];
517 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
518 int initialRulePlies, FENrulePlies;
519 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
521 Boolean shuffleOpenings;
522 int mute; // mute all sounds
524 // [HGM] vari: next 12 to save and restore variations
525 #define MAX_VARIATIONS 10
526 int framePtr = MAX_MOVES-1; // points to free stack entry
528 int savedFirst[MAX_VARIATIONS];
529 int savedLast[MAX_VARIATIONS];
530 int savedFramePtr[MAX_VARIATIONS];
531 char *savedDetails[MAX_VARIATIONS];
532 ChessMove savedResult[MAX_VARIATIONS];
534 void PushTail P((int firstMove, int lastMove));
535 Boolean PopTail P((Boolean annotate));
536 void PushInner P((int firstMove, int lastMove));
537 void PopInner P((Boolean annotate));
538 void CleanupTail P((void));
540 ChessSquare FIDEArray[2][BOARD_FILES] = {
541 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
542 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
544 BlackKing, BlackBishop, BlackKnight, BlackRook }
547 ChessSquare twoKingsArray[2][BOARD_FILES] = {
548 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
549 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
550 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
551 BlackKing, BlackKing, BlackKnight, BlackRook }
554 ChessSquare KnightmateArray[2][BOARD_FILES] = {
555 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
556 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
557 { BlackRook, BlackMan, BlackBishop, BlackQueen,
558 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
561 ChessSquare SpartanArray[2][BOARD_FILES] = {
562 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
563 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
564 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
565 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
568 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
569 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
570 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
571 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
572 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
575 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
576 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
577 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
578 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
579 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
582 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
583 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
584 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
585 { BlackRook, BlackKnight, BlackMan, BlackFerz,
586 BlackKing, BlackMan, BlackKnight, BlackRook }
589 ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
590 { WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
591 WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
592 { BlackRook, BlackKnight, BlackMan, BlackFerz,
593 BlackKing, BlackMan, BlackKnight, BlackRook }
596 ChessSquare lionArray[2][BOARD_FILES] = {
597 { WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
598 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
599 { BlackRook, BlackLion, BlackBishop, BlackQueen,
600 BlackKing, BlackBishop, BlackKnight, BlackRook }
604 #if (BOARD_FILES>=10)
605 ChessSquare ShogiArray[2][BOARD_FILES] = {
606 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
607 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
608 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
609 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
612 ChessSquare XiangqiArray[2][BOARD_FILES] = {
613 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
614 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
615 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
616 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
619 ChessSquare CapablancaArray[2][BOARD_FILES] = {
620 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
621 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
622 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
623 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
626 ChessSquare GreatArray[2][BOARD_FILES] = {
627 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
628 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
629 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
630 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
633 ChessSquare JanusArray[2][BOARD_FILES] = {
634 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
635 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
636 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
637 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
640 ChessSquare GrandArray[2][BOARD_FILES] = {
641 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
642 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
643 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
644 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
647 ChessSquare ChuChessArray[2][BOARD_FILES] = {
648 { WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
649 WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
650 { BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
651 BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
655 ChessSquare GothicArray[2][BOARD_FILES] = {
656 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
657 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
658 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
659 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
662 #define GothicArray CapablancaArray
666 ChessSquare FalconArray[2][BOARD_FILES] = {
667 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
668 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
669 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
670 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
673 #define FalconArray CapablancaArray
676 #else // !(BOARD_FILES>=10)
677 #define XiangqiPosition FIDEArray
678 #define CapablancaArray FIDEArray
679 #define GothicArray FIDEArray
680 #define GreatArray FIDEArray
681 #endif // !(BOARD_FILES>=10)
683 #if (BOARD_FILES>=12)
684 ChessSquare CourierArray[2][BOARD_FILES] = {
685 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
686 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
687 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
688 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
690 ChessSquare ChuArray[6][BOARD_FILES] = {
691 { WhiteLance, WhiteUnicorn, WhiteMan, WhiteFerz, WhiteWazir, WhiteKing,
692 WhiteAlfil, WhiteWazir, WhiteFerz, WhiteMan, WhiteUnicorn, WhiteLance },
693 { BlackLance, BlackUnicorn, BlackMan, BlackFerz, BlackWazir, BlackAlfil,
694 BlackKing, BlackWazir, BlackFerz, BlackMan, BlackUnicorn, BlackLance },
695 { WhiteCannon, EmptySquare, WhiteBishop, EmptySquare, WhiteNightrider, WhiteMarshall,
696 WhiteAngel, WhiteNightrider, EmptySquare, WhiteBishop, EmptySquare, WhiteCannon },
697 { BlackCannon, EmptySquare, BlackBishop, EmptySquare, BlackNightrider, BlackAngel,
698 BlackMarshall, BlackNightrider, EmptySquare, BlackBishop, EmptySquare, BlackCannon },
699 { WhiteFalcon, WhiteSilver, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
700 WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSilver, WhiteFalcon },
701 { BlackFalcon, BlackSilver, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
702 BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSilver, BlackFalcon }
704 #else // !(BOARD_FILES>=12)
705 #define CourierArray CapablancaArray
706 #define ChuArray CapablancaArray
707 #endif // !(BOARD_FILES>=12)
710 Board initialPosition;
713 /* Convert str to a rating. Checks for special cases of "----",
715 "++++", etc. Also strips ()'s */
717 string_to_rating (char *str)
719 while(*str && !isdigit(*str)) ++str;
721 return 0; /* One of the special "no rating" cases */
729 /* Init programStats */
730 programStats.movelist[0] = 0;
731 programStats.depth = 0;
732 programStats.nr_moves = 0;
733 programStats.moves_left = 0;
734 programStats.nodes = 0;
735 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
736 programStats.score = 0;
737 programStats.got_only_move = 0;
738 programStats.got_fail = 0;
739 programStats.line_is_book = 0;
744 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
745 if (appData.firstPlaysBlack) {
746 first.twoMachinesColor = "black\n";
747 second.twoMachinesColor = "white\n";
749 first.twoMachinesColor = "white\n";
750 second.twoMachinesColor = "black\n";
753 first.other = &second;
754 second.other = &first;
757 if(appData.timeOddsMode) {
758 norm = appData.timeOdds[0];
759 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
761 first.timeOdds = appData.timeOdds[0]/norm;
762 second.timeOdds = appData.timeOdds[1]/norm;
765 if(programVersion) free(programVersion);
766 if (appData.noChessProgram) {
767 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
768 sprintf(programVersion, "%s", PACKAGE_STRING);
770 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
771 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
772 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
777 UnloadEngine (ChessProgramState *cps)
779 /* Kill off first chess program */
780 if (cps->isr != NULL)
781 RemoveInputSource(cps->isr);
784 if (cps->pr != NoProc) {
786 DoSleep( appData.delayBeforeQuit );
787 SendToProgram("quit\n", cps);
788 DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
791 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
795 ClearOptions (ChessProgramState *cps)
798 cps->nrOptions = cps->comboCnt = 0;
799 for(i=0; i<MAX_OPTIONS; i++) {
800 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
801 cps->option[i].textValue = 0;
805 char *engineNames[] = {
806 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
807 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
809 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
810 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
815 InitEngine (ChessProgramState *cps, int n)
816 { // [HGM] all engine initialiation put in a function that does one engine
820 cps->which = engineNames[n];
821 cps->maybeThinking = FALSE;
825 cps->sendDrawOffers = 1;
827 cps->program = appData.chessProgram[n];
828 cps->host = appData.host[n];
829 cps->dir = appData.directory[n];
830 cps->initString = appData.engInitString[n];
831 cps->computerString = appData.computerString[n];
832 cps->useSigint = TRUE;
833 cps->useSigterm = TRUE;
834 cps->reuse = appData.reuse[n];
835 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
836 cps->useSetboard = FALSE;
838 cps->usePing = FALSE;
841 cps->usePlayother = FALSE;
842 cps->useColors = TRUE;
843 cps->useUsermove = FALSE;
844 cps->sendICS = FALSE;
845 cps->sendName = appData.icsActive;
846 cps->sdKludge = FALSE;
847 cps->stKludge = FALSE;
848 if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
849 TidyProgramName(cps->program, cps->host, cps->tidy);
851 ASSIGN(cps->variants, appData.variant);
852 cps->analysisSupport = 2; /* detect */
853 cps->analyzing = FALSE;
854 cps->initDone = FALSE;
856 cps->pseudo = appData.pseudo[n];
858 /* New features added by Tord: */
859 cps->useFEN960 = FALSE;
860 cps->useOOCastle = TRUE;
861 /* End of new features added by Tord. */
862 cps->fenOverride = appData.fenOverride[n];
864 /* [HGM] time odds: set factor for each machine */
865 cps->timeOdds = appData.timeOdds[n];
867 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
868 cps->accumulateTC = appData.accumulateTC[n];
869 cps->maxNrOfSessions = 1;
874 cps->drawDepth = appData.drawDepth[n];
875 cps->supportsNPS = UNKNOWN;
876 cps->memSize = FALSE;
877 cps->maxCores = FALSE;
878 ASSIGN(cps->egtFormats, "");
881 cps->optionSettings = appData.engOptions[n];
883 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
884 cps->isUCI = appData.isUCI[n]; /* [AS] */
885 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
888 if (appData.protocolVersion[n] > PROTOVER
889 || appData.protocolVersion[n] < 1)
894 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
895 appData.protocolVersion[n]);
896 if( (len >= MSG_SIZ) && appData.debugMode )
897 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
899 DisplayFatalError(buf, 0, 2);
903 cps->protocolVersion = appData.protocolVersion[n];
906 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
907 ParseFeatures(appData.featureDefaults, cps);
910 ChessProgramState *savCps;
918 if(WaitForEngine(savCps, LoadEngine)) return;
919 CommonEngineInit(); // recalculate time odds
920 if(gameInfo.variant != StringToVariant(appData.variant)) {
921 // we changed variant when loading the engine; this forces us to reset
922 Reset(TRUE, savCps != &first);
923 oldMode = BeginningOfGame; // to prevent restoring old mode
925 InitChessProgram(savCps, FALSE);
926 if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
927 DisplayMessage("", "");
928 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
929 for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
932 if(oldMode == AnalyzeMode) AnalyzeModeEvent();
936 ReplaceEngine (ChessProgramState *cps, int n)
938 oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
940 if(oldMode != BeginningOfGame) EditGameEvent();
943 appData.noChessProgram = FALSE;
944 appData.clockMode = TRUE;
947 if(n) return; // only startup first engine immediately; second can wait
948 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
952 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
953 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
955 static char resetOptions[] =
956 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
957 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
958 "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
959 "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
962 FloatToFront(char **list, char *engineLine)
964 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
966 if(appData.recentEngines <= 0) return;
967 TidyProgramName(engineLine, "localhost", tidy+1);
968 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
969 strncpy(buf+1, *list, MSG_SIZ-50);
970 if(p = strstr(buf, tidy)) { // tidy name appears in list
971 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
972 while(*p++ = *++q); // squeeze out
974 strcat(tidy, buf+1); // put list behind tidy name
975 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
976 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
977 ASSIGN(*list, tidy+1);
980 char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
983 Load (ChessProgramState *cps, int i)
985 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
986 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
987 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
988 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
989 ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
990 FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
991 appData.firstProtocolVersion = PROTOVER;
992 ParseArgsFromString(buf);
994 ReplaceEngine(cps, i);
995 FloatToFront(&appData.recentEngineList, engineLine);
999 while(q = strchr(p, SLASH)) p = q+1;
1000 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
1001 if(engineDir[0] != NULLCHAR) {
1002 ASSIGN(appData.directory[i], engineDir); p = engineName;
1003 } else if(p != engineName) { // derive directory from engine path, when not given
1005 ASSIGN(appData.directory[i], engineName);
1007 if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
1008 } else { ASSIGN(appData.directory[i], "."); }
1009 jar = (strstr(p, ".jar") == p + strlen(p) - 4);
1011 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
1012 snprintf(command, MSG_SIZ, "%s %s", p, params);
1015 if(jar) { snprintf(buf3, MSG_SIZ, "java -jar %s", p); p = buf3; }
1016 ASSIGN(appData.chessProgram[i], p);
1017 appData.isUCI[i] = isUCI;
1018 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
1019 appData.hasOwnBookUCI[i] = hasBook;
1020 if(!nickName[0]) useNick = FALSE;
1021 if(useNick) ASSIGN(appData.pgnName[i], nickName);
1025 q = firstChessProgramNames;
1026 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
1027 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
1028 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
1029 quote, p, quote, appData.directory[i],
1030 useNick ? " -fn \"" : "",
1031 useNick ? nickName : "",
1032 useNick ? "\"" : "",
1033 v1 ? " -firstProtocolVersion 1" : "",
1034 hasBook ? "" : " -fNoOwnBookUCI",
1035 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
1036 storeVariant ? " -variant " : "",
1037 storeVariant ? VariantName(gameInfo.variant) : "");
1038 if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
1039 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
1040 if(insert != q) insert[-1] = NULLCHAR;
1041 snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
1043 FloatToFront(&appData.recentEngineList, buf);
1045 ReplaceEngine(cps, i);
1051 int matched, min, sec;
1053 * Parse timeControl resource
1055 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
1056 appData.movesPerSession)) {
1058 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
1059 DisplayFatalError(buf, 0, 2);
1063 * Parse searchTime resource
1065 if (*appData.searchTime != NULLCHAR) {
1066 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
1068 searchTime = min * 60;
1069 } else if (matched == 2) {
1070 searchTime = min * 60 + sec;
1073 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1074 DisplayFatalError(buf, 0, 2);
1083 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1084 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1086 GetTimeMark(&programStartTime);
1087 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1088 appData.seedBase = random() + (random()<<15);
1089 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1091 ClearProgramStats();
1092 programStats.ok_to_send = 1;
1093 programStats.seen_stat = 0;
1096 * Initialize game list
1102 * Internet chess server status
1104 if (appData.icsActive) {
1105 appData.matchMode = FALSE;
1106 appData.matchGames = 0;
1108 appData.noChessProgram = !appData.zippyPlay;
1110 appData.zippyPlay = FALSE;
1111 appData.zippyTalk = FALSE;
1112 appData.noChessProgram = TRUE;
1114 if (*appData.icsHelper != NULLCHAR) {
1115 appData.useTelnet = TRUE;
1116 appData.telnetProgram = appData.icsHelper;
1119 appData.zippyTalk = appData.zippyPlay = FALSE;
1122 /* [AS] Initialize pv info list [HGM] and game state */
1126 for( i=0; i<=framePtr; i++ ) {
1127 pvInfoList[i].depth = -1;
1128 boards[i][EP_STATUS] = EP_NONE;
1129 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1135 /* [AS] Adjudication threshold */
1136 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1138 InitEngine(&first, 0);
1139 InitEngine(&second, 1);
1142 pairing.which = "pairing"; // pairing engine
1143 pairing.pr = NoProc;
1145 pairing.program = appData.pairingEngine;
1146 pairing.host = "localhost";
1149 if (appData.icsActive) {
1150 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1151 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1152 appData.clockMode = FALSE;
1153 first.sendTime = second.sendTime = 0;
1157 /* Override some settings from environment variables, for backward
1158 compatibility. Unfortunately it's not feasible to have the env
1159 vars just set defaults, at least in xboard. Ugh.
1161 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1166 if (!appData.icsActive) {
1170 /* Check for variants that are supported only in ICS mode,
1171 or not at all. Some that are accepted here nevertheless
1172 have bugs; see comments below.
1174 VariantClass variant = StringToVariant(appData.variant);
1176 case VariantBughouse: /* need four players and two boards */
1177 case VariantKriegspiel: /* need to hide pieces and move details */
1178 /* case VariantFischeRandom: (Fabien: moved below) */
1179 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1180 if( (len >= MSG_SIZ) && appData.debugMode )
1181 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1183 DisplayFatalError(buf, 0, 2);
1186 case VariantUnknown:
1187 case VariantLoadable:
1197 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1198 if( (len >= MSG_SIZ) && appData.debugMode )
1199 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1201 DisplayFatalError(buf, 0, 2);
1204 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1205 case VariantFairy: /* [HGM] TestLegality definitely off! */
1206 case VariantGothic: /* [HGM] should work */
1207 case VariantCapablanca: /* [HGM] should work */
1208 case VariantCourier: /* [HGM] initial forced moves not implemented */
1209 case VariantShogi: /* [HGM] could still mate with pawn drop */
1210 case VariantChu: /* [HGM] experimental */
1211 case VariantKnightmate: /* [HGM] should work */
1212 case VariantCylinder: /* [HGM] untested */
1213 case VariantFalcon: /* [HGM] untested */
1214 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1215 offboard interposition not understood */
1216 case VariantNormal: /* definitely works! */
1217 case VariantWildCastle: /* pieces not automatically shuffled */
1218 case VariantNoCastle: /* pieces not automatically shuffled */
1219 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1220 case VariantLosers: /* should work except for win condition,
1221 and doesn't know captures are mandatory */
1222 case VariantSuicide: /* should work except for win condition,
1223 and doesn't know captures are mandatory */
1224 case VariantGiveaway: /* should work except for win condition,
1225 and doesn't know captures are mandatory */
1226 case VariantTwoKings: /* should work */
1227 case VariantAtomic: /* should work except for win condition */
1228 case Variant3Check: /* should work except for win condition */
1229 case VariantShatranj: /* should work except for all win conditions */
1230 case VariantMakruk: /* should work except for draw countdown */
1231 case VariantASEAN : /* should work except for draw countdown */
1232 case VariantBerolina: /* might work if TestLegality is off */
1233 case VariantCapaRandom: /* should work */
1234 case VariantJanus: /* should work */
1235 case VariantSuper: /* experimental */
1236 case VariantGreat: /* experimental, requires legality testing to be off */
1237 case VariantSChess: /* S-Chess, should work */
1238 case VariantGrand: /* should work */
1239 case VariantSpartan: /* should work */
1240 case VariantLion: /* should work */
1241 case VariantChuChess: /* should work */
1249 NextIntegerFromString (char ** str, long * value)
1254 while( *s == ' ' || *s == '\t' ) {
1260 if( *s >= '0' && *s <= '9' ) {
1261 while( *s >= '0' && *s <= '9' ) {
1262 *value = *value * 10 + (*s - '0');
1275 NextTimeControlFromString (char ** str, long * value)
1278 int result = NextIntegerFromString( str, &temp );
1281 *value = temp * 60; /* Minutes */
1282 if( **str == ':' ) {
1284 result = NextIntegerFromString( str, &temp );
1285 *value += temp; /* Seconds */
1293 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1294 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1295 int result = -1, type = 0; long temp, temp2;
1297 if(**str != ':') return -1; // old params remain in force!
1299 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1300 if( NextIntegerFromString( str, &temp ) ) return -1;
1301 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1304 /* time only: incremental or sudden-death time control */
1305 if(**str == '+') { /* increment follows; read it */
1307 if(**str == '!') type = *(*str)++; // Bronstein TC
1308 if(result = NextIntegerFromString( str, &temp2)) return -1;
1309 *inc = temp2 * 1000;
1310 if(**str == '.') { // read fraction of increment
1311 char *start = ++(*str);
1312 if(result = NextIntegerFromString( str, &temp2)) return -1;
1314 while(start++ < *str) temp2 /= 10;
1318 *moves = 0; *tc = temp * 1000; *incType = type;
1322 (*str)++; /* classical time control */
1323 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1335 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1336 { /* [HGM] get time to add from the multi-session time-control string */
1337 int incType, moves=1; /* kludge to force reading of first session */
1338 long time, increment;
1341 if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1343 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1344 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1345 if(movenr == -1) return time; /* last move before new session */
1346 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1347 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1348 if(!moves) return increment; /* current session is incremental */
1349 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1350 } while(movenr >= -1); /* try again for next session */
1352 return 0; // no new time quota on this move
1356 ParseTimeControl (char *tc, float ti, int mps)
1360 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1363 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1364 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1365 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1369 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1371 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1374 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1376 snprintf(buf, MSG_SIZ, ":%s", mytc);
1378 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1380 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1385 /* Parse second time control */
1388 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1396 timeControl_2 = tc2 * 1000;
1406 timeControl = tc1 * 1000;
1409 timeIncrement = ti * 1000; /* convert to ms */
1410 movesPerSession = 0;
1413 movesPerSession = mps;
1421 if (appData.debugMode) {
1422 # ifdef __GIT_VERSION
1423 fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1425 fprintf(debugFP, "Version: %s\n", programVersion);
1428 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1430 set_cont_sequence(appData.wrapContSeq);
1431 if (appData.matchGames > 0) {
1432 appData.matchMode = TRUE;
1433 } else if (appData.matchMode) {
1434 appData.matchGames = 1;
1436 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1437 appData.matchGames = appData.sameColorGames;
1438 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1439 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1440 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1443 if (appData.noChessProgram || first.protocolVersion == 1) {
1446 /* kludge: allow timeout for initial "feature" commands */
1448 DisplayMessage("", _("Starting chess program"));
1449 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1454 CalculateIndex (int index, int gameNr)
1455 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1457 if(index > 0) return index; // fixed nmber
1458 if(index == 0) return 1;
1459 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1460 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1465 LoadGameOrPosition (int gameNr)
1466 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1467 if (*appData.loadGameFile != NULLCHAR) {
1468 if (!LoadGameFromFile(appData.loadGameFile,
1469 CalculateIndex(appData.loadGameIndex, gameNr),
1470 appData.loadGameFile, FALSE)) {
1471 DisplayFatalError(_("Bad game file"), 0, 1);
1474 } else if (*appData.loadPositionFile != NULLCHAR) {
1475 if (!LoadPositionFromFile(appData.loadPositionFile,
1476 CalculateIndex(appData.loadPositionIndex, gameNr),
1477 appData.loadPositionFile)) {
1478 DisplayFatalError(_("Bad position file"), 0, 1);
1486 ReserveGame (int gameNr, char resChar)
1488 FILE *tf = fopen(appData.tourneyFile, "r+");
1489 char *p, *q, c, buf[MSG_SIZ];
1490 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1491 safeStrCpy(buf, lastMsg, MSG_SIZ);
1492 DisplayMessage(_("Pick new game"), "");
1493 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1494 ParseArgsFromFile(tf);
1495 p = q = appData.results;
1496 if(appData.debugMode) {
1497 char *r = appData.participants;
1498 fprintf(debugFP, "results = '%s'\n", p);
1499 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1500 fprintf(debugFP, "\n");
1502 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1504 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1505 safeStrCpy(q, p, strlen(p) + 2);
1506 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1507 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1508 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1509 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1512 fseek(tf, -(strlen(p)+4), SEEK_END);
1514 if(c != '"') // depending on DOS or Unix line endings we can be one off
1515 fseek(tf, -(strlen(p)+2), SEEK_END);
1516 else fseek(tf, -(strlen(p)+3), SEEK_END);
1517 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1518 DisplayMessage(buf, "");
1519 free(p); appData.results = q;
1520 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1521 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1522 int round = appData.defaultMatchGames * appData.tourneyType;
1523 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1524 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1525 UnloadEngine(&first); // next game belongs to other pairing;
1526 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1528 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1532 MatchEvent (int mode)
1533 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1535 if(matchMode) { // already in match mode: switch it off
1537 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1540 // if(gameMode != BeginningOfGame) {
1541 // DisplayError(_("You can only start a match from the initial position."), 0);
1545 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1546 /* Set up machine vs. machine match */
1548 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1549 if(appData.tourneyFile[0]) {
1551 if(nextGame > appData.matchGames) {
1553 if(strchr(appData.results, '*') == NULL) {
1555 appData.tourneyCycles++;
1556 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1558 NextTourneyGame(-1, &dummy);
1560 if(nextGame <= appData.matchGames) {
1561 DisplayNote(_("You restarted an already completed tourney.\nOne more cycle will now be added to it.\nGames commence in 10 sec."));
1563 ScheduleDelayedEvent(NextMatchGame, 10000);
1568 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1569 DisplayError(buf, 0);
1570 appData.tourneyFile[0] = 0;
1574 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1575 DisplayFatalError(_("Can't have a match with no chess programs"),
1580 matchGame = roundNr = 1;
1581 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1585 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1588 InitBackEnd3 P((void))
1590 GameMode initialMode;
1594 if(!appData.icsActive && !appData.noChessProgram && !appData.matchMode && // mode involves only first engine
1595 !strcmp(appData.variant, "normal") && // no explicit variant request
1596 appData.NrRanks == -1 && appData.NrFiles == -1 && appData.holdingsSize == -1 && // no size overrides requested
1597 !SupportedVariant(first.variants, VariantNormal, 8, 8, 0, first.protocolVersion, "") && // but 'normal' won't work with engine
1598 !SupportedVariant(first.variants, VariantFischeRandom, 8, 8, 0, first.protocolVersion, "") ) { // nor will Chess960
1599 char c, *q = first.variants, *p = strchr(q, ',');
1600 if(p) *p = NULLCHAR;
1601 if(StringToVariant(q) != VariantUnknown) { // the engine can play a recognized variant, however
1603 if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
1604 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
1605 ASSIGN(appData.variant, q); // fake user requested the first variant played by the engine
1606 Reset(TRUE, FALSE); // and re-initialize
1611 InitChessProgram(&first, startedFromSetupPosition);
1613 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1614 free(programVersion);
1615 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1616 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1617 FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1620 if (appData.icsActive) {
1622 /* [DM] Make a console window if needed [HGM] merged ifs */
1628 if (*appData.icsCommPort != NULLCHAR)
1629 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1630 appData.icsCommPort);
1632 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1633 appData.icsHost, appData.icsPort);
1635 if( (len >= MSG_SIZ) && appData.debugMode )
1636 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1638 DisplayFatalError(buf, err, 1);
1643 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1645 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1646 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1647 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1648 } else if (appData.noChessProgram) {
1654 if (*appData.cmailGameName != NULLCHAR) {
1656 OpenLoopback(&cmailPR);
1658 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1662 DisplayMessage("", "");
1663 if (StrCaseCmp(appData.initialMode, "") == 0) {
1664 initialMode = BeginningOfGame;
1665 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1666 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1667 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1668 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1671 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1672 initialMode = TwoMachinesPlay;
1673 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1674 initialMode = AnalyzeFile;
1675 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1676 initialMode = AnalyzeMode;
1677 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1678 initialMode = MachinePlaysWhite;
1679 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1680 initialMode = MachinePlaysBlack;
1681 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1682 initialMode = EditGame;
1683 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1684 initialMode = EditPosition;
1685 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1686 initialMode = Training;
1688 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1689 if( (len >= MSG_SIZ) && appData.debugMode )
1690 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1692 DisplayFatalError(buf, 0, 2);
1696 if (appData.matchMode) {
1697 if(appData.tourneyFile[0]) { // start tourney from command line
1699 if(f = fopen(appData.tourneyFile, "r")) {
1700 ParseArgsFromFile(f); // make sure tourney parmeters re known
1702 appData.clockMode = TRUE;
1704 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1707 } else if (*appData.cmailGameName != NULLCHAR) {
1708 /* Set up cmail mode */
1709 ReloadCmailMsgEvent(TRUE);
1711 /* Set up other modes */
1712 if (initialMode == AnalyzeFile) {
1713 if (*appData.loadGameFile == NULLCHAR) {
1714 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1718 if (*appData.loadGameFile != NULLCHAR) {
1719 (void) LoadGameFromFile(appData.loadGameFile,
1720 appData.loadGameIndex,
1721 appData.loadGameFile, TRUE);
1722 } else if (*appData.loadPositionFile != NULLCHAR) {
1723 (void) LoadPositionFromFile(appData.loadPositionFile,
1724 appData.loadPositionIndex,
1725 appData.loadPositionFile);
1726 /* [HGM] try to make self-starting even after FEN load */
1727 /* to allow automatic setup of fairy variants with wtm */
1728 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1729 gameMode = BeginningOfGame;
1730 setboardSpoiledMachineBlack = 1;
1732 /* [HGM] loadPos: make that every new game uses the setup */
1733 /* from file as long as we do not switch variant */
1734 if(!blackPlaysFirst) {
1735 startedFromPositionFile = TRUE;
1736 CopyBoard(filePosition, boards[0]);
1739 if (initialMode == AnalyzeMode) {
1740 if (appData.noChessProgram) {
1741 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1744 if (appData.icsActive) {
1745 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1749 } else if (initialMode == AnalyzeFile) {
1750 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1751 ShowThinkingEvent();
1753 AnalysisPeriodicEvent(1);
1754 } else if (initialMode == MachinePlaysWhite) {
1755 if (appData.noChessProgram) {
1756 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1760 if (appData.icsActive) {
1761 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1765 MachineWhiteEvent();
1766 } else if (initialMode == MachinePlaysBlack) {
1767 if (appData.noChessProgram) {
1768 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1772 if (appData.icsActive) {
1773 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1777 MachineBlackEvent();
1778 } else if (initialMode == TwoMachinesPlay) {
1779 if (appData.noChessProgram) {
1780 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1784 if (appData.icsActive) {
1785 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1790 } else if (initialMode == EditGame) {
1792 } else if (initialMode == EditPosition) {
1793 EditPositionEvent();
1794 } else if (initialMode == Training) {
1795 if (*appData.loadGameFile == NULLCHAR) {
1796 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1805 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1807 DisplayBook(current+1);
1809 MoveHistorySet( movelist, first, last, current, pvInfoList );
1811 EvalGraphSet( first, last, current, pvInfoList );
1813 MakeEngineOutputTitle();
1817 * Establish will establish a contact to a remote host.port.
1818 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1819 * used to talk to the host.
1820 * Returns 0 if okay, error code if not.
1827 if (*appData.icsCommPort != NULLCHAR) {
1828 /* Talk to the host through a serial comm port */
1829 return OpenCommPort(appData.icsCommPort, &icsPR);
1831 } else if (*appData.gateway != NULLCHAR) {
1832 if (*appData.remoteShell == NULLCHAR) {
1833 /* Use the rcmd protocol to run telnet program on a gateway host */
1834 snprintf(buf, sizeof(buf), "%s %s %s",
1835 appData.telnetProgram, appData.icsHost, appData.icsPort);
1836 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1839 /* Use the rsh program to run telnet program on a gateway host */
1840 if (*appData.remoteUser == NULLCHAR) {
1841 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1842 appData.gateway, appData.telnetProgram,
1843 appData.icsHost, appData.icsPort);
1845 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1846 appData.remoteShell, appData.gateway,
1847 appData.remoteUser, appData.telnetProgram,
1848 appData.icsHost, appData.icsPort);
1850 return StartChildProcess(buf, "", &icsPR);
1853 } else if (appData.useTelnet) {
1854 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1857 /* TCP socket interface differs somewhat between
1858 Unix and NT; handle details in the front end.
1860 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1865 EscapeExpand (char *p, char *q)
1866 { // [HGM] initstring: routine to shape up string arguments
1867 while(*p++ = *q++) if(p[-1] == '\\')
1869 case 'n': p[-1] = '\n'; break;
1870 case 'r': p[-1] = '\r'; break;
1871 case 't': p[-1] = '\t'; break;
1872 case '\\': p[-1] = '\\'; break;
1873 case 0: *p = 0; return;
1874 default: p[-1] = q[-1]; break;
1879 show_bytes (FILE *fp, char *buf, int count)
1882 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1883 fprintf(fp, "\\%03o", *buf & 0xff);
1892 /* Returns an errno value */
1894 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1896 char buf[8192], *p, *q, *buflim;
1897 int left, newcount, outcount;
1899 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1900 *appData.gateway != NULLCHAR) {
1901 if (appData.debugMode) {
1902 fprintf(debugFP, ">ICS: ");
1903 show_bytes(debugFP, message, count);
1904 fprintf(debugFP, "\n");
1906 return OutputToProcess(pr, message, count, outError);
1909 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1916 if (appData.debugMode) {
1917 fprintf(debugFP, ">ICS: ");
1918 show_bytes(debugFP, buf, newcount);
1919 fprintf(debugFP, "\n");
1921 outcount = OutputToProcess(pr, buf, newcount, outError);
1922 if (outcount < newcount) return -1; /* to be sure */
1929 } else if (((unsigned char) *p) == TN_IAC) {
1930 *q++ = (char) TN_IAC;
1937 if (appData.debugMode) {
1938 fprintf(debugFP, ">ICS: ");
1939 show_bytes(debugFP, buf, newcount);
1940 fprintf(debugFP, "\n");
1942 outcount = OutputToProcess(pr, buf, newcount, outError);
1943 if (outcount < newcount) return -1; /* to be sure */
1948 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1950 int outError, outCount;
1951 static int gotEof = 0;
1954 /* Pass data read from player on to ICS */
1957 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1958 if (outCount < count) {
1959 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1961 if(have_sent_ICS_logon == 2) {
1962 if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1963 fprintf(ini, "%s", message);
1964 have_sent_ICS_logon = 3;
1966 have_sent_ICS_logon = 1;
1967 } else if(have_sent_ICS_logon == 3) {
1968 fprintf(ini, "%s", message);
1970 have_sent_ICS_logon = 1;
1972 } else if (count < 0) {
1973 RemoveInputSource(isr);
1974 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1975 } else if (gotEof++ > 0) {
1976 RemoveInputSource(isr);
1977 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1983 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1984 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1985 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1986 SendToICS("date\n");
1987 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1990 /* added routine for printf style output to ics */
1992 ics_printf (char *format, ...)
1994 char buffer[MSG_SIZ];
1997 va_start(args, format);
1998 vsnprintf(buffer, sizeof(buffer), format, args);
1999 buffer[sizeof(buffer)-1] = '\0';
2007 int count, outCount, outError;
2009 if (icsPR == NoProc) return;
2012 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
2013 if (outCount < count) {
2014 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2018 /* This is used for sending logon scripts to the ICS. Sending
2019 without a delay causes problems when using timestamp on ICC
2020 (at least on my machine). */
2022 SendToICSDelayed (char *s, long msdelay)
2024 int count, outCount, outError;
2026 if (icsPR == NoProc) return;
2029 if (appData.debugMode) {
2030 fprintf(debugFP, ">ICS: ");
2031 show_bytes(debugFP, s, count);
2032 fprintf(debugFP, "\n");
2034 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
2036 if (outCount < count) {
2037 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2042 /* Remove all highlighting escape sequences in s
2043 Also deletes any suffix starting with '('
2046 StripHighlightAndTitle (char *s)
2048 static char retbuf[MSG_SIZ];
2051 while (*s != NULLCHAR) {
2052 while (*s == '\033') {
2053 while (*s != NULLCHAR && !isalpha(*s)) s++;
2054 if (*s != NULLCHAR) s++;
2056 while (*s != NULLCHAR && *s != '\033') {
2057 if (*s == '(' || *s == '[') {
2068 /* Remove all highlighting escape sequences in s */
2070 StripHighlight (char *s)
2072 static char retbuf[MSG_SIZ];
2075 while (*s != NULLCHAR) {
2076 while (*s == '\033') {
2077 while (*s != NULLCHAR && !isalpha(*s)) s++;
2078 if (*s != NULLCHAR) s++;
2080 while (*s != NULLCHAR && *s != '\033') {
2088 char engineVariant[MSG_SIZ];
2089 char *variantNames[] = VARIANT_NAMES;
2091 VariantName (VariantClass v)
2093 if(v == VariantUnknown || *engineVariant) return engineVariant;
2094 return variantNames[v];
2098 /* Identify a variant from the strings the chess servers use or the
2099 PGN Variant tag names we use. */
2101 StringToVariant (char *e)
2105 VariantClass v = VariantNormal;
2106 int i, found = FALSE;
2112 /* [HGM] skip over optional board-size prefixes */
2113 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
2114 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
2115 while( *e++ != '_');
2118 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2122 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2123 if (p = StrCaseStr(e, variantNames[i])) {
2124 if(p && i >= VariantShogi && isalpha(p[strlen(variantNames[i])])) continue;
2125 v = (VariantClass) i;
2132 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2133 || StrCaseStr(e, "wild/fr")
2134 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2135 v = VariantFischeRandom;
2136 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2137 (i = 1, p = StrCaseStr(e, "w"))) {
2139 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2146 case 0: /* FICS only, actually */
2148 /* Castling legal even if K starts on d-file */
2149 v = VariantWildCastle;
2154 /* Castling illegal even if K & R happen to start in
2155 normal positions. */
2156 v = VariantNoCastle;
2169 /* Castling legal iff K & R start in normal positions */
2175 /* Special wilds for position setup; unclear what to do here */
2176 v = VariantLoadable;
2179 /* Bizarre ICC game */
2180 v = VariantTwoKings;
2183 v = VariantKriegspiel;
2189 v = VariantFischeRandom;
2192 v = VariantCrazyhouse;
2195 v = VariantBughouse;
2201 /* Not quite the same as FICS suicide! */
2202 v = VariantGiveaway;
2208 v = VariantShatranj;
2211 /* Temporary names for future ICC types. The name *will* change in
2212 the next xboard/WinBoard release after ICC defines it. */
2250 v = VariantCapablanca;
2253 v = VariantKnightmate;
2259 v = VariantCylinder;
2265 v = VariantCapaRandom;
2268 v = VariantBerolina;
2280 /* Found "wild" or "w" in the string but no number;
2281 must assume it's normal chess. */
2285 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2286 if( (len >= MSG_SIZ) && appData.debugMode )
2287 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2289 DisplayError(buf, 0);
2295 if (appData.debugMode) {
2296 fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2297 e, wnum, VariantName(v));
2302 static int leftover_start = 0, leftover_len = 0;
2303 char star_match[STAR_MATCH_N][MSG_SIZ];
2305 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2306 advance *index beyond it, and set leftover_start to the new value of
2307 *index; else return FALSE. If pattern contains the character '*', it
2308 matches any sequence of characters not containing '\r', '\n', or the
2309 character following the '*' (if any), and the matched sequence(s) are
2310 copied into star_match.
2313 looking_at ( char *buf, int *index, char *pattern)
2315 char *bufp = &buf[*index], *patternp = pattern;
2317 char *matchp = star_match[0];
2320 if (*patternp == NULLCHAR) {
2321 *index = leftover_start = bufp - buf;
2325 if (*bufp == NULLCHAR) return FALSE;
2326 if (*patternp == '*') {
2327 if (*bufp == *(patternp + 1)) {
2329 matchp = star_match[++star_count];
2333 } else if (*bufp == '\n' || *bufp == '\r') {
2335 if (*patternp == NULLCHAR)
2340 *matchp++ = *bufp++;
2344 if (*patternp != *bufp) return FALSE;
2351 SendToPlayer (char *data, int length)
2353 int error, outCount;
2354 outCount = OutputToProcess(NoProc, data, length, &error);
2355 if (outCount < length) {
2356 DisplayFatalError(_("Error writing to display"), error, 1);
2361 PackHolding (char packed[], char *holding)
2371 switch (runlength) {
2382 sprintf(q, "%d", runlength);
2394 /* Telnet protocol requests from the front end */
2396 TelnetRequest (unsigned char ddww, unsigned char option)
2398 unsigned char msg[3];
2399 int outCount, outError;
2401 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2403 if (appData.debugMode) {
2404 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2420 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2429 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2432 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2437 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2439 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2446 if (!appData.icsActive) return;
2447 TelnetRequest(TN_DO, TN_ECHO);
2453 if (!appData.icsActive) return;
2454 TelnetRequest(TN_DONT, TN_ECHO);
2458 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2460 /* put the holdings sent to us by the server on the board holdings area */
2461 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2465 if(gameInfo.holdingsWidth < 2) return;
2466 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2467 return; // prevent overwriting by pre-board holdings
2469 if( (int)lowestPiece >= BlackPawn ) {
2472 holdingsStartRow = BOARD_HEIGHT-1;
2475 holdingsColumn = BOARD_WIDTH-1;
2476 countsColumn = BOARD_WIDTH-2;
2477 holdingsStartRow = 0;
2481 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2482 board[i][holdingsColumn] = EmptySquare;
2483 board[i][countsColumn] = (ChessSquare) 0;
2485 while( (p=*holdings++) != NULLCHAR ) {
2486 piece = CharToPiece( ToUpper(p) );
2487 if(piece == EmptySquare) continue;
2488 /*j = (int) piece - (int) WhitePawn;*/
2489 j = PieceToNumber(piece);
2490 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2491 if(j < 0) continue; /* should not happen */
2492 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2493 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2494 board[holdingsStartRow+j*direction][countsColumn]++;
2500 VariantSwitch (Board board, VariantClass newVariant)
2502 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2503 static Board oldBoard;
2505 startedFromPositionFile = FALSE;
2506 if(gameInfo.variant == newVariant) return;
2508 /* [HGM] This routine is called each time an assignment is made to
2509 * gameInfo.variant during a game, to make sure the board sizes
2510 * are set to match the new variant. If that means adding or deleting
2511 * holdings, we shift the playing board accordingly
2512 * This kludge is needed because in ICS observe mode, we get boards
2513 * of an ongoing game without knowing the variant, and learn about the
2514 * latter only later. This can be because of the move list we requested,
2515 * in which case the game history is refilled from the beginning anyway,
2516 * but also when receiving holdings of a crazyhouse game. In the latter
2517 * case we want to add those holdings to the already received position.
2521 if (appData.debugMode) {
2522 fprintf(debugFP, "Switch board from %s to %s\n",
2523 VariantName(gameInfo.variant), VariantName(newVariant));
2524 setbuf(debugFP, NULL);
2526 shuffleOpenings = 0; /* [HGM] shuffle */
2527 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2531 newWidth = 9; newHeight = 9;
2532 gameInfo.holdingsSize = 7;
2533 case VariantBughouse:
2534 case VariantCrazyhouse:
2535 newHoldingsWidth = 2; break;
2539 newHoldingsWidth = 2;
2540 gameInfo.holdingsSize = 8;
2543 case VariantCapablanca:
2544 case VariantCapaRandom:
2547 newHoldingsWidth = gameInfo.holdingsSize = 0;
2550 if(newWidth != gameInfo.boardWidth ||
2551 newHeight != gameInfo.boardHeight ||
2552 newHoldingsWidth != gameInfo.holdingsWidth ) {
2554 /* shift position to new playing area, if needed */
2555 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2556 for(i=0; i<BOARD_HEIGHT; i++)
2557 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2558 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2560 for(i=0; i<newHeight; i++) {
2561 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2562 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2564 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2565 for(i=0; i<BOARD_HEIGHT; i++)
2566 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2567 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2570 board[HOLDINGS_SET] = 0;
2571 gameInfo.boardWidth = newWidth;
2572 gameInfo.boardHeight = newHeight;
2573 gameInfo.holdingsWidth = newHoldingsWidth;
2574 gameInfo.variant = newVariant;
2575 InitDrawingSizes(-2, 0);
2576 } else gameInfo.variant = newVariant;
2577 CopyBoard(oldBoard, board); // remember correctly formatted board
2578 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2579 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2582 static int loggedOn = FALSE;
2584 /*-- Game start info cache: --*/
2586 char gs_kind[MSG_SIZ];
2587 static char player1Name[128] = "";
2588 static char player2Name[128] = "";
2589 static char cont_seq[] = "\n\\ ";
2590 static int player1Rating = -1;
2591 static int player2Rating = -1;
2592 /*----------------------------*/
2594 ColorClass curColor = ColorNormal;
2595 int suppressKibitz = 0;
2598 Boolean soughtPending = FALSE;
2599 Boolean seekGraphUp;
2600 #define MAX_SEEK_ADS 200
2602 char *seekAdList[MAX_SEEK_ADS];
2603 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2604 float tcList[MAX_SEEK_ADS];
2605 char colorList[MAX_SEEK_ADS];
2606 int nrOfSeekAds = 0;
2607 int minRating = 1010, maxRating = 2800;
2608 int hMargin = 10, vMargin = 20, h, w;
2609 extern int squareSize, lineGap;
2614 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2615 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2616 if(r < minRating+100 && r >=0 ) r = minRating+100;
2617 if(r > maxRating) r = maxRating;
2618 if(tc < 1.f) tc = 1.f;
2619 if(tc > 95.f) tc = 95.f;
2620 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2621 y = ((double)r - minRating)/(maxRating - minRating)
2622 * (h-vMargin-squareSize/8-1) + vMargin;
2623 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2624 if(strstr(seekAdList[i], " u ")) color = 1;
2625 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2626 !strstr(seekAdList[i], "bullet") &&
2627 !strstr(seekAdList[i], "blitz") &&
2628 !strstr(seekAdList[i], "standard") ) color = 2;
2629 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2630 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2634 PlotSingleSeekAd (int i)
2640 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2642 char buf[MSG_SIZ], *ext = "";
2643 VariantClass v = StringToVariant(type);
2644 if(strstr(type, "wild")) {
2645 ext = type + 4; // append wild number
2646 if(v == VariantFischeRandom) type = "chess960"; else
2647 if(v == VariantLoadable) type = "setup"; else
2648 type = VariantName(v);
2650 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2651 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2652 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2653 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2654 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2655 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2656 seekNrList[nrOfSeekAds] = nr;
2657 zList[nrOfSeekAds] = 0;
2658 seekAdList[nrOfSeekAds++] = StrSave(buf);
2659 if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2664 EraseSeekDot (int i)
2666 int x = xList[i], y = yList[i], d=squareSize/4, k;
2667 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2668 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2669 // now replot every dot that overlapped
2670 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2671 int xx = xList[k], yy = yList[k];
2672 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2673 DrawSeekDot(xx, yy, colorList[k]);
2678 RemoveSeekAd (int nr)
2681 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2683 if(seekAdList[i]) free(seekAdList[i]);
2684 seekAdList[i] = seekAdList[--nrOfSeekAds];
2685 seekNrList[i] = seekNrList[nrOfSeekAds];
2686 ratingList[i] = ratingList[nrOfSeekAds];
2687 colorList[i] = colorList[nrOfSeekAds];
2688 tcList[i] = tcList[nrOfSeekAds];
2689 xList[i] = xList[nrOfSeekAds];
2690 yList[i] = yList[nrOfSeekAds];
2691 zList[i] = zList[nrOfSeekAds];
2692 seekAdList[nrOfSeekAds] = NULL;
2698 MatchSoughtLine (char *line)
2700 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2701 int nr, base, inc, u=0; char dummy;
2703 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2704 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2706 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2707 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2708 // match: compact and save the line
2709 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2719 if(!seekGraphUp) return FALSE;
2720 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2721 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2723 DrawSeekBackground(0, 0, w, h);
2724 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2725 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2726 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2727 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2729 DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2732 snprintf(buf, MSG_SIZ, "%d", i);
2733 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2736 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2737 for(i=1; i<100; i+=(i<10?1:5)) {
2738 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2739 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2740 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2742 snprintf(buf, MSG_SIZ, "%d", i);
2743 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2746 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2751 SeekGraphClick (ClickType click, int x, int y, int moving)
2753 static int lastDown = 0, displayed = 0, lastSecond;
2754 if(y < 0) return FALSE;
2755 if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2756 (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2757 if(!seekGraphUp) return FALSE;
2758 seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2759 DrawPosition(TRUE, NULL);
2762 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2763 if(click == Release || moving) return FALSE;
2765 soughtPending = TRUE;
2766 SendToICS(ics_prefix);
2767 SendToICS("sought\n"); // should this be "sought all"?
2768 } else { // issue challenge based on clicked ad
2769 int dist = 10000; int i, closest = 0, second = 0;
2770 for(i=0; i<nrOfSeekAds; i++) {
2771 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2772 if(d < dist) { dist = d; closest = i; }
2773 second += (d - zList[i] < 120); // count in-range ads
2774 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2778 second = (second > 1);
2779 if(displayed != closest || second != lastSecond) {
2780 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2781 lastSecond = second; displayed = closest;
2783 if(click == Press) {
2784 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2787 } // on press 'hit', only show info
2788 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2789 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2790 SendToICS(ics_prefix);
2792 return TRUE; // let incoming board of started game pop down the graph
2793 } else if(click == Release) { // release 'miss' is ignored
2794 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2795 if(moving == 2) { // right up-click
2796 nrOfSeekAds = 0; // refresh graph
2797 soughtPending = TRUE;
2798 SendToICS(ics_prefix);
2799 SendToICS("sought\n"); // should this be "sought all"?
2802 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2803 // press miss or release hit 'pop down' seek graph
2804 seekGraphUp = FALSE;
2805 DrawPosition(TRUE, NULL);
2811 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2813 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2814 #define STARTED_NONE 0
2815 #define STARTED_MOVES 1
2816 #define STARTED_BOARD 2
2817 #define STARTED_OBSERVE 3
2818 #define STARTED_HOLDINGS 4
2819 #define STARTED_CHATTER 5
2820 #define STARTED_COMMENT 6
2821 #define STARTED_MOVES_NOHIDE 7
2823 static int started = STARTED_NONE;
2824 static char parse[20000];
2825 static int parse_pos = 0;
2826 static char buf[BUF_SIZE + 1];
2827 static int firstTime = TRUE, intfSet = FALSE;
2828 static ColorClass prevColor = ColorNormal;
2829 static int savingComment = FALSE;
2830 static int cmatch = 0; // continuation sequence match
2837 int backup; /* [DM] For zippy color lines */
2839 char talker[MSG_SIZ]; // [HGM] chat
2840 int channel, collective=0;
2842 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2844 if (appData.debugMode) {
2846 fprintf(debugFP, "<ICS: ");
2847 show_bytes(debugFP, data, count);
2848 fprintf(debugFP, "\n");
2852 if (appData.debugMode) { int f = forwardMostMove;
2853 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2854 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2855 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2858 /* If last read ended with a partial line that we couldn't parse,
2859 prepend it to the new read and try again. */
2860 if (leftover_len > 0) {
2861 for (i=0; i<leftover_len; i++)
2862 buf[i] = buf[leftover_start + i];
2865 /* copy new characters into the buffer */
2866 bp = buf + leftover_len;
2867 buf_len=leftover_len;
2868 for (i=0; i<count; i++)
2871 if (data[i] == '\r')
2874 // join lines split by ICS?
2875 if (!appData.noJoin)
2878 Joining just consists of finding matches against the
2879 continuation sequence, and discarding that sequence
2880 if found instead of copying it. So, until a match
2881 fails, there's nothing to do since it might be the
2882 complete sequence, and thus, something we don't want
2885 if (data[i] == cont_seq[cmatch])
2888 if (cmatch == strlen(cont_seq))
2890 cmatch = 0; // complete match. just reset the counter
2893 it's possible for the ICS to not include the space
2894 at the end of the last word, making our [correct]
2895 join operation fuse two separate words. the server
2896 does this when the space occurs at the width setting.
2898 if (!buf_len || buf[buf_len-1] != ' ')
2909 match failed, so we have to copy what matched before
2910 falling through and copying this character. In reality,
2911 this will only ever be just the newline character, but
2912 it doesn't hurt to be precise.
2914 strncpy(bp, cont_seq, cmatch);
2926 buf[buf_len] = NULLCHAR;
2927 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2932 while (i < buf_len) {
2933 /* Deal with part of the TELNET option negotiation
2934 protocol. We refuse to do anything beyond the
2935 defaults, except that we allow the WILL ECHO option,
2936 which ICS uses to turn off password echoing when we are
2937 directly connected to it. We reject this option
2938 if localLineEditing mode is on (always on in xboard)
2939 and we are talking to port 23, which might be a real
2940 telnet server that will try to keep WILL ECHO on permanently.
2942 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2943 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2944 unsigned char option;
2946 switch ((unsigned char) buf[++i]) {
2948 if (appData.debugMode)
2949 fprintf(debugFP, "\n<WILL ");
2950 switch (option = (unsigned char) buf[++i]) {
2952 if (appData.debugMode)
2953 fprintf(debugFP, "ECHO ");
2954 /* Reply only if this is a change, according
2955 to the protocol rules. */
2956 if (remoteEchoOption) break;
2957 if (appData.localLineEditing &&
2958 atoi(appData.icsPort) == TN_PORT) {
2959 TelnetRequest(TN_DONT, TN_ECHO);
2962 TelnetRequest(TN_DO, TN_ECHO);
2963 remoteEchoOption = TRUE;
2967 if (appData.debugMode)
2968 fprintf(debugFP, "%d ", option);
2969 /* Whatever this is, we don't want it. */
2970 TelnetRequest(TN_DONT, option);
2975 if (appData.debugMode)
2976 fprintf(debugFP, "\n<WONT ");
2977 switch (option = (unsigned char) buf[++i]) {
2979 if (appData.debugMode)
2980 fprintf(debugFP, "ECHO ");
2981 /* Reply only if this is a change, according
2982 to the protocol rules. */
2983 if (!remoteEchoOption) break;
2985 TelnetRequest(TN_DONT, TN_ECHO);
2986 remoteEchoOption = FALSE;
2989 if (appData.debugMode)
2990 fprintf(debugFP, "%d ", (unsigned char) option);
2991 /* Whatever this is, it must already be turned
2992 off, because we never agree to turn on
2993 anything non-default, so according to the
2994 protocol rules, we don't reply. */
2999 if (appData.debugMode)
3000 fprintf(debugFP, "\n<DO ");
3001 switch (option = (unsigned char) buf[++i]) {
3003 /* Whatever this is, we refuse to do it. */
3004 if (appData.debugMode)
3005 fprintf(debugFP, "%d ", option);
3006 TelnetRequest(TN_WONT, option);
3011 if (appData.debugMode)
3012 fprintf(debugFP, "\n<DONT ");
3013 switch (option = (unsigned char) buf[++i]) {
3015 if (appData.debugMode)
3016 fprintf(debugFP, "%d ", option);
3017 /* Whatever this is, we are already not doing
3018 it, because we never agree to do anything
3019 non-default, so according to the protocol
3020 rules, we don't reply. */
3025 if (appData.debugMode)
3026 fprintf(debugFP, "\n<IAC ");
3027 /* Doubled IAC; pass it through */
3031 if (appData.debugMode)
3032 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
3033 /* Drop all other telnet commands on the floor */
3036 if (oldi > next_out)
3037 SendToPlayer(&buf[next_out], oldi - next_out);
3043 /* OK, this at least will *usually* work */
3044 if (!loggedOn && looking_at(buf, &i, "ics%")) {
3048 if (loggedOn && !intfSet) {
3049 if (ics_type == ICS_ICC) {
3050 snprintf(str, MSG_SIZ,
3051 "/set-quietly interface %s\n/set-quietly style 12\n",
3053 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3054 strcat(str, "/set-2 51 1\n/set seek 1\n");
3055 } else if (ics_type == ICS_CHESSNET) {
3056 snprintf(str, MSG_SIZ, "/style 12\n");
3058 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
3059 strcat(str, programVersion);
3060 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
3061 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3062 strcat(str, "$iset seekremove 1\n$set seek 1\n");
3064 strcat(str, "$iset nohighlight 1\n");
3066 strcat(str, "$iset lock 1\n$style 12\n");
3069 NotifyFrontendLogin();
3073 if (started == STARTED_COMMENT) {
3074 /* Accumulate characters in comment */
3075 parse[parse_pos++] = buf[i];
3076 if (buf[i] == '\n') {
3077 parse[parse_pos] = NULLCHAR;
3078 if(chattingPartner>=0) {
3080 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
3081 OutputChatMessage(chattingPartner, mess);
3082 if(collective == 1) { // broadcasted talk also goes to private chatbox of talker
3084 talker[strlen(talker+1)-1] = NULLCHAR; // strip closing delimiter
3085 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3086 snprintf(mess, MSG_SIZ, "%s: %s", chatPartner[chattingPartner], parse);
3087 OutputChatMessage(p, mess);
3091 chattingPartner = -1;
3092 if(collective != 3) next_out = i+1; // [HGM] suppress printing in ICS window
3095 if(!suppressKibitz) // [HGM] kibitz
3096 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
3097 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
3098 int nrDigit = 0, nrAlph = 0, j;
3099 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
3100 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
3101 parse[parse_pos] = NULLCHAR;
3102 // try to be smart: if it does not look like search info, it should go to
3103 // ICS interaction window after all, not to engine-output window.
3104 for(j=0; j<parse_pos; j++) { // count letters and digits
3105 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3106 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
3107 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
3109 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3110 int depth=0; float score;
3111 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3112 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3113 pvInfoList[forwardMostMove-1].depth = depth;
3114 pvInfoList[forwardMostMove-1].score = 100*score;
3116 OutputKibitz(suppressKibitz, parse);
3119 if(gameMode == IcsObserving) // restore original ICS messages
3120 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3121 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3123 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3124 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3125 SendToPlayer(tmp, strlen(tmp));
3127 next_out = i+1; // [HGM] suppress printing in ICS window
3129 started = STARTED_NONE;
3131 /* Don't match patterns against characters in comment */
3136 if (started == STARTED_CHATTER) {
3137 if (buf[i] != '\n') {
3138 /* Don't match patterns against characters in chatter */
3142 started = STARTED_NONE;
3143 if(suppressKibitz) next_out = i+1;
3146 /* Kludge to deal with rcmd protocol */
3147 if (firstTime && looking_at(buf, &i, "\001*")) {
3148 DisplayFatalError(&buf[1], 0, 1);
3154 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3157 if (appData.debugMode)
3158 fprintf(debugFP, "ics_type %d\n", ics_type);
3161 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3162 ics_type = ICS_FICS;
3164 if (appData.debugMode)
3165 fprintf(debugFP, "ics_type %d\n", ics_type);
3168 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3169 ics_type = ICS_CHESSNET;
3171 if (appData.debugMode)
3172 fprintf(debugFP, "ics_type %d\n", ics_type);
3177 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3178 looking_at(buf, &i, "Logging you in as \"*\"") ||
3179 looking_at(buf, &i, "will be \"*\""))) {
3180 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3184 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3186 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3187 DisplayIcsInteractionTitle(buf);
3188 have_set_title = TRUE;
3191 /* skip finger notes */
3192 if (started == STARTED_NONE &&
3193 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3194 (buf[i] == '1' && buf[i+1] == '0')) &&
3195 buf[i+2] == ':' && buf[i+3] == ' ') {
3196 started = STARTED_CHATTER;
3202 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3203 if(appData.seekGraph) {
3204 if(soughtPending && MatchSoughtLine(buf+i)) {
3205 i = strstr(buf+i, "rated") - buf;
3206 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3207 next_out = leftover_start = i;
3208 started = STARTED_CHATTER;
3209 suppressKibitz = TRUE;
3212 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3213 && looking_at(buf, &i, "* ads displayed")) {
3214 soughtPending = FALSE;
3219 if(appData.autoRefresh) {
3220 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3221 int s = (ics_type == ICS_ICC); // ICC format differs
3223 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3224 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3225 looking_at(buf, &i, "*% "); // eat prompt
3226 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3227 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3228 next_out = i; // suppress
3231 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3232 char *p = star_match[0];
3234 if(seekGraphUp) RemoveSeekAd(atoi(p));
3235 while(*p && *p++ != ' '); // next
3237 looking_at(buf, &i, "*% "); // eat prompt
3238 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3245 /* skip formula vars */
3246 if (started == STARTED_NONE &&
3247 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3248 started = STARTED_CHATTER;
3253 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3254 if (appData.autoKibitz && started == STARTED_NONE &&
3255 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3256 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3257 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3258 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3259 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3260 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3261 suppressKibitz = TRUE;
3262 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3264 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3265 && (gameMode == IcsPlayingWhite)) ||
3266 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3267 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3268 started = STARTED_CHATTER; // own kibitz we simply discard
3270 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3271 parse_pos = 0; parse[0] = NULLCHAR;
3272 savingComment = TRUE;
3273 suppressKibitz = gameMode != IcsObserving ? 2 :
3274 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3278 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3279 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3280 && atoi(star_match[0])) {
3281 // suppress the acknowledgements of our own autoKibitz
3283 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3284 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3285 SendToPlayer(star_match[0], strlen(star_match[0]));
3286 if(looking_at(buf, &i, "*% ")) // eat prompt
3287 suppressKibitz = FALSE;
3291 } // [HGM] kibitz: end of patch
3293 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3295 // [HGM] chat: intercept tells by users for which we have an open chat window
3297 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3298 looking_at(buf, &i, "* whispers:") ||
3299 looking_at(buf, &i, "* kibitzes:") ||
3300 looking_at(buf, &i, "* shouts:") ||
3301 looking_at(buf, &i, "* c-shouts:") ||
3302 looking_at(buf, &i, "--> * ") ||
3303 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3304 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3305 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3306 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3308 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3309 chattingPartner = -1; collective = 0;
3311 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3312 for(p=0; p<MAX_CHAT; p++) {
3314 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3315 talker[0] = '['; strcat(talker, "] ");
3316 Colorize((channel == 1 ? ColorChannel1 : ColorChannel), FALSE);
3317 chattingPartner = p; break;
3320 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3321 for(p=0; p<MAX_CHAT; p++) {
3323 if(!strcmp("kibitzes", chatPartner[p])) {
3324 talker[0] = '['; strcat(talker, "] ");
3325 chattingPartner = p; break;
3328 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3329 for(p=0; p<MAX_CHAT; p++) {
3331 if(!strcmp("whispers", chatPartner[p])) {
3332 talker[0] = '['; strcat(talker, "] ");
3333 chattingPartner = p; break;
3336 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3337 if(buf[i-8] == '-' && buf[i-3] == 't')
3338 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3340 if(!strcmp("c-shouts", chatPartner[p])) {
3341 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3342 chattingPartner = p; break;
3345 if(chattingPartner < 0)
3346 for(p=0; p<MAX_CHAT; p++) {
3348 if(!strcmp("shouts", chatPartner[p])) {
3349 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3350 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3351 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3352 chattingPartner = p; break;
3356 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3357 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3359 Colorize(ColorTell, FALSE);
3360 if(collective) safeStrCpy(talker, "broadcasts: ", MSG_SIZ);
3362 chattingPartner = p; break;
3364 if(chattingPartner<0) i = oldi, safeStrCpy(lastTalker, talker+1, MSG_SIZ); else {
3365 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3366 started = STARTED_COMMENT;
3367 parse_pos = 0; parse[0] = NULLCHAR;
3368 savingComment = 3 + chattingPartner; // counts as TRUE
3369 if(collective == 3) i = oldi; else {
3370 suppressKibitz = TRUE;
3371 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3372 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3376 } // [HGM] chat: end of patch
3379 if (appData.zippyTalk || appData.zippyPlay) {
3380 /* [DM] Backup address for color zippy lines */
3382 if (loggedOn == TRUE)
3383 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3384 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3386 } // [DM] 'else { ' deleted
3388 /* Regular tells and says */
3389 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3390 looking_at(buf, &i, "* (your partner) tells you: ") ||
3391 looking_at(buf, &i, "* says: ") ||
3392 /* Don't color "message" or "messages" output */
3393 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3394 looking_at(buf, &i, "*. * at *:*: ") ||
3395 looking_at(buf, &i, "--* (*:*): ") ||
3396 /* Message notifications (same color as tells) */
3397 looking_at(buf, &i, "* has left a message ") ||
3398 looking_at(buf, &i, "* just sent you a message:\n") ||
3399 /* Whispers and kibitzes */
3400 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3401 looking_at(buf, &i, "* kibitzes: ") ||
3403 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3405 if (tkind == 1 && strchr(star_match[0], ':')) {
3406 /* Avoid "tells you:" spoofs in channels */
3409 if (star_match[0][0] == NULLCHAR ||
3410 strchr(star_match[0], ' ') ||
3411 (tkind == 3 && strchr(star_match[1], ' '))) {
3412 /* Reject bogus matches */
3415 if (appData.colorize) {
3416 if (oldi > next_out) {
3417 SendToPlayer(&buf[next_out], oldi - next_out);
3422 Colorize(ColorTell, FALSE);
3423 curColor = ColorTell;
3426 Colorize(ColorKibitz, FALSE);
3427 curColor = ColorKibitz;
3430 p = strrchr(star_match[1], '(');
3437 Colorize(ColorChannel1, FALSE);
3438 curColor = ColorChannel1;
3440 Colorize(ColorChannel, FALSE);
3441 curColor = ColorChannel;
3445 curColor = ColorNormal;
3449 if (started == STARTED_NONE && appData.autoComment &&
3450 (gameMode == IcsObserving ||
3451 gameMode == IcsPlayingWhite ||
3452 gameMode == IcsPlayingBlack)) {
3453 parse_pos = i - oldi;
3454 memcpy(parse, &buf[oldi], parse_pos);
3455 parse[parse_pos] = NULLCHAR;
3456 started = STARTED_COMMENT;
3457 savingComment = TRUE;
3458 } else if(collective != 3) {
3459 started = STARTED_CHATTER;
3460 savingComment = FALSE;
3467 if (looking_at(buf, &i, "* s-shouts: ") ||
3468 looking_at(buf, &i, "* c-shouts: ")) {
3469 if (appData.colorize) {
3470 if (oldi > next_out) {
3471 SendToPlayer(&buf[next_out], oldi - next_out);
3474 Colorize(ColorSShout, FALSE);
3475 curColor = ColorSShout;
3478 started = STARTED_CHATTER;
3482 if (looking_at(buf, &i, "--->")) {
3487 if (looking_at(buf, &i, "* shouts: ") ||
3488 looking_at(buf, &i, "--> ")) {
3489 if (appData.colorize) {
3490 if (oldi > next_out) {
3491 SendToPlayer(&buf[next_out], oldi - next_out);
3494 Colorize(ColorShout, FALSE);
3495 curColor = ColorShout;
3498 started = STARTED_CHATTER;
3502 if (looking_at( buf, &i, "Challenge:")) {
3503 if (appData.colorize) {
3504 if (oldi > next_out) {
3505 SendToPlayer(&buf[next_out], oldi - next_out);
3508 Colorize(ColorChallenge, FALSE);
3509 curColor = ColorChallenge;
3515 if (looking_at(buf, &i, "* offers you") ||
3516 looking_at(buf, &i, "* offers to be") ||
3517 looking_at(buf, &i, "* would like to") ||
3518 looking_at(buf, &i, "* requests to") ||
3519 looking_at(buf, &i, "Your opponent offers") ||
3520 looking_at(buf, &i, "Your opponent requests")) {
3522 if (appData.colorize) {
3523 if (oldi > next_out) {
3524 SendToPlayer(&buf[next_out], oldi - next_out);
3527 Colorize(ColorRequest, FALSE);
3528 curColor = ColorRequest;
3533 if (looking_at(buf, &i, "* (*) seeking")) {
3534 if (appData.colorize) {
3535 if (oldi > next_out) {
3536 SendToPlayer(&buf[next_out], oldi - next_out);
3539 Colorize(ColorSeek, FALSE);
3540 curColor = ColorSeek;
3545 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3547 if (looking_at(buf, &i, "\\ ")) {
3548 if (prevColor != ColorNormal) {
3549 if (oldi > next_out) {
3550 SendToPlayer(&buf[next_out], oldi - next_out);
3553 Colorize(prevColor, TRUE);
3554 curColor = prevColor;
3556 if (savingComment) {
3557 parse_pos = i - oldi;
3558 memcpy(parse, &buf[oldi], parse_pos);
3559 parse[parse_pos] = NULLCHAR;
3560 started = STARTED_COMMENT;
3561 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3562 chattingPartner = savingComment - 3; // kludge to remember the box
3564 started = STARTED_CHATTER;
3569 if (looking_at(buf, &i, "Black Strength :") ||
3570 looking_at(buf, &i, "<<< style 10 board >>>") ||
3571 looking_at(buf, &i, "<10>") ||
3572 looking_at(buf, &i, "#@#")) {
3573 /* Wrong board style */
3575 SendToICS(ics_prefix);
3576 SendToICS("set style 12\n");
3577 SendToICS(ics_prefix);
3578 SendToICS("refresh\n");
3582 if (looking_at(buf, &i, "login:")) {
3583 if (!have_sent_ICS_logon) {
3585 have_sent_ICS_logon = 1;
3586 else // no init script was found
3587 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3588 } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3589 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3594 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3595 (looking_at(buf, &i, "\n<12> ") ||
3596 looking_at(buf, &i, "<12> "))) {
3598 if (oldi > next_out) {
3599 SendToPlayer(&buf[next_out], oldi - next_out);
3602 started = STARTED_BOARD;
3607 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3608 looking_at(buf, &i, "<b1> ")) {
3609 if (oldi > next_out) {
3610 SendToPlayer(&buf[next_out], oldi - next_out);
3613 started = STARTED_HOLDINGS;
3618 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3620 /* Header for a move list -- first line */
3622 switch (ics_getting_history) {
3626 case BeginningOfGame:
3627 /* User typed "moves" or "oldmoves" while we
3628 were idle. Pretend we asked for these
3629 moves and soak them up so user can step
3630 through them and/or save them.
3633 gameMode = IcsObserving;
3636 ics_getting_history = H_GOT_UNREQ_HEADER;
3638 case EditGame: /*?*/
3639 case EditPosition: /*?*/
3640 /* Should above feature work in these modes too? */
3641 /* For now it doesn't */
3642 ics_getting_history = H_GOT_UNWANTED_HEADER;
3645 ics_getting_history = H_GOT_UNWANTED_HEADER;
3650 /* Is this the right one? */
3651 if (gameInfo.white && gameInfo.black &&
3652 strcmp(gameInfo.white, star_match[0]) == 0 &&
3653 strcmp(gameInfo.black, star_match[2]) == 0) {
3655 ics_getting_history = H_GOT_REQ_HEADER;
3658 case H_GOT_REQ_HEADER:
3659 case H_GOT_UNREQ_HEADER:
3660 case H_GOT_UNWANTED_HEADER:
3661 case H_GETTING_MOVES:
3662 /* Should not happen */
3663 DisplayError(_("Error gathering move list: two headers"), 0);
3664 ics_getting_history = H_FALSE;
3668 /* Save player ratings into gameInfo if needed */
3669 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3670 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3671 (gameInfo.whiteRating == -1 ||
3672 gameInfo.blackRating == -1)) {
3674 gameInfo.whiteRating = string_to_rating(star_match[1]);
3675 gameInfo.blackRating = string_to_rating(star_match[3]);
3676 if (appData.debugMode)
3677 fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3678 gameInfo.whiteRating, gameInfo.blackRating);
3683 if (looking_at(buf, &i,
3684 "* * match, initial time: * minute*, increment: * second")) {
3685 /* Header for a move list -- second line */
3686 /* Initial board will follow if this is a wild game */
3687 if (gameInfo.event != NULL) free(gameInfo.event);
3688 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3689 gameInfo.event = StrSave(str);
3690 /* [HGM] we switched variant. Translate boards if needed. */
3691 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3695 if (looking_at(buf, &i, "Move ")) {
3696 /* Beginning of a move list */
3697 switch (ics_getting_history) {
3699 /* Normally should not happen */
3700 /* Maybe user hit reset while we were parsing */
3703 /* Happens if we are ignoring a move list that is not
3704 * the one we just requested. Common if the user
3705 * tries to observe two games without turning off
3708 case H_GETTING_MOVES:
3709 /* Should not happen */
3710 DisplayError(_("Error gathering move list: nested"), 0);
3711 ics_getting_history = H_FALSE;
3713 case H_GOT_REQ_HEADER:
3714 ics_getting_history = H_GETTING_MOVES;
3715 started = STARTED_MOVES;
3717 if (oldi > next_out) {
3718 SendToPlayer(&buf[next_out], oldi - next_out);
3721 case H_GOT_UNREQ_HEADER:
3722 ics_getting_history = H_GETTING_MOVES;
3723 started = STARTED_MOVES_NOHIDE;
3726 case H_GOT_UNWANTED_HEADER:
3727 ics_getting_history = H_FALSE;
3733 if (looking_at(buf, &i, "% ") ||
3734 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3735 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3736 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3737 soughtPending = FALSE;
3741 if(suppressKibitz) next_out = i;
3742 savingComment = FALSE;
3746 case STARTED_MOVES_NOHIDE:
3747 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3748 parse[parse_pos + i - oldi] = NULLCHAR;
3749 ParseGameHistory(parse);
3751 if (appData.zippyPlay && first.initDone) {
3752 FeedMovesToProgram(&first, forwardMostMove);
3753 if (gameMode == IcsPlayingWhite) {
3754 if (WhiteOnMove(forwardMostMove)) {
3755 if (first.sendTime) {
3756 if (first.useColors) {
3757 SendToProgram("black\n", &first);
3759 SendTimeRemaining(&first, TRUE);
3761 if (first.useColors) {
3762 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3764 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3765 first.maybeThinking = TRUE;
3767 if (first.usePlayother) {
3768 if (first.sendTime) {
3769 SendTimeRemaining(&first, TRUE);
3771 SendToProgram("playother\n", &first);
3777 } else if (gameMode == IcsPlayingBlack) {
3778 if (!WhiteOnMove(forwardMostMove)) {
3779 if (first.sendTime) {
3780 if (first.useColors) {
3781 SendToProgram("white\n", &first);
3783 SendTimeRemaining(&first, FALSE);
3785 if (first.useColors) {
3786 SendToProgram("black\n", &first);
3788 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3789 first.maybeThinking = TRUE;
3791 if (first.usePlayother) {
3792 if (first.sendTime) {
3793 SendTimeRemaining(&first, FALSE);
3795 SendToProgram("playother\n", &first);
3804 if (gameMode == IcsObserving && ics_gamenum == -1) {
3805 /* Moves came from oldmoves or moves command
3806 while we weren't doing anything else.
3808 currentMove = forwardMostMove;
3809 ClearHighlights();/*!!could figure this out*/
3810 flipView = appData.flipView;
3811 DrawPosition(TRUE, boards[currentMove]);
3812 DisplayBothClocks();
3813 snprintf(str, MSG_SIZ, "%s %s %s",
3814 gameInfo.white, _("vs."), gameInfo.black);
3818 /* Moves were history of an active game */
3819 if (gameInfo.resultDetails != NULL) {
3820 free(gameInfo.resultDetails);
3821 gameInfo.resultDetails = NULL;
3824 HistorySet(parseList, backwardMostMove,
3825 forwardMostMove, currentMove-1);
3826 DisplayMove(currentMove - 1);
3827 if (started == STARTED_MOVES) next_out = i;
3828 started = STARTED_NONE;
3829 ics_getting_history = H_FALSE;
3832 case STARTED_OBSERVE:
3833 started = STARTED_NONE;
3834 SendToICS(ics_prefix);
3835 SendToICS("refresh\n");
3841 if(bookHit) { // [HGM] book: simulate book reply
3842 static char bookMove[MSG_SIZ]; // a bit generous?
3844 programStats.nodes = programStats.depth = programStats.time =
3845 programStats.score = programStats.got_only_move = 0;
3846 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3848 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3849 strcat(bookMove, bookHit);
3850 HandleMachineMove(bookMove, &first);
3855 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3856 started == STARTED_HOLDINGS ||
3857 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3858 /* Accumulate characters in move list or board */
3859 parse[parse_pos++] = buf[i];
3862 /* Start of game messages. Mostly we detect start of game
3863 when the first board image arrives. On some versions
3864 of the ICS, though, we need to do a "refresh" after starting
3865 to observe in order to get the current board right away. */
3866 if (looking_at(buf, &i, "Adding game * to observation list")) {
3867 started = STARTED_OBSERVE;
3871 /* Handle auto-observe */
3872 if (appData.autoObserve &&
3873 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3874 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3876 /* Choose the player that was highlighted, if any. */
3877 if (star_match[0][0] == '\033' ||
3878 star_match[1][0] != '\033') {
3879 player = star_match[0];
3881 player = star_match[2];
3883 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3884 ics_prefix, StripHighlightAndTitle(player));
3887 /* Save ratings from notify string */
3888 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3889 player1Rating = string_to_rating(star_match[1]);
3890 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3891 player2Rating = string_to_rating(star_match[3]);
3893 if (appData.debugMode)
3895 "Ratings from 'Game notification:' %s %d, %s %d\n",
3896 player1Name, player1Rating,
3897 player2Name, player2Rating);
3902 /* Deal with automatic examine mode after a game,
3903 and with IcsObserving -> IcsExamining transition */
3904 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3905 looking_at(buf, &i, "has made you an examiner of game *")) {
3907 int gamenum = atoi(star_match[0]);
3908 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3909 gamenum == ics_gamenum) {
3910 /* We were already playing or observing this game;
3911 no need to refetch history */
3912 gameMode = IcsExamining;
3914 pauseExamForwardMostMove = forwardMostMove;
3915 } else if (currentMove < forwardMostMove) {
3916 ForwardInner(forwardMostMove);
3919 /* I don't think this case really can happen */
3920 SendToICS(ics_prefix);
3921 SendToICS("refresh\n");
3926 /* Error messages */
3927 // if (ics_user_moved) {
3928 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3929 if (looking_at(buf, &i, "Illegal move") ||
3930 looking_at(buf, &i, "Not a legal move") ||
3931 looking_at(buf, &i, "Your king is in check") ||
3932 looking_at(buf, &i, "It isn't your turn") ||
3933 looking_at(buf, &i, "It is not your move")) {
3935 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3936 currentMove = forwardMostMove-1;
3937 DisplayMove(currentMove - 1); /* before DMError */
3938 DrawPosition(FALSE, boards[currentMove]);
3939 SwitchClocks(forwardMostMove-1); // [HGM] race
3940 DisplayBothClocks();
3942 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3948 if (looking_at(buf, &i, "still have time") ||
3949 looking_at(buf, &i, "not out of time") ||
3950 looking_at(buf, &i, "either player is out of time") ||
3951 looking_at(buf, &i, "has timeseal; checking")) {
3952 /* We must have called his flag a little too soon */
3953 whiteFlag = blackFlag = FALSE;
3957 if (looking_at(buf, &i, "added * seconds to") ||
3958 looking_at(buf, &i, "seconds were added to")) {
3959 /* Update the clocks */
3960 SendToICS(ics_prefix);
3961 SendToICS("refresh\n");
3965 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3966 ics_clock_paused = TRUE;
3971 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3972 ics_clock_paused = FALSE;
3977 /* Grab player ratings from the Creating: message.
3978 Note we have to check for the special case when
3979 the ICS inserts things like [white] or [black]. */
3980 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3981 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3983 0 player 1 name (not necessarily white)
3985 2 empty, white, or black (IGNORED)
3986 3 player 2 name (not necessarily black)
3989 The names/ratings are sorted out when the game
3990 actually starts (below).
3992 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3993 player1Rating = string_to_rating(star_match[1]);
3994 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3995 player2Rating = string_to_rating(star_match[4]);
3997 if (appData.debugMode)
3999 "Ratings from 'Creating:' %s %d, %s %d\n",
4000 player1Name, player1Rating,
4001 player2Name, player2Rating);
4006 /* Improved generic start/end-of-game messages */
4007 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
4008 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
4009 /* If tkind == 0: */
4010 /* star_match[0] is the game number */
4011 /* [1] is the white player's name */
4012 /* [2] is the black player's name */
4013 /* For end-of-game: */
4014 /* [3] is the reason for the game end */
4015 /* [4] is a PGN end game-token, preceded by " " */
4016 /* For start-of-game: */
4017 /* [3] begins with "Creating" or "Continuing" */
4018 /* [4] is " *" or empty (don't care). */
4019 int gamenum = atoi(star_match[0]);
4020 char *whitename, *blackname, *why, *endtoken;
4021 ChessMove endtype = EndOfFile;
4024 whitename = star_match[1];
4025 blackname = star_match[2];
4026 why = star_match[3];
4027 endtoken = star_match[4];
4029 whitename = star_match[1];
4030 blackname = star_match[3];
4031 why = star_match[5];
4032 endtoken = star_match[6];
4035 /* Game start messages */
4036 if (strncmp(why, "Creating ", 9) == 0 ||
4037 strncmp(why, "Continuing ", 11) == 0) {
4038 gs_gamenum = gamenum;
4039 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
4040 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
4041 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
4043 if (appData.zippyPlay) {
4044 ZippyGameStart(whitename, blackname);
4047 partnerBoardValid = FALSE; // [HGM] bughouse
4051 /* Game end messages */
4052 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
4053 ics_gamenum != gamenum) {
4056 while (endtoken[0] == ' ') endtoken++;
4057 switch (endtoken[0]) {
4060 endtype = GameUnfinished;
4063 endtype = BlackWins;
4066 if (endtoken[1] == '/')
4067 endtype = GameIsDrawn;
4069 endtype = WhiteWins;
4072 GameEnds(endtype, why, GE_ICS);
4074 if (appData.zippyPlay && first.initDone) {
4075 ZippyGameEnd(endtype, why);
4076 if (first.pr == NoProc) {
4077 /* Start the next process early so that we'll
4078 be ready for the next challenge */
4079 StartChessProgram(&first);
4081 /* Send "new" early, in case this command takes
4082 a long time to finish, so that we'll be ready
4083 for the next challenge. */
4084 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
4088 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
4092 if (looking_at(buf, &i, "Removing game * from observation") ||
4093 looking_at(buf, &i, "no longer observing game *") ||
4094 looking_at(buf, &i, "Game * (*) has no examiners")) {
4095 if (gameMode == IcsObserving &&
4096 atoi(star_match[0]) == ics_gamenum)
4098 /* icsEngineAnalyze */
4099 if (appData.icsEngineAnalyze) {
4106 ics_user_moved = FALSE;
4111 if (looking_at(buf, &i, "no longer examining game *")) {
4112 if (gameMode == IcsExamining &&
4113 atoi(star_match[0]) == ics_gamenum)
4117 ics_user_moved = FALSE;
4122 /* Advance leftover_start past any newlines we find,
4123 so only partial lines can get reparsed */
4124 if (looking_at(buf, &i, "\n")) {
4125 prevColor = curColor;
4126 if (curColor != ColorNormal) {
4127 if (oldi > next_out) {
4128 SendToPlayer(&buf[next_out], oldi - next_out);
4131 Colorize(ColorNormal, FALSE);
4132 curColor = ColorNormal;
4134 if (started == STARTED_BOARD) {
4135 started = STARTED_NONE;
4136 parse[parse_pos] = NULLCHAR;
4137 ParseBoard12(parse);
4140 /* Send premove here */
4141 if (appData.premove) {
4143 if (currentMove == 0 &&
4144 gameMode == IcsPlayingWhite &&
4145 appData.premoveWhite) {
4146 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4147 if (appData.debugMode)
4148 fprintf(debugFP, "Sending premove:\n");
4150 } else if (currentMove == 1 &&
4151 gameMode == IcsPlayingBlack &&
4152 appData.premoveBlack) {
4153 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4154 if (appData.debugMode)
4155 fprintf(debugFP, "Sending premove:\n");
4157 } else if (gotPremove) {
4159 ClearPremoveHighlights();
4160 if (appData.debugMode)
4161 fprintf(debugFP, "Sending premove:\n");
4162 UserMoveEvent(premoveFromX, premoveFromY,
4163 premoveToX, premoveToY,
4168 /* Usually suppress following prompt */
4169 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4170 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4171 if (looking_at(buf, &i, "*% ")) {
4172 savingComment = FALSE;
4177 } else if (started == STARTED_HOLDINGS) {
4179 char new_piece[MSG_SIZ];
4180 started = STARTED_NONE;
4181 parse[parse_pos] = NULLCHAR;
4182 if (appData.debugMode)
4183 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4184 parse, currentMove);
4185 if (sscanf(parse, " game %d", &gamenum) == 1) {
4186 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4187 if (gameInfo.variant == VariantNormal) {
4188 /* [HGM] We seem to switch variant during a game!
4189 * Presumably no holdings were displayed, so we have
4190 * to move the position two files to the right to
4191 * create room for them!
4193 VariantClass newVariant;
4194 switch(gameInfo.boardWidth) { // base guess on board width
4195 case 9: newVariant = VariantShogi; break;
4196 case 10: newVariant = VariantGreat; break;
4197 default: newVariant = VariantCrazyhouse; break;
4199 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4200 /* Get a move list just to see the header, which
4201 will tell us whether this is really bug or zh */
4202 if (ics_getting_history == H_FALSE) {
4203 ics_getting_history = H_REQUESTED;
4204 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4208 new_piece[0] = NULLCHAR;
4209 sscanf(parse, "game %d white [%s black [%s <- %s",
4210 &gamenum, white_holding, black_holding,
4212 white_holding[strlen(white_holding)-1] = NULLCHAR;
4213 black_holding[strlen(black_holding)-1] = NULLCHAR;
4214 /* [HGM] copy holdings to board holdings area */
4215 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4216 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4217 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4219 if (appData.zippyPlay && first.initDone) {
4220 ZippyHoldings(white_holding, black_holding,
4224 if (tinyLayout || smallLayout) {
4225 char wh[16], bh[16];
4226 PackHolding(wh, white_holding);
4227 PackHolding(bh, black_holding);
4228 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4229 gameInfo.white, gameInfo.black);
4231 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4232 gameInfo.white, white_holding, _("vs."),
4233 gameInfo.black, black_holding);
4235 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4236 DrawPosition(FALSE, boards[currentMove]);
4238 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4239 sscanf(parse, "game %d white [%s black [%s <- %s",
4240 &gamenum, white_holding, black_holding,
4242 white_holding[strlen(white_holding)-1] = NULLCHAR;
4243 black_holding[strlen(black_holding)-1] = NULLCHAR;
4244 /* [HGM] copy holdings to partner-board holdings area */
4245 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4246 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4247 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4248 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4249 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4252 /* Suppress following prompt */
4253 if (looking_at(buf, &i, "*% ")) {
4254 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4255 savingComment = FALSE;
4263 i++; /* skip unparsed character and loop back */
4266 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4267 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4268 // SendToPlayer(&buf[next_out], i - next_out);
4269 started != STARTED_HOLDINGS && leftover_start > next_out) {
4270 SendToPlayer(&buf[next_out], leftover_start - next_out);
4274 leftover_len = buf_len - leftover_start;
4275 /* if buffer ends with something we couldn't parse,
4276 reparse it after appending the next read */
4278 } else if (count == 0) {
4279 RemoveInputSource(isr);
4280 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4282 DisplayFatalError(_("Error reading from ICS"), error, 1);
4287 /* Board style 12 looks like this:
4289 <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
4291 * The "<12> " is stripped before it gets to this routine. The two
4292 * trailing 0's (flip state and clock ticking) are later addition, and
4293 * some chess servers may not have them, or may have only the first.
4294 * Additional trailing fields may be added in the future.
4297 #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"
4299 #define RELATION_OBSERVING_PLAYED 0
4300 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4301 #define RELATION_PLAYING_MYMOVE 1
4302 #define RELATION_PLAYING_NOTMYMOVE -1
4303 #define RELATION_EXAMINING 2
4304 #define RELATION_ISOLATED_BOARD -3
4305 #define RELATION_STARTING_POSITION -4 /* FICS only */
4308 ParseBoard12 (char *string)
4312 char *bookHit = NULL; // [HGM] book
4314 GameMode newGameMode;
4315 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4316 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4317 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4318 char to_play, board_chars[200];
4319 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4320 char black[32], white[32];
4322 int prevMove = currentMove;
4325 int fromX, fromY, toX, toY;
4327 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4328 Boolean weird = FALSE, reqFlag = FALSE;
4330 fromX = fromY = toX = toY = -1;
4334 if (appData.debugMode)
4335 fprintf(debugFP, "Parsing board: %s\n", string);
4337 move_str[0] = NULLCHAR;
4338 elapsed_time[0] = NULLCHAR;
4339 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4341 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4342 if(string[i] == ' ') { ranks++; files = 0; }
4344 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4347 for(j = 0; j <i; j++) board_chars[j] = string[j];
4348 board_chars[i] = '\0';
4351 n = sscanf(string, PATTERN, &to_play, &double_push,
4352 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4353 &gamenum, white, black, &relation, &basetime, &increment,
4354 &white_stren, &black_stren, &white_time, &black_time,
4355 &moveNum, str, elapsed_time, move_str, &ics_flip,
4359 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4360 DisplayError(str, 0);
4364 /* Convert the move number to internal form */
4365 moveNum = (moveNum - 1) * 2;
4366 if (to_play == 'B') moveNum++;
4367 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4368 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4374 case RELATION_OBSERVING_PLAYED:
4375 case RELATION_OBSERVING_STATIC:
4376 if (gamenum == -1) {
4377 /* Old ICC buglet */
4378 relation = RELATION_OBSERVING_STATIC;
4380 newGameMode = IcsObserving;
4382 case RELATION_PLAYING_MYMOVE:
4383 case RELATION_PLAYING_NOTMYMOVE:
4385 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4386 IcsPlayingWhite : IcsPlayingBlack;
4387 soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4389 case RELATION_EXAMINING:
4390 newGameMode = IcsExamining;
4392 case RELATION_ISOLATED_BOARD:
4394 /* Just display this board. If user was doing something else,
4395 we will forget about it until the next board comes. */
4396 newGameMode = IcsIdle;
4398 case RELATION_STARTING_POSITION:
4399 newGameMode = gameMode;
4403 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4404 gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4405 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4406 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4407 int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4408 static int lastBgGame = -1;
4410 for (k = 0; k < ranks; k++) {
4411 for (j = 0; j < files; j++)
4412 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4413 if(gameInfo.holdingsWidth > 1) {
4414 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4415 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4418 CopyBoard(partnerBoard, board);
4419 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4420 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4421 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4422 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4423 if(toSqr = strchr(str, '-')) {
4424 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4425 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4426 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4427 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4428 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4429 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4431 DisplayWhiteClock(white_time*fac, to_play == 'W');
4432 DisplayBlackClock(black_time*fac, to_play != 'W');
4433 activePartner = to_play;
4434 if(gamenum != lastBgGame) {
4436 snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4439 lastBgGame = gamenum;
4440 activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4441 partnerUp = 0; flipView = !flipView; } // [HGM] dual
4442 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4443 (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4444 if(!twoBoards) DisplayMessage(partnerStatus, "");
4445 partnerBoardValid = TRUE;
4449 if(appData.dualBoard && appData.bgObserve) {
4450 if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4451 SendToICS(ics_prefix), SendToICS("pobserve\n");
4452 else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4454 snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4459 /* Modify behavior for initial board display on move listing
4462 switch (ics_getting_history) {
4466 case H_GOT_REQ_HEADER:
4467 case H_GOT_UNREQ_HEADER:
4468 /* This is the initial position of the current game */
4469 gamenum = ics_gamenum;
4470 moveNum = 0; /* old ICS bug workaround */
4471 if (to_play == 'B') {
4472 startedFromSetupPosition = TRUE;
4473 blackPlaysFirst = TRUE;
4475 if (forwardMostMove == 0) forwardMostMove = 1;
4476 if (backwardMostMove == 0) backwardMostMove = 1;
4477 if (currentMove == 0) currentMove = 1;
4479 newGameMode = gameMode;
4480 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4482 case H_GOT_UNWANTED_HEADER:
4483 /* This is an initial board that we don't want */
4485 case H_GETTING_MOVES:
4486 /* Should not happen */
4487 DisplayError(_("Error gathering move list: extra board"), 0);
4488 ics_getting_history = H_FALSE;
4492 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4493 move_str[1] == '@' && !gameInfo.holdingsWidth ||
4494 weird && (int)gameInfo.variant < (int)VariantShogi) {
4495 /* [HGM] We seem to have switched variant unexpectedly
4496 * Try to guess new variant from board size
4498 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4499 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4500 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4501 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4502 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4503 if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4504 if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4505 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4506 /* Get a move list just to see the header, which
4507 will tell us whether this is really bug or zh */
4508 if (ics_getting_history == H_FALSE) {
4509 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4510 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4515 /* Take action if this is the first board of a new game, or of a
4516 different game than is currently being displayed. */
4517 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4518 relation == RELATION_ISOLATED_BOARD) {
4520 /* Forget the old game and get the history (if any) of the new one */
4521 if (gameMode != BeginningOfGame) {
4525 if (appData.autoRaiseBoard) BoardToTop();
4527 if (gamenum == -1) {
4528 newGameMode = IcsIdle;
4529 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4530 appData.getMoveList && !reqFlag) {
4531 /* Need to get game history */
4532 ics_getting_history = H_REQUESTED;
4533 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4537 /* Initially flip the board to have black on the bottom if playing
4538 black or if the ICS flip flag is set, but let the user change
4539 it with the Flip View button. */
4540 flipView = appData.autoFlipView ?
4541 (newGameMode == IcsPlayingBlack) || ics_flip :
4544 /* Done with values from previous mode; copy in new ones */
4545 gameMode = newGameMode;
4547 ics_gamenum = gamenum;
4548 if (gamenum == gs_gamenum) {
4549 int klen = strlen(gs_kind);
4550 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4551 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4552 gameInfo.event = StrSave(str);
4554 gameInfo.event = StrSave("ICS game");
4556 gameInfo.site = StrSave(appData.icsHost);
4557 gameInfo.date = PGNDate();
4558 gameInfo.round = StrSave("-");
4559 gameInfo.white = StrSave(white);
4560 gameInfo.black = StrSave(black);
4561 timeControl = basetime * 60 * 1000;
4563 timeIncrement = increment * 1000;
4564 movesPerSession = 0;
4565 gameInfo.timeControl = TimeControlTagValue();
4566 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4567 if (appData.debugMode) {
4568 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4569 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4570 setbuf(debugFP, NULL);
4573 gameInfo.outOfBook = NULL;
4575 /* Do we have the ratings? */
4576 if (strcmp(player1Name, white) == 0 &&
4577 strcmp(player2Name, black) == 0) {
4578 if (appData.debugMode)
4579 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4580 player1Rating, player2Rating);
4581 gameInfo.whiteRating = player1Rating;
4582 gameInfo.blackRating = player2Rating;
4583 } else if (strcmp(player2Name, white) == 0 &&
4584 strcmp(player1Name, black) == 0) {
4585 if (appData.debugMode)
4586 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4587 player2Rating, player1Rating);
4588 gameInfo.whiteRating = player2Rating;
4589 gameInfo.blackRating = player1Rating;
4591 player1Name[0] = player2Name[0] = NULLCHAR;
4593 /* Silence shouts if requested */
4594 if (appData.quietPlay &&
4595 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4596 SendToICS(ics_prefix);
4597 SendToICS("set shout 0\n");
4601 /* Deal with midgame name changes */
4603 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4604 if (gameInfo.white) free(gameInfo.white);
4605 gameInfo.white = StrSave(white);
4607 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4608 if (gameInfo.black) free(gameInfo.black);
4609 gameInfo.black = StrSave(black);
4613 /* Throw away game result if anything actually changes in examine mode */
4614 if (gameMode == IcsExamining && !newGame) {
4615 gameInfo.result = GameUnfinished;
4616 if (gameInfo.resultDetails != NULL) {
4617 free(gameInfo.resultDetails);
4618 gameInfo.resultDetails = NULL;
4622 /* In pausing && IcsExamining mode, we ignore boards coming
4623 in if they are in a different variation than we are. */
4624 if (pauseExamInvalid) return;
4625 if (pausing && gameMode == IcsExamining) {
4626 if (moveNum <= pauseExamForwardMostMove) {
4627 pauseExamInvalid = TRUE;
4628 forwardMostMove = pauseExamForwardMostMove;
4633 if (appData.debugMode) {
4634 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4636 /* Parse the board */
4637 for (k = 0; k < ranks; k++) {
4638 for (j = 0; j < files; j++)
4639 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4640 if(gameInfo.holdingsWidth > 1) {
4641 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4642 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4645 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4646 board[5][BOARD_RGHT+1] = WhiteAngel;
4647 board[6][BOARD_RGHT+1] = WhiteMarshall;
4648 board[1][0] = BlackMarshall;
4649 board[2][0] = BlackAngel;
4650 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4652 CopyBoard(boards[moveNum], board);
4653 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4655 startedFromSetupPosition =
4656 !CompareBoards(board, initialPosition);
4657 if(startedFromSetupPosition)
4658 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4661 /* [HGM] Set castling rights. Take the outermost Rooks,
4662 to make it also work for FRC opening positions. Note that board12
4663 is really defective for later FRC positions, as it has no way to
4664 indicate which Rook can castle if they are on the same side of King.
4665 For the initial position we grant rights to the outermost Rooks,
4666 and remember thos rights, and we then copy them on positions
4667 later in an FRC game. This means WB might not recognize castlings with
4668 Rooks that have moved back to their original position as illegal,
4669 but in ICS mode that is not its job anyway.
4671 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4672 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4674 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4675 if(board[0][i] == WhiteRook) j = i;
4676 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4677 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4678 if(board[0][i] == WhiteRook) j = i;
4679 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4680 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4681 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4682 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4683 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4684 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4685 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4687 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4688 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4689 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4690 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4691 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4692 if(board[BOARD_HEIGHT-1][k] == bKing)
4693 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4694 if(gameInfo.variant == VariantTwoKings) {
4695 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4696 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4697 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4700 r = boards[moveNum][CASTLING][0] = initialRights[0];
4701 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4702 r = boards[moveNum][CASTLING][1] = initialRights[1];
4703 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4704 r = boards[moveNum][CASTLING][3] = initialRights[3];
4705 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4706 r = boards[moveNum][CASTLING][4] = initialRights[4];
4707 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4708 /* wildcastle kludge: always assume King has rights */
4709 r = boards[moveNum][CASTLING][2] = initialRights[2];
4710 r = boards[moveNum][CASTLING][5] = initialRights[5];
4712 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4713 boards[moveNum][EP_STATUS] = EP_NONE;
4714 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4715 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4716 if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4719 if (ics_getting_history == H_GOT_REQ_HEADER ||
4720 ics_getting_history == H_GOT_UNREQ_HEADER) {
4721 /* This was an initial position from a move list, not
4722 the current position */
4726 /* Update currentMove and known move number limits */
4727 newMove = newGame || moveNum > forwardMostMove;
4730 forwardMostMove = backwardMostMove = currentMove = moveNum;
4731 if (gameMode == IcsExamining && moveNum == 0) {
4732 /* Workaround for ICS limitation: we are not told the wild
4733 type when starting to examine a game. But if we ask for
4734 the move list, the move list header will tell us */
4735 ics_getting_history = H_REQUESTED;
4736 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4739 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4740 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4742 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4743 /* [HGM] applied this also to an engine that is silently watching */
4744 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4745 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4746 gameInfo.variant == currentlyInitializedVariant) {
4747 takeback = forwardMostMove - moveNum;
4748 for (i = 0; i < takeback; i++) {
4749 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4750 SendToProgram("undo\n", &first);
4755 forwardMostMove = moveNum;
4756 if (!pausing || currentMove > forwardMostMove)
4757 currentMove = forwardMostMove;
4759 /* New part of history that is not contiguous with old part */
4760 if (pausing && gameMode == IcsExamining) {
4761 pauseExamInvalid = TRUE;
4762 forwardMostMove = pauseExamForwardMostMove;
4765 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4767 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4768 // [HGM] when we will receive the move list we now request, it will be
4769 // fed to the engine from the first move on. So if the engine is not
4770 // in the initial position now, bring it there.
4771 InitChessProgram(&first, 0);
4774 ics_getting_history = H_REQUESTED;
4775 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4778 forwardMostMove = backwardMostMove = currentMove = moveNum;
4781 /* Update the clocks */
4782 if (strchr(elapsed_time, '.')) {
4784 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4785 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4787 /* Time is in seconds */
4788 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4789 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4794 if (appData.zippyPlay && newGame &&
4795 gameMode != IcsObserving && gameMode != IcsIdle &&
4796 gameMode != IcsExamining)
4797 ZippyFirstBoard(moveNum, basetime, increment);
4800 /* Put the move on the move list, first converting
4801 to canonical algebraic form. */
4803 if (appData.debugMode) {
4804 int f = forwardMostMove;
4805 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4806 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4807 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4808 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4809 fprintf(debugFP, "moveNum = %d\n", moveNum);
4810 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4811 setbuf(debugFP, NULL);
4813 if (moveNum <= backwardMostMove) {
4814 /* We don't know what the board looked like before
4816 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4817 strcat(parseList[moveNum - 1], " ");
4818 strcat(parseList[moveNum - 1], elapsed_time);
4819 moveList[moveNum - 1][0] = NULLCHAR;
4820 } else if (strcmp(move_str, "none") == 0) {
4821 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4822 /* Again, we don't know what the board looked like;
4823 this is really the start of the game. */
4824 parseList[moveNum - 1][0] = NULLCHAR;
4825 moveList[moveNum - 1][0] = NULLCHAR;
4826 backwardMostMove = moveNum;
4827 startedFromSetupPosition = TRUE;
4828 fromX = fromY = toX = toY = -1;
4830 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4831 // So we parse the long-algebraic move string in stead of the SAN move
4832 int valid; char buf[MSG_SIZ], *prom;
4834 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4835 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4836 // str looks something like "Q/a1-a2"; kill the slash
4838 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4839 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4840 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4841 strcat(buf, prom); // long move lacks promo specification!
4842 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4843 if(appData.debugMode)
4844 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4845 safeStrCpy(move_str, buf, MSG_SIZ);
4847 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4848 &fromX, &fromY, &toX, &toY, &promoChar)
4849 || ParseOneMove(buf, moveNum - 1, &moveType,
4850 &fromX, &fromY, &toX, &toY, &promoChar);
4851 // end of long SAN patch
4853 (void) CoordsToAlgebraic(boards[moveNum - 1],
4854 PosFlags(moveNum - 1),
4855 fromY, fromX, toY, toX, promoChar,
4856 parseList[moveNum-1]);
4857 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4863 if(!IS_SHOGI(gameInfo.variant))
4864 strcat(parseList[moveNum - 1], "+");
4867 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4868 strcat(parseList[moveNum - 1], "#");
4871 strcat(parseList[moveNum - 1], " ");
4872 strcat(parseList[moveNum - 1], elapsed_time);
4873 /* currentMoveString is set as a side-effect of ParseOneMove */
4874 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4875 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4876 strcat(moveList[moveNum - 1], "\n");
4878 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4879 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4880 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4881 ChessSquare old, new = boards[moveNum][k][j];
4882 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4883 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4884 if(old == new) continue;
4885 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4886 else if(new == WhiteWazir || new == BlackWazir) {
4887 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4888 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4889 else boards[moveNum][k][j] = old; // preserve type of Gold
4890 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4891 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4894 /* Move from ICS was illegal!? Punt. */
4895 if (appData.debugMode) {
4896 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4897 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4899 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4900 strcat(parseList[moveNum - 1], " ");
4901 strcat(parseList[moveNum - 1], elapsed_time);
4902 moveList[moveNum - 1][0] = NULLCHAR;
4903 fromX = fromY = toX = toY = -1;
4906 if (appData.debugMode) {
4907 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4908 setbuf(debugFP, NULL);
4912 /* Send move to chess program (BEFORE animating it). */
4913 if (appData.zippyPlay && !newGame && newMove &&
4914 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4916 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4917 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4918 if (moveList[moveNum - 1][0] == NULLCHAR) {
4919 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4921 DisplayError(str, 0);
4923 if (first.sendTime) {
4924 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4926 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4927 if (firstMove && !bookHit) {
4929 if (first.useColors) {
4930 SendToProgram(gameMode == IcsPlayingWhite ?
4932 "black\ngo\n", &first);
4934 SendToProgram("go\n", &first);
4936 first.maybeThinking = TRUE;
4939 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4940 if (moveList[moveNum - 1][0] == NULLCHAR) {
4941 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4942 DisplayError(str, 0);
4944 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4945 SendMoveToProgram(moveNum - 1, &first);
4952 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4953 /* If move comes from a remote source, animate it. If it
4954 isn't remote, it will have already been animated. */
4955 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4956 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4958 if (!pausing && appData.highlightLastMove) {
4959 SetHighlights(fromX, fromY, toX, toY);
4963 /* Start the clocks */
4964 whiteFlag = blackFlag = FALSE;
4965 appData.clockMode = !(basetime == 0 && increment == 0);
4967 ics_clock_paused = TRUE;
4969 } else if (ticking == 1) {
4970 ics_clock_paused = FALSE;
4972 if (gameMode == IcsIdle ||
4973 relation == RELATION_OBSERVING_STATIC ||
4974 relation == RELATION_EXAMINING ||
4976 DisplayBothClocks();
4980 /* Display opponents and material strengths */
4981 if (gameInfo.variant != VariantBughouse &&
4982 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4983 if (tinyLayout || smallLayout) {
4984 if(gameInfo.variant == VariantNormal)
4985 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4986 gameInfo.white, white_stren, gameInfo.black, black_stren,
4987 basetime, increment);
4989 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4990 gameInfo.white, white_stren, gameInfo.black, black_stren,
4991 basetime, increment, (int) gameInfo.variant);
4993 if(gameInfo.variant == VariantNormal)
4994 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4995 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4996 basetime, increment);
4998 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
4999 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5000 basetime, increment, VariantName(gameInfo.variant));
5003 if (appData.debugMode) {
5004 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
5009 /* Display the board */
5010 if (!pausing && !appData.noGUI) {
5012 if (appData.premove)
5014 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
5015 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
5016 ClearPremoveHighlights();
5018 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
5019 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
5020 DrawPosition(j, boards[currentMove]);
5022 DisplayMove(moveNum - 1);
5023 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
5024 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
5025 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
5026 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
5030 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5032 if(bookHit) { // [HGM] book: simulate book reply
5033 static char bookMove[MSG_SIZ]; // a bit generous?
5035 programStats.nodes = programStats.depth = programStats.time =
5036 programStats.score = programStats.got_only_move = 0;
5037 sprintf(programStats.movelist, "%s (xbook)", bookHit);
5039 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
5040 strcat(bookMove, bookHit);
5041 HandleMachineMove(bookMove, &first);
5050 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
5051 ics_getting_history = H_REQUESTED;
5052 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
5058 SendToBoth (char *msg)
5059 { // to make it easy to keep two engines in step in dual analysis
5060 SendToProgram(msg, &first);
5061 if(second.analyzing) SendToProgram(msg, &second);
5065 AnalysisPeriodicEvent (int force)
5067 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
5068 && !force) || !appData.periodicUpdates)
5071 /* Send . command to Crafty to collect stats */
5074 /* Don't send another until we get a response (this makes
5075 us stop sending to old Crafty's which don't understand
5076 the "." command (sending illegal cmds resets node count & time,
5077 which looks bad)) */
5078 programStats.ok_to_send = 0;
5082 ics_update_width (int new_width)
5084 ics_printf("set width %d\n", new_width);
5088 SendMoveToProgram (int moveNum, ChessProgramState *cps)
5092 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
5093 if(gameInfo.variant == VariantLion || gameInfo.variant == VariantChuChess || gameInfo.variant == VariantChu) {
5094 sprintf(buf, "%s@@@@\n", cps->useUsermove ? "usermove " : "");
5095 SendToProgram(buf, cps);
5098 // null move in variant where engine does not understand it (for analysis purposes)
5099 SendBoard(cps, moveNum + 1); // send position after move in stead.
5102 if (cps->useUsermove) {
5103 SendToProgram("usermove ", cps);
5107 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
5108 int len = space - parseList[moveNum];
5109 memcpy(buf, parseList[moveNum], len);
5111 buf[len] = NULLCHAR;
5113 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
5115 SendToProgram(buf, cps);
5117 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
5118 AlphaRank(moveList[moveNum], 4);
5119 SendToProgram(moveList[moveNum], cps);
5120 AlphaRank(moveList[moveNum], 4); // and back
5122 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5123 * the engine. It would be nice to have a better way to identify castle
5125 if(appData.fischerCastling && cps->useOOCastle) {
5126 int fromX = moveList[moveNum][0] - AAA;
5127 int fromY = moveList[moveNum][1] - ONE;
5128 int toX = moveList[moveNum][2] - AAA;
5129 int toY = moveList[moveNum][3] - ONE;
5130 if((boards[moveNum][fromY][fromX] == WhiteKing
5131 && boards[moveNum][toY][toX] == WhiteRook)
5132 || (boards[moveNum][fromY][fromX] == BlackKing
5133 && boards[moveNum][toY][toX] == BlackRook)) {
5134 if(toX > fromX) SendToProgram("O-O\n", cps);
5135 else SendToProgram("O-O-O\n", cps);
5137 else SendToProgram(moveList[moveNum], cps);
5139 if(moveList[moveNum][4] == ';') { // [HGM] lion: move is double-step over intermediate square
5140 snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d\n", moveList[moveNum][0], moveList[moveNum][1] - '0', // convert to two moves
5141 moveList[moveNum][5], moveList[moveNum][6] - '0',
5142 moveList[moveNum][5], moveList[moveNum][6] - '0',
5143 moveList[moveNum][2], moveList[moveNum][3] - '0');
5144 SendToProgram(buf, cps);
5146 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5147 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5148 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5149 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5150 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5152 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5153 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5154 SendToProgram(buf, cps);
5156 else SendToProgram(moveList[moveNum], cps);
5157 /* End of additions by Tord */
5160 /* [HGM] setting up the opening has brought engine in force mode! */
5161 /* Send 'go' if we are in a mode where machine should play. */
5162 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5163 (gameMode == TwoMachinesPlay ||
5165 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
5167 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5168 SendToProgram("go\n", cps);
5169 if (appData.debugMode) {
5170 fprintf(debugFP, "(extra)\n");
5173 setboardSpoiledMachineBlack = 0;
5177 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5179 char user_move[MSG_SIZ];
5182 if(gameInfo.variant == VariantSChess && promoChar) {
5183 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5184 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5185 } else suffix[0] = NULLCHAR;
5189 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5190 (int)moveType, fromX, fromY, toX, toY);
5191 DisplayError(user_move + strlen("say "), 0);
5193 case WhiteKingSideCastle:
5194 case BlackKingSideCastle:
5195 case WhiteQueenSideCastleWild:
5196 case BlackQueenSideCastleWild:
5198 case WhiteHSideCastleFR:
5199 case BlackHSideCastleFR:
5201 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5203 case WhiteQueenSideCastle:
5204 case BlackQueenSideCastle:
5205 case WhiteKingSideCastleWild:
5206 case BlackKingSideCastleWild:
5208 case WhiteASideCastleFR:
5209 case BlackASideCastleFR:
5211 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5213 case WhiteNonPromotion:
5214 case BlackNonPromotion:
5215 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5217 case WhitePromotion:
5218 case BlackPromotion:
5219 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
5220 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN)
5221 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5222 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5223 PieceToChar(WhiteFerz));
5224 else if(gameInfo.variant == VariantGreat)
5225 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5226 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5227 PieceToChar(WhiteMan));
5229 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5230 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5236 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5237 ToUpper(PieceToChar((ChessSquare) fromX)),
5238 AAA + toX, ONE + toY);
5240 case IllegalMove: /* could be a variant we don't quite understand */
5241 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5243 case WhiteCapturesEnPassant:
5244 case BlackCapturesEnPassant:
5245 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5246 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5249 SendToICS(user_move);
5250 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5251 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5256 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5257 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5258 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5259 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5260 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5263 if(gameMode != IcsExamining) { // is this ever not the case?
5264 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5266 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5267 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5268 } else { // on FICS we must first go to general examine mode
5269 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5271 if(gameInfo.variant != VariantNormal) {
5272 // try figure out wild number, as xboard names are not always valid on ICS
5273 for(i=1; i<=36; i++) {
5274 snprintf(buf, MSG_SIZ, "wild/%d", i);
5275 if(StringToVariant(buf) == gameInfo.variant) break;
5277 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5278 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5279 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5280 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5281 SendToICS(ics_prefix);
5283 if(startedFromSetupPosition || backwardMostMove != 0) {
5284 fen = PositionToFEN(backwardMostMove, NULL, 1);
5285 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5286 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5288 } else { // FICS: everything has to set by separate bsetup commands
5289 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5290 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5292 if(!WhiteOnMove(backwardMostMove)) {
5293 SendToICS("bsetup tomove black\n");
5295 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5296 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5298 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5299 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5301 i = boards[backwardMostMove][EP_STATUS];
5302 if(i >= 0) { // set e.p.
5303 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5309 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5310 SendToICS("bsetup done\n"); // switch to normal examining.
5312 for(i = backwardMostMove; i<last; i++) {
5314 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5315 if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5316 int len = strlen(moveList[i]);
5317 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5318 if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5322 SendToICS(ics_prefix);
5323 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5326 int killX = -1, killY = -1; // [HGM] lion: used for passing e.p. capture square to MakeMove
5329 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5331 if (rf == DROP_RANK) {
5332 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5333 sprintf(move, "%c@%c%c\n",
5334 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5336 if (promoChar == 'x' || promoChar == NULLCHAR) {
5337 sprintf(move, "%c%c%c%c\n",
5338 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5339 if(killX >= 0 && killY >= 0) sprintf(move+4, ";%c%c\n", AAA + killX, ONE + killY);
5341 sprintf(move, "%c%c%c%c%c\n",
5342 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5348 ProcessICSInitScript (FILE *f)
5352 while (fgets(buf, MSG_SIZ, f)) {
5353 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5360 static int lastX, lastY, lastLeftX, lastLeftY, selectFlag;
5362 static ClickType lastClickType;
5365 Partner (ChessSquare *p)
5366 { // change piece into promotion partner if one shogi-promotes to the other
5367 int stride = gameInfo.variant == VariantChu ? 22 : 11;
5368 ChessSquare partner;
5369 partner = (*p/stride & 1 ? *p - stride : *p + stride);
5370 if(PieceToChar(*p) != '+' && PieceToChar(partner) != '+') return 0;
5378 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5379 static int toggleFlag;
5380 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5381 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5382 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5383 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5384 if(fromY != BOARD_HEIGHT-2 && fromY != 1 && gameInfo.variant != VariantChuChess) pawn = EmptySquare;
5385 if(!step) toggleFlag = Partner(&last); // piece has shogi-promotion
5387 if(step && !(toggleFlag && Partner(&promoSweep))) promoSweep -= step;
5388 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5389 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5390 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5391 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5392 if(!step) step = -1;
5393 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5394 !toggleFlag && PieceToChar(promoSweep) == '+' || // skip promoted versions of other
5395 appData.testLegality && (promoSweep == king || gameInfo.variant != VariantChuChess &&
5396 (promoSweep == WhiteLion || promoSweep == BlackLion)));
5398 int victim = boards[currentMove][toY][toX];
5399 boards[currentMove][toY][toX] = promoSweep;
5400 DrawPosition(FALSE, boards[currentMove]);
5401 boards[currentMove][toY][toX] = victim;
5403 ChangeDragPiece(promoSweep);
5407 PromoScroll (int x, int y)
5411 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5412 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5413 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5414 if(!step) return FALSE;
5415 lastX = x; lastY = y;
5416 if((promoSweep < BlackPawn) == flipView) step = -step;
5417 if(step > 0) selectFlag = 1;
5418 if(!selectFlag) Sweep(step);
5423 NextPiece (int step)
5425 ChessSquare piece = boards[currentMove][toY][toX];
5428 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5429 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5430 if(!step) step = -1;
5431 } while(PieceToChar(pieceSweep) == '.');
5432 boards[currentMove][toY][toX] = pieceSweep;
5433 DrawPosition(FALSE, boards[currentMove]);
5434 boards[currentMove][toY][toX] = piece;
5436 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5438 AlphaRank (char *move, int n)
5440 // char *p = move, c; int x, y;
5442 if (appData.debugMode) {
5443 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5447 move[2]>='0' && move[2]<='9' &&
5448 move[3]>='a' && move[3]<='x' ) {
5450 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5451 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5453 if(move[0]>='0' && move[0]<='9' &&
5454 move[1]>='a' && move[1]<='x' &&
5455 move[2]>='0' && move[2]<='9' &&
5456 move[3]>='a' && move[3]<='x' ) {
5457 /* input move, Shogi -> normal */
5458 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5459 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5460 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5461 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5464 move[3]>='0' && move[3]<='9' &&
5465 move[2]>='a' && move[2]<='x' ) {
5467 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5468 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5471 move[0]>='a' && move[0]<='x' &&
5472 move[3]>='0' && move[3]<='9' &&
5473 move[2]>='a' && move[2]<='x' ) {
5474 /* output move, normal -> Shogi */
5475 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5476 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5477 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5478 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5479 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5481 if (appData.debugMode) {
5482 fprintf(debugFP, " out = '%s'\n", move);
5486 char yy_textstr[8000];
5488 /* Parser for moves from gnuchess, ICS, or user typein box */
5490 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5492 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5494 switch (*moveType) {
5495 case WhitePromotion:
5496 case BlackPromotion:
5497 case WhiteNonPromotion:
5498 case BlackNonPromotion:
5501 case WhiteCapturesEnPassant:
5502 case BlackCapturesEnPassant:
5503 case WhiteKingSideCastle:
5504 case WhiteQueenSideCastle:
5505 case BlackKingSideCastle:
5506 case BlackQueenSideCastle:
5507 case WhiteKingSideCastleWild:
5508 case WhiteQueenSideCastleWild:
5509 case BlackKingSideCastleWild:
5510 case BlackQueenSideCastleWild:
5511 /* Code added by Tord: */
5512 case WhiteHSideCastleFR:
5513 case WhiteASideCastleFR:
5514 case BlackHSideCastleFR:
5515 case BlackASideCastleFR:
5516 /* End of code added by Tord */
5517 case IllegalMove: /* bug or odd chess variant */
5518 *fromX = currentMoveString[0] - AAA;
5519 *fromY = currentMoveString[1] - ONE;
5520 *toX = currentMoveString[2] - AAA;
5521 *toY = currentMoveString[3] - ONE;
5522 *promoChar = currentMoveString[4];
5523 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5524 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5525 if (appData.debugMode) {
5526 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5528 *fromX = *fromY = *toX = *toY = 0;
5531 if (appData.testLegality) {
5532 return (*moveType != IllegalMove);
5534 return !(*fromX == *toX && *fromY == *toY && killX < 0) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5535 // [HGM] lion: if this is a double move we are less critical
5536 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5541 *fromX = *moveType == WhiteDrop ?
5542 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5543 (int) CharToPiece(ToLower(currentMoveString[0]));
5545 *toX = currentMoveString[2] - AAA;
5546 *toY = currentMoveString[3] - ONE;
5547 *promoChar = NULLCHAR;
5551 case ImpossibleMove:
5561 if (appData.debugMode) {
5562 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5565 *fromX = *fromY = *toX = *toY = 0;
5566 *promoChar = NULLCHAR;
5571 Boolean pushed = FALSE;
5572 char *lastParseAttempt;
5575 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5576 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5577 int fromX, fromY, toX, toY; char promoChar;
5582 lastParseAttempt = pv; if(!*pv) return; // turns out we crash when we parse an empty PV
5583 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5584 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5587 endPV = forwardMostMove;
5589 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5590 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5591 lastParseAttempt = pv;
5592 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5593 if(!valid && nr == 0 &&
5594 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5595 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5596 // Hande case where played move is different from leading PV move
5597 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5598 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5599 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5600 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5601 endPV += 2; // if position different, keep this
5602 moveList[endPV-1][0] = fromX + AAA;
5603 moveList[endPV-1][1] = fromY + ONE;
5604 moveList[endPV-1][2] = toX + AAA;
5605 moveList[endPV-1][3] = toY + ONE;
5606 parseList[endPV-1][0] = NULLCHAR;
5607 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5610 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5611 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5612 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5613 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5614 valid++; // allow comments in PV
5618 if(endPV+1 > framePtr) break; // no space, truncate
5621 CopyBoard(boards[endPV], boards[endPV-1]);
5622 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5623 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5624 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5625 CoordsToAlgebraic(boards[endPV - 1],
5626 PosFlags(endPV - 1),
5627 fromY, fromX, toY, toX, promoChar,
5628 parseList[endPV - 1]);
5630 if(atEnd == 2) return; // used hidden, for PV conversion
5631 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5632 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5633 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5634 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5635 DrawPosition(TRUE, boards[currentMove]);
5639 MultiPV (ChessProgramState *cps)
5640 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5642 for(i=0; i<cps->nrOptions; i++)
5643 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5648 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5651 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5653 int startPV, multi, lineStart, origIndex = index;
5654 char *p, buf2[MSG_SIZ];
5655 ChessProgramState *cps = (pane ? &second : &first);
5657 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5658 lastX = x; lastY = y;
5659 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5660 lineStart = startPV = index;
5661 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5662 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5664 do{ while(buf[index] && buf[index] != '\n') index++;
5665 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5667 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(cps)) >= 0) {
5668 int n = cps->option[multi].value;
5669 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5670 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5671 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5672 cps->option[multi].value = n;
5675 } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5676 ExcludeClick(origIndex - lineStart);
5678 } else if(!strncmp(buf+lineStart, "dep\t", 4)) { // column headers clicked
5679 Collapse(origIndex - lineStart);
5682 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5683 *start = startPV; *end = index-1;
5684 extendGame = (gameMode == AnalyzeMode && appData.autoExtend && origIndex - startPV < 5);
5691 static char buf[10*MSG_SIZ];
5692 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5694 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5695 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5696 for(i = forwardMostMove; i<endPV; i++){
5697 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5698 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5701 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5702 if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5703 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5709 LoadPV (int x, int y)
5710 { // called on right mouse click to load PV
5711 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5712 lastX = x; lastY = y;
5713 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5721 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5722 if(endPV < 0) return;
5723 if(appData.autoCopyPV) CopyFENToClipboard();
5725 if(extendGame && currentMove > forwardMostMove) {
5726 Boolean saveAnimate = appData.animate;
5728 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5729 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5730 } else storedGames--; // abandon shelved tail of original game
5733 forwardMostMove = currentMove;
5734 currentMove = oldFMM;
5735 appData.animate = FALSE;
5736 ToNrEvent(forwardMostMove);
5737 appData.animate = saveAnimate;
5739 currentMove = forwardMostMove;
5740 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5741 ClearPremoveHighlights();
5742 DrawPosition(TRUE, boards[currentMove]);
5746 MovePV (int x, int y, int h)
5747 { // step through PV based on mouse coordinates (called on mouse move)
5748 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5750 // we must somehow check if right button is still down (might be released off board!)
5751 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5752 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5753 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5755 lastX = x; lastY = y;
5757 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5758 if(endPV < 0) return;
5759 if(y < margin) step = 1; else
5760 if(y > h - margin) step = -1;
5761 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5762 currentMove += step;
5763 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5764 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5765 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5766 DrawPosition(FALSE, boards[currentMove]);
5770 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5771 // All positions will have equal probability, but the current method will not provide a unique
5772 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5778 int piecesLeft[(int)BlackPawn];
5779 int seed, nrOfShuffles;
5782 GetPositionNumber ()
5783 { // sets global variable seed
5786 seed = appData.defaultFrcPosition;
5787 if(seed < 0) { // randomize based on time for negative FRC position numbers
5788 for(i=0; i<50; i++) seed += random();
5789 seed = random() ^ random() >> 8 ^ random() << 8;
5790 if(seed<0) seed = -seed;
5795 put (Board board, int pieceType, int rank, int n, int shade)
5796 // put the piece on the (n-1)-th empty squares of the given shade
5800 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5801 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5802 board[rank][i] = (ChessSquare) pieceType;
5803 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5805 piecesLeft[pieceType]--;
5814 AddOnePiece (Board board, int pieceType, int rank, int shade)
5815 // calculate where the next piece goes, (any empty square), and put it there
5819 i = seed % squaresLeft[shade];
5820 nrOfShuffles *= squaresLeft[shade];
5821 seed /= squaresLeft[shade];
5822 put(board, pieceType, rank, i, shade);
5826 AddTwoPieces (Board board, int pieceType, int rank)
5827 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5829 int i, n=squaresLeft[ANY], j=n-1, k;
5831 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5832 i = seed % k; // pick one
5835 while(i >= j) i -= j--;
5836 j = n - 1 - j; i += j;
5837 put(board, pieceType, rank, j, ANY);
5838 put(board, pieceType, rank, i, ANY);
5842 SetUpShuffle (Board board, int number)
5846 GetPositionNumber(); nrOfShuffles = 1;
5848 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5849 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5850 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5852 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5854 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5855 p = (int) board[0][i];
5856 if(p < (int) BlackPawn) piecesLeft[p] ++;
5857 board[0][i] = EmptySquare;
5860 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5861 // shuffles restricted to allow normal castling put KRR first
5862 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5863 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5864 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5865 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5866 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5867 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5868 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5869 put(board, WhiteRook, 0, 0, ANY);
5870 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5873 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5874 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5875 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5876 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5877 while(piecesLeft[p] >= 2) {
5878 AddOnePiece(board, p, 0, LITE);
5879 AddOnePiece(board, p, 0, DARK);
5881 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5884 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5885 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5886 // but we leave King and Rooks for last, to possibly obey FRC restriction
5887 if(p == (int)WhiteRook) continue;
5888 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5889 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5892 // now everything is placed, except perhaps King (Unicorn) and Rooks
5894 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5895 // Last King gets castling rights
5896 while(piecesLeft[(int)WhiteUnicorn]) {
5897 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5898 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5901 while(piecesLeft[(int)WhiteKing]) {
5902 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5903 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5908 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5909 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5912 // Only Rooks can be left; simply place them all
5913 while(piecesLeft[(int)WhiteRook]) {
5914 i = put(board, WhiteRook, 0, 0, ANY);
5915 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5918 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5920 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5923 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5924 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5927 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5931 SetCharTable (char *table, const char * map)
5932 /* [HGM] moved here from winboard.c because of its general usefulness */
5933 /* Basically a safe strcpy that uses the last character as King */
5935 int result = FALSE; int NrPieces;
5937 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5938 && NrPieces >= 12 && !(NrPieces&1)) {
5939 int i; /* [HGM] Accept even length from 12 to 34 */
5941 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5942 for( i=0; i<NrPieces/2-1; i++ ) {
5944 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5946 table[(int) WhiteKing] = map[NrPieces/2-1];
5947 table[(int) BlackKing] = map[NrPieces-1];
5956 Prelude (Board board)
5957 { // [HGM] superchess: random selection of exo-pieces
5958 int i, j, k; ChessSquare p;
5959 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5961 GetPositionNumber(); // use FRC position number
5963 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5964 SetCharTable(pieceToChar, appData.pieceToCharTable);
5965 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5966 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5969 j = seed%4; seed /= 4;
5970 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5971 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5972 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5973 j = seed%3 + (seed%3 >= j); seed /= 3;
5974 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5975 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5976 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5977 j = seed%3; seed /= 3;
5978 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5979 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5980 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5981 j = seed%2 + (seed%2 >= j); seed /= 2;
5982 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5983 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5984 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5985 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5986 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5987 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5988 put(board, exoPieces[0], 0, 0, ANY);
5989 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5993 InitPosition (int redraw)
5995 ChessSquare (* pieces)[BOARD_FILES];
5996 int i, j, pawnRow=1, pieceRows=1, overrule,
5997 oldx = gameInfo.boardWidth,
5998 oldy = gameInfo.boardHeight,
5999 oldh = gameInfo.holdingsWidth;
6002 if(appData.icsActive) shuffleOpenings = appData.fischerCastling = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
6004 /* [AS] Initialize pv info list [HGM] and game status */
6006 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
6007 pvInfoList[i].depth = 0;
6008 boards[i][EP_STATUS] = EP_NONE;
6009 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
6012 initialRulePlies = 0; /* 50-move counter start */
6014 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
6015 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
6019 /* [HGM] logic here is completely changed. In stead of full positions */
6020 /* the initialized data only consist of the two backranks. The switch */
6021 /* selects which one we will use, which is than copied to the Board */
6022 /* initialPosition, which for the rest is initialized by Pawns and */
6023 /* empty squares. This initial position is then copied to boards[0], */
6024 /* possibly after shuffling, so that it remains available. */
6026 gameInfo.holdingsWidth = 0; /* default board sizes */
6027 gameInfo.boardWidth = 8;
6028 gameInfo.boardHeight = 8;
6029 gameInfo.holdingsSize = 0;
6030 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
6031 for(i=0; i<BOARD_FILES-6; i++)
6032 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
6033 initialPosition[EP_STATUS] = EP_NONE;
6034 initialPosition[TOUCHED_W] = initialPosition[TOUCHED_B] = 0;
6035 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
6036 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
6037 SetCharTable(pieceNickName, appData.pieceNickNames);
6038 else SetCharTable(pieceNickName, "............");
6041 switch (gameInfo.variant) {
6042 case VariantFischeRandom:
6043 shuffleOpenings = TRUE;
6044 appData.fischerCastling = TRUE;
6047 case VariantShatranj:
6048 pieces = ShatranjArray;
6049 nrCastlingRights = 0;
6050 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
6053 pieces = makrukArray;
6054 nrCastlingRights = 0;
6055 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
6058 pieces = aseanArray;
6059 nrCastlingRights = 0;
6060 SetCharTable(pieceToChar, "PN.R.Q....BKpn.r.q....bk");
6062 case VariantTwoKings:
6063 pieces = twoKingsArray;
6066 pieces = GrandArray;
6067 nrCastlingRights = 0;
6068 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6069 gameInfo.boardWidth = 10;
6070 gameInfo.boardHeight = 10;
6071 gameInfo.holdingsSize = 7;
6073 case VariantCapaRandom:
6074 shuffleOpenings = TRUE;
6075 appData.fischerCastling = TRUE;
6076 case VariantCapablanca:
6077 pieces = CapablancaArray;
6078 gameInfo.boardWidth = 10;
6079 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6082 pieces = GothicArray;
6083 gameInfo.boardWidth = 10;
6084 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6087 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
6088 gameInfo.holdingsSize = 7;
6089 for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
6092 pieces = JanusArray;
6093 gameInfo.boardWidth = 10;
6094 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
6095 nrCastlingRights = 6;
6096 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6097 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6098 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
6099 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6100 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6101 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
6104 pieces = FalconArray;
6105 gameInfo.boardWidth = 10;
6106 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
6108 case VariantXiangqi:
6109 pieces = XiangqiArray;
6110 gameInfo.boardWidth = 9;
6111 gameInfo.boardHeight = 10;
6112 nrCastlingRights = 0;
6113 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
6116 pieces = ShogiArray;
6117 gameInfo.boardWidth = 9;
6118 gameInfo.boardHeight = 9;
6119 gameInfo.holdingsSize = 7;
6120 nrCastlingRights = 0;
6121 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
6124 pieces = ChuArray; pieceRows = 3;
6125 gameInfo.boardWidth = 12;
6126 gameInfo.boardHeight = 12;
6127 nrCastlingRights = 0;
6128 SetCharTable(pieceToChar, "P.BRQSEXOGCATHD.VMLIFN+.++.++++++++++.+++++K"
6129 "p.brqsexogcathd.vmlifn+.++.++++++++++.+++++k");
6131 case VariantCourier:
6132 pieces = CourierArray;
6133 gameInfo.boardWidth = 12;
6134 nrCastlingRights = 0;
6135 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
6137 case VariantKnightmate:
6138 pieces = KnightmateArray;
6139 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
6141 case VariantSpartan:
6142 pieces = SpartanArray;
6143 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
6147 SetCharTable(pieceToChar, "PNBRQ................LKpnbrq................lk");
6149 case VariantChuChess:
6150 pieces = ChuChessArray;
6151 gameInfo.boardWidth = 10;
6152 gameInfo.boardHeight = 10;
6153 SetCharTable(pieceToChar, "PNBRQ.....M.+++......LKpnbrq.....m.+++......lk");
6156 pieces = fairyArray;
6157 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
6160 pieces = GreatArray;
6161 gameInfo.boardWidth = 10;
6162 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
6163 gameInfo.holdingsSize = 8;
6167 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
6168 gameInfo.holdingsSize = 8;
6169 startedFromSetupPosition = TRUE;
6171 case VariantCrazyhouse:
6172 case VariantBughouse:
6174 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
6175 gameInfo.holdingsSize = 5;
6177 case VariantWildCastle:
6179 /* !!?shuffle with kings guaranteed to be on d or e file */
6180 shuffleOpenings = 1;
6182 case VariantNoCastle:
6184 nrCastlingRights = 0;
6185 /* !!?unconstrained back-rank shuffle */
6186 shuffleOpenings = 1;
6191 if(appData.NrFiles >= 0) {
6192 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6193 gameInfo.boardWidth = appData.NrFiles;
6195 if(appData.NrRanks >= 0) {
6196 gameInfo.boardHeight = appData.NrRanks;
6198 if(appData.holdingsSize >= 0) {
6199 i = appData.holdingsSize;
6200 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6201 gameInfo.holdingsSize = i;
6203 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6204 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6205 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6207 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6208 if(pawnRow < 1) pawnRow = 1;
6209 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN ||
6210 gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) pawnRow = 2;
6211 if(gameInfo.variant == VariantChu) pawnRow = 3;
6213 /* User pieceToChar list overrules defaults */
6214 if(appData.pieceToCharTable != NULL)
6215 SetCharTable(pieceToChar, appData.pieceToCharTable);
6217 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6219 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6220 s = (ChessSquare) 0; /* account holding counts in guard band */
6221 for( i=0; i<BOARD_HEIGHT; i++ )
6222 initialPosition[i][j] = s;
6224 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6225 initialPosition[gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess][j] = pieces[0][j-gameInfo.holdingsWidth];
6226 initialPosition[pawnRow][j] = WhitePawn;
6227 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6228 if(gameInfo.variant == VariantXiangqi) {
6230 initialPosition[pawnRow][j] =
6231 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6232 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6233 initialPosition[2][j] = WhiteCannon;
6234 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6238 if(gameInfo.variant == VariantChu) {
6239 if(j == (BOARD_WIDTH-2)/3 || j == BOARD_WIDTH - (BOARD_WIDTH+1)/3)
6240 initialPosition[pawnRow+1][j] = WhiteCobra,
6241 initialPosition[BOARD_HEIGHT-pawnRow-2][j] = BlackCobra;
6242 for(i=1; i<pieceRows; i++) {
6243 initialPosition[i][j] = pieces[2*i][j-gameInfo.holdingsWidth];
6244 initialPosition[BOARD_HEIGHT-1-i][j] = pieces[2*i+1][j-gameInfo.holdingsWidth];
6247 if(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6248 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6249 initialPosition[0][j] = WhiteRook;
6250 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6253 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess)][j] = pieces[1][j-gameInfo.holdingsWidth];
6255 if(gameInfo.variant == VariantChuChess) initialPosition[0][BOARD_WIDTH/2] = WhiteKing, initialPosition[BOARD_HEIGHT-1][BOARD_WIDTH/2-1] = BlackKing;
6256 if( (gameInfo.variant == VariantShogi) && !overrule ) {
6259 initialPosition[1][j] = WhiteBishop;
6260 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6262 initialPosition[1][j] = WhiteRook;
6263 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6266 if( nrCastlingRights == -1) {
6267 /* [HGM] Build normal castling rights (must be done after board sizing!) */
6268 /* This sets default castling rights from none to normal corners */
6269 /* Variants with other castling rights must set them themselves above */
6270 nrCastlingRights = 6;
6272 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6273 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6274 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6275 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6276 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6277 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6280 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6281 if(gameInfo.variant == VariantGreat) { // promotion commoners
6282 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6283 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6284 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6285 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
6287 if( gameInfo.variant == VariantSChess ) {
6288 initialPosition[1][0] = BlackMarshall;
6289 initialPosition[2][0] = BlackAngel;
6290 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6291 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6292 initialPosition[1][1] = initialPosition[2][1] =
6293 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6295 if (appData.debugMode) {
6296 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6298 if(shuffleOpenings) {
6299 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6300 startedFromSetupPosition = TRUE;
6302 if(startedFromPositionFile) {
6303 /* [HGM] loadPos: use PositionFile for every new game */
6304 CopyBoard(initialPosition, filePosition);
6305 for(i=0; i<nrCastlingRights; i++)
6306 initialRights[i] = filePosition[CASTLING][i];
6307 startedFromSetupPosition = TRUE;
6310 CopyBoard(boards[0], initialPosition);
6312 if(oldx != gameInfo.boardWidth ||
6313 oldy != gameInfo.boardHeight ||
6314 oldv != gameInfo.variant ||
6315 oldh != gameInfo.holdingsWidth
6317 InitDrawingSizes(-2 ,0);
6319 oldv = gameInfo.variant;
6321 DrawPosition(TRUE, boards[currentMove]);
6325 SendBoard (ChessProgramState *cps, int moveNum)
6327 char message[MSG_SIZ];
6329 if (cps->useSetboard) {
6330 char* fen = PositionToFEN(moveNum, cps->fenOverride, 1);
6331 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6332 SendToProgram(message, cps);
6337 int i, j, left=0, right=BOARD_WIDTH;
6338 /* Kludge to set black to move, avoiding the troublesome and now
6339 * deprecated "black" command.
6341 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6342 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6344 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6346 SendToProgram("edit\n", cps);
6347 SendToProgram("#\n", cps);
6348 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6349 bp = &boards[moveNum][i][left];
6350 for (j = left; j < right; j++, bp++) {
6351 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6352 if ((int) *bp < (int) BlackPawn) {
6353 if(j == BOARD_RGHT+1)
6354 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6355 else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6356 if(message[0] == '+' || message[0] == '~') {
6357 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6358 PieceToChar((ChessSquare)(DEMOTED *bp)),
6361 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6362 message[1] = BOARD_RGHT - 1 - j + '1';
6363 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6365 SendToProgram(message, cps);
6370 SendToProgram("c\n", cps);
6371 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6372 bp = &boards[moveNum][i][left];
6373 for (j = left; j < right; j++, bp++) {
6374 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6375 if (((int) *bp != (int) EmptySquare)
6376 && ((int) *bp >= (int) BlackPawn)) {
6377 if(j == BOARD_LEFT-2)
6378 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6379 else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6381 if(message[0] == '+' || message[0] == '~') {
6382 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6383 PieceToChar((ChessSquare)(DEMOTED *bp)),
6386 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6387 message[1] = BOARD_RGHT - 1 - j + '1';
6388 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6390 SendToProgram(message, cps);
6395 SendToProgram(".\n", cps);
6397 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6400 char exclusionHeader[MSG_SIZ];
6401 int exCnt, excludePtr;
6402 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6403 static Exclusion excluTab[200];
6404 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6410 for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6411 exclusionHeader[19] = s ? '-' : '+'; // update tail state
6417 safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
6418 excludePtr = 24; exCnt = 0;
6423 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6424 { // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6425 char buf[2*MOVE_LEN], *p;
6426 Exclusion *e = excluTab;
6428 for(i=0; i<exCnt; i++)
6429 if(e[i].ff == fromX && e[i].fr == fromY &&
6430 e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
6431 if(i == exCnt) { // was not in exclude list; add it
6432 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6433 if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6434 if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6437 e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6438 excludePtr++; e[i].mark = excludePtr++;
6439 for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6442 exclusionHeader[e[i].mark] = state;
6446 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6447 { // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6451 if((signed char)promoChar == -1) { // kludge to indicate best move
6452 if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6453 return 1; // if unparsable, abort
6455 // update exclusion map (resolving toggle by consulting existing state)
6456 k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6458 if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6459 if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6460 excludeMap[k] |= 1<<j;
6461 else excludeMap[k] &= ~(1<<j);
6463 UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6465 snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6466 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6468 return (state == '+');
6472 ExcludeClick (int index)
6475 Exclusion *e = excluTab;
6476 if(index < 25) { // none, best or tail clicked
6477 if(index < 13) { // none: include all
6478 WriteMap(0); // clear map
6479 for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6480 SendToBoth("include all\n"); // and inform engine
6481 } else if(index > 18) { // tail
6482 if(exclusionHeader[19] == '-') { // tail was excluded
6483 SendToBoth("include all\n");
6484 WriteMap(0); // clear map completely
6485 // now re-exclude selected moves
6486 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6487 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6488 } else { // tail was included or in mixed state
6489 SendToBoth("exclude all\n");
6490 WriteMap(0xFF); // fill map completely
6491 // now re-include selected moves
6492 j = 0; // count them
6493 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6494 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6495 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6498 ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6501 for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6502 char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6503 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6510 DefaultPromoChoice (int white)
6513 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6514 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN)
6515 result = WhiteFerz; // no choice
6516 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6517 result= WhiteKing; // in Suicide Q is the last thing we want
6518 else if(gameInfo.variant == VariantSpartan)
6519 result = white ? WhiteQueen : WhiteAngel;
6520 else result = WhiteQueen;
6521 if(!white) result = WHITE_TO_BLACK result;
6525 static int autoQueen; // [HGM] oneclick
6528 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6530 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6531 /* [HGM] add Shogi promotions */
6532 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6533 ChessSquare piece, partner;
6537 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6538 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6540 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6541 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6544 piece = boards[currentMove][fromY][fromX];
6545 if(gameInfo.variant == VariantChu) {
6546 int p = piece >= BlackPawn ? BLACK_TO_WHITE piece : piece;
6547 promotionZoneSize = BOARD_HEIGHT/3;
6548 highestPromotingPiece = (p >= WhiteLion || PieceToChar(piece + 22) == '.') ? WhitePawn : WhiteLion;
6549 } else if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantChuChess) {
6550 promotionZoneSize = BOARD_HEIGHT/3;
6551 highestPromotingPiece = (int)WhiteAlfil;
6552 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6553 promotionZoneSize = 3;
6556 // Treat Lance as Pawn when it is not representing Amazon or Lance
6557 if(gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu) {
6558 if(piece == WhiteLance) piece = WhitePawn; else
6559 if(piece == BlackLance) piece = BlackPawn;
6562 // next weed out all moves that do not touch the promotion zone at all
6563 if((int)piece >= BlackPawn) {
6564 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6566 if(fromY < promotionZoneSize && gameInfo.variant == VariantChuChess) return FALSE;
6567 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6569 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6570 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6571 if(fromY >= BOARD_HEIGHT - promotionZoneSize && gameInfo.variant == VariantChuChess)
6575 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6577 // weed out mandatory Shogi promotions
6578 if(gameInfo.variant == VariantShogi) {
6579 if(piece >= BlackPawn) {
6580 if(toY == 0 && piece == BlackPawn ||
6581 toY == 0 && piece == BlackQueen ||
6582 toY <= 1 && piece == BlackKnight) {
6587 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6588 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6589 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6596 // weed out obviously illegal Pawn moves
6597 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6598 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6599 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6600 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6601 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6602 // note we are not allowed to test for valid (non-)capture, due to premove
6605 // we either have a choice what to promote to, or (in Shogi) whether to promote
6606 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6607 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN) {
6608 ChessSquare p=BlackFerz; // no choice
6609 while(p < EmptySquare) { //but make sure we use piece that exists
6610 *promoChoice = PieceToChar(p++);
6611 if(*promoChoice != '.') break;
6615 // no sense asking what we must promote to if it is going to explode...
6616 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6617 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6620 // give caller the default choice even if we will not make it
6621 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6622 partner = piece; // pieces can promote if the pieceToCharTable says so
6623 if(IS_SHOGI(gameInfo.variant)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? '=' : '+'); // obsolete?
6624 else if(Partner(&partner)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? NULLCHAR : '+');
6625 if( sweepSelect && gameInfo.variant != VariantGreat
6626 && gameInfo.variant != VariantGrand
6627 && gameInfo.variant != VariantSuper) return FALSE;
6628 if(autoQueen) return FALSE; // predetermined
6630 // suppress promotion popup on illegal moves that are not premoves
6631 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6632 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6633 if(appData.testLegality && !premove) {
6634 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6635 fromY, fromX, toY, toX, IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantChuChess ? '+' : NULLCHAR);
6636 if(moveType == IllegalMove) *promoChoice = NULLCHAR; // could be the fact we promoted was illegal
6637 if(moveType != WhitePromotion && moveType != BlackPromotion)
6645 InPalace (int row, int column)
6646 { /* [HGM] for Xiangqi */
6647 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6648 column < (BOARD_WIDTH + 4)/2 &&
6649 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6654 PieceForSquare (int x, int y)
6656 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6659 return boards[currentMove][y][x];
6663 OKToStartUserMove (int x, int y)
6665 ChessSquare from_piece;
6668 if (matchMode) return FALSE;
6669 if (gameMode == EditPosition) return TRUE;
6671 if (x >= 0 && y >= 0)
6672 from_piece = boards[currentMove][y][x];
6674 from_piece = EmptySquare;
6676 if (from_piece == EmptySquare) return FALSE;
6678 white_piece = (int)from_piece >= (int)WhitePawn &&
6679 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6683 case TwoMachinesPlay:
6691 case MachinePlaysWhite:
6692 case IcsPlayingBlack:
6693 if (appData.zippyPlay) return FALSE;
6695 DisplayMoveError(_("You are playing Black"));
6700 case MachinePlaysBlack:
6701 case IcsPlayingWhite:
6702 if (appData.zippyPlay) return FALSE;
6704 DisplayMoveError(_("You are playing White"));
6709 case PlayFromGameFile:
6710 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6712 if (!white_piece && WhiteOnMove(currentMove)) {
6713 DisplayMoveError(_("It is White's turn"));
6716 if (white_piece && !WhiteOnMove(currentMove)) {
6717 DisplayMoveError(_("It is Black's turn"));
6720 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6721 /* Editing correspondence game history */
6722 /* Could disallow this or prompt for confirmation */
6727 case BeginningOfGame:
6728 if (appData.icsActive) return FALSE;
6729 if (!appData.noChessProgram) {
6731 DisplayMoveError(_("You are playing White"));
6738 if (!white_piece && WhiteOnMove(currentMove)) {
6739 DisplayMoveError(_("It is White's turn"));
6742 if (white_piece && !WhiteOnMove(currentMove)) {
6743 DisplayMoveError(_("It is Black's turn"));
6752 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6753 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6754 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6755 && gameMode != AnalyzeFile && gameMode != Training) {
6756 DisplayMoveError(_("Displayed position is not current"));
6763 OnlyMove (int *x, int *y, Boolean captures)
6765 DisambiguateClosure cl;
6766 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6768 case MachinePlaysBlack:
6769 case IcsPlayingWhite:
6770 case BeginningOfGame:
6771 if(!WhiteOnMove(currentMove)) return FALSE;
6773 case MachinePlaysWhite:
6774 case IcsPlayingBlack:
6775 if(WhiteOnMove(currentMove)) return FALSE;
6782 cl.pieceIn = EmptySquare;
6787 cl.promoCharIn = NULLCHAR;
6788 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6789 if( cl.kind == NormalMove ||
6790 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6791 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6792 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6799 if(cl.kind != ImpossibleMove) return FALSE;
6800 cl.pieceIn = EmptySquare;
6805 cl.promoCharIn = NULLCHAR;
6806 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6807 if( cl.kind == NormalMove ||
6808 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6809 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6810 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6815 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6821 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6822 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6823 int lastLoadGameUseList = FALSE;
6824 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6825 ChessMove lastLoadGameStart = EndOfFile;
6827 Boolean addToBookFlag;
6830 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6834 int ff=fromX, rf=fromY, ft=toX, rt=toY;
6836 /* Check if the user is playing in turn. This is complicated because we
6837 let the user "pick up" a piece before it is his turn. So the piece he
6838 tried to pick up may have been captured by the time he puts it down!
6839 Therefore we use the color the user is supposed to be playing in this
6840 test, not the color of the piece that is currently on the starting
6841 square---except in EditGame mode, where the user is playing both
6842 sides; fortunately there the capture race can't happen. (It can
6843 now happen in IcsExamining mode, but that's just too bad. The user
6844 will get a somewhat confusing message in that case.)
6849 case TwoMachinesPlay:
6853 /* We switched into a game mode where moves are not accepted,
6854 perhaps while the mouse button was down. */
6857 case MachinePlaysWhite:
6858 /* User is moving for Black */
6859 if (WhiteOnMove(currentMove)) {
6860 DisplayMoveError(_("It is White's turn"));
6865 case MachinePlaysBlack:
6866 /* User is moving for White */
6867 if (!WhiteOnMove(currentMove)) {
6868 DisplayMoveError(_("It is Black's turn"));
6873 case PlayFromGameFile:
6874 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6877 case BeginningOfGame:
6880 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6881 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6882 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6883 /* User is moving for Black */
6884 if (WhiteOnMove(currentMove)) {
6885 DisplayMoveError(_("It is White's turn"));
6889 /* User is moving for White */
6890 if (!WhiteOnMove(currentMove)) {
6891 DisplayMoveError(_("It is Black's turn"));
6897 case IcsPlayingBlack:
6898 /* User is moving for Black */
6899 if (WhiteOnMove(currentMove)) {
6900 if (!appData.premove) {
6901 DisplayMoveError(_("It is White's turn"));
6902 } else if (toX >= 0 && toY >= 0) {
6905 premoveFromX = fromX;
6906 premoveFromY = fromY;
6907 premovePromoChar = promoChar;
6909 if (appData.debugMode)
6910 fprintf(debugFP, "Got premove: fromX %d,"
6911 "fromY %d, toX %d, toY %d\n",
6912 fromX, fromY, toX, toY);
6918 case IcsPlayingWhite:
6919 /* User is moving for White */
6920 if (!WhiteOnMove(currentMove)) {
6921 if (!appData.premove) {
6922 DisplayMoveError(_("It is Black's turn"));
6923 } else if (toX >= 0 && toY >= 0) {
6926 premoveFromX = fromX;
6927 premoveFromY = fromY;
6928 premovePromoChar = promoChar;
6930 if (appData.debugMode)
6931 fprintf(debugFP, "Got premove: fromX %d,"
6932 "fromY %d, toX %d, toY %d\n",
6933 fromX, fromY, toX, toY);
6943 /* EditPosition, empty square, or different color piece;
6944 click-click move is possible */
6945 if (toX == -2 || toY == -2) {
6946 boards[0][fromY][fromX] = EmptySquare;
6947 DrawPosition(FALSE, boards[currentMove]);
6949 } else if (toX >= 0 && toY >= 0) {
6950 if(!appData.pieceMenu && toX == fromX && toY == fromY && boards[0][rf][ff] != EmptySquare) {
6951 ChessSquare q, p = boards[0][rf][ff];
6952 if(p >= BlackPawn) p = BLACK_TO_WHITE p;
6953 if(CHUPROMOTED p < BlackPawn) p = q = CHUPROMOTED boards[0][rf][ff];
6954 else p = CHUDEMOTED (q = boards[0][rf][ff]);
6955 if(PieceToChar(q) == '+') gatingPiece = p;
6957 boards[0][toY][toX] = boards[0][fromY][fromX];
6958 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6959 if(boards[0][fromY][0] != EmptySquare) {
6960 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6961 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6964 if(fromX == BOARD_RGHT+1) {
6965 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6966 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6967 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6970 boards[0][fromY][fromX] = gatingPiece;
6971 DrawPosition(FALSE, boards[currentMove]);
6977 if((toX < 0 || toY < 0) && (fromY != DROP_RANK || fromX != EmptySquare)) return;
6978 pup = boards[currentMove][toY][toX];
6980 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6981 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6982 if( pup != EmptySquare ) return;
6983 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6984 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6985 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6986 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6987 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6988 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6989 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6993 /* [HGM] always test for legality, to get promotion info */
6994 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6995 fromY, fromX, toY, toX, promoChar);
6997 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame || PosFlags(0) & F_NULL_MOVE)) moveType = NormalMove;
6999 /* [HGM] but possibly ignore an IllegalMove result */
7000 if (appData.testLegality) {
7001 if (moveType == IllegalMove || moveType == ImpossibleMove) {
7002 DisplayMoveError(_("Illegal move"));
7007 if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
7008 if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
7009 ClearPremoveHighlights(); // was included
7010 else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
7014 if(addToBookFlag) { // adding moves to book
7015 char buf[MSG_SIZ], move[MSG_SIZ];
7016 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, move);
7017 snprintf(buf, MSG_SIZ, " 0.0%% 1 %s\n", move);
7019 addToBookFlag = FALSE;
7024 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
7027 /* Common tail of UserMoveEvent and DropMenuEvent */
7029 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
7033 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
7034 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
7035 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
7036 if(WhiteOnMove(currentMove)) {
7037 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
7039 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
7043 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
7044 move type in caller when we know the move is a legal promotion */
7045 if(moveType == NormalMove && promoChar)
7046 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
7048 /* [HGM] <popupFix> The following if has been moved here from
7049 UserMoveEvent(). Because it seemed to belong here (why not allow
7050 piece drops in training games?), and because it can only be
7051 performed after it is known to what we promote. */
7052 if (gameMode == Training) {
7053 /* compare the move played on the board to the next move in the
7054 * game. If they match, display the move and the opponent's response.
7055 * If they don't match, display an error message.
7059 CopyBoard(testBoard, boards[currentMove]);
7060 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
7062 if (CompareBoards(testBoard, boards[currentMove+1])) {
7063 ForwardInner(currentMove+1);
7065 /* Autoplay the opponent's response.
7066 * if appData.animate was TRUE when Training mode was entered,
7067 * the response will be animated.
7069 saveAnimate = appData.animate;
7070 appData.animate = animateTraining;
7071 ForwardInner(currentMove+1);
7072 appData.animate = saveAnimate;
7074 /* check for the end of the game */
7075 if (currentMove >= forwardMostMove) {
7076 gameMode = PlayFromGameFile;
7078 SetTrainingModeOff();
7079 DisplayInformation(_("End of game"));
7082 DisplayError(_("Incorrect move"), 0);
7087 /* Ok, now we know that the move is good, so we can kill
7088 the previous line in Analysis Mode */
7089 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
7090 && currentMove < forwardMostMove) {
7091 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
7092 else forwardMostMove = currentMove;
7097 /* If we need the chess program but it's dead, restart it */
7098 ResurrectChessProgram();
7100 /* A user move restarts a paused game*/
7104 thinkOutput[0] = NULLCHAR;
7106 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
7108 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
7109 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7113 if (gameMode == BeginningOfGame) {
7114 if (appData.noChessProgram) {
7115 gameMode = EditGame;
7119 gameMode = MachinePlaysBlack;
7122 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
7124 if (first.sendName) {
7125 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
7126 SendToProgram(buf, &first);
7133 /* Relay move to ICS or chess engine */
7134 if (appData.icsActive) {
7135 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
7136 gameMode == IcsExamining) {
7137 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7138 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7140 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7142 // also send plain move, in case ICS does not understand atomic claims
7143 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7147 if (first.sendTime && (gameMode == BeginningOfGame ||
7148 gameMode == MachinePlaysWhite ||
7149 gameMode == MachinePlaysBlack)) {
7150 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
7152 if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
7153 // [HGM] book: if program might be playing, let it use book
7154 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
7155 first.maybeThinking = TRUE;
7156 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
7157 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
7158 SendBoard(&first, currentMove+1);
7159 if(second.analyzing) {
7160 if(!second.useSetboard) SendToProgram("undo\n", &second);
7161 SendBoard(&second, currentMove+1);
7164 SendMoveToProgram(forwardMostMove-1, &first);
7165 if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
7167 if (currentMove == cmailOldMove + 1) {
7168 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7172 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7176 if(appData.testLegality)
7177 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
7183 if (WhiteOnMove(currentMove)) {
7184 GameEnds(BlackWins, "Black mates", GE_PLAYER);
7186 GameEnds(WhiteWins, "White mates", GE_PLAYER);
7190 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
7195 case MachinePlaysBlack:
7196 case MachinePlaysWhite:
7197 /* disable certain menu options while machine is thinking */
7198 SetMachineThinkingEnables();
7205 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
7206 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
7208 if(bookHit) { // [HGM] book: simulate book reply
7209 static char bookMove[MSG_SIZ]; // a bit generous?
7211 programStats.nodes = programStats.depth = programStats.time =
7212 programStats.score = programStats.got_only_move = 0;
7213 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7215 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7216 strcat(bookMove, bookHit);
7217 HandleMachineMove(bookMove, &first);
7223 MarkByFEN(char *fen)
7226 if(!appData.markers || !appData.highlightDragging) return;
7227 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) legal[r][f] = 0;
7228 r=BOARD_HEIGHT-1; f=BOARD_LEFT;
7232 if(*fen == 'M') legal[r][f] = 2; else // request promotion choice
7233 if(*fen >= 'A' && *fen <= 'Z') legal[r][f] = 1; else
7234 if(*fen >= 'a' && *fen <= 'z') *fen += 'A' - 'a';
7235 if(*fen == '/' && f > BOARD_LEFT) f = BOARD_LEFT, r--; else
7236 if(*fen == 'T') marker[r][f++] = 0; else
7237 if(*fen == 'Y') marker[r][f++] = 1; else
7238 if(*fen == 'G') marker[r][f++] = 3; else
7239 if(*fen == 'B') marker[r][f++] = 4; else
7240 if(*fen == 'C') marker[r][f++] = 5; else
7241 if(*fen == 'M') marker[r][f++] = 6; else
7242 if(*fen == 'W') marker[r][f++] = 7; else
7243 if(*fen == 'D') marker[r][f++] = 8; else
7244 if(*fen == 'R') marker[r][f++] = 2; else {
7245 while(*fen <= '9' && *fen >= '0') s = 10*s + *fen++ - '0';
7248 while(f >= BOARD_RGHT) f -= BOARD_RGHT - BOARD_LEFT, r--;
7252 DrawPosition(TRUE, NULL);
7255 static char baseMarker[BOARD_RANKS][BOARD_FILES], baseLegal[BOARD_RANKS][BOARD_FILES];
7258 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7260 typedef char Markers[BOARD_RANKS][BOARD_FILES];
7261 Markers *m = (Markers *) closure;
7262 if(rf == fromY && ff == fromX && (killX < 0 && !(rt == rf && ft == ff) || abs(ft-killX) < 2 && abs(rt-killY) < 2))
7263 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7264 || kind == WhiteCapturesEnPassant
7265 || kind == BlackCapturesEnPassant) + 3*(kind == FirstLeg && killX < 0), legal[rt][ft] = 1;
7266 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3, legal[rt][ft] = 1;
7269 static int hoverSavedValid;
7272 MarkTargetSquares (int clear)
7275 if(clear) { // no reason to ever suppress clearing
7276 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) sum += marker[y][x], marker[y][x] = 0;
7277 hoverSavedValid = 0;
7278 if(!sum) return; // nothing was cleared,no redraw needed
7281 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7282 !appData.testLegality && !pieceDefs || gameMode == EditPosition) return;
7283 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7284 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7285 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7287 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
7290 DrawPosition(FALSE, NULL);
7294 Explode (Board board, int fromX, int fromY, int toX, int toY)
7296 if(gameInfo.variant == VariantAtomic &&
7297 (board[toY][toX] != EmptySquare || // capture?
7298 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
7299 board[fromY][fromX] == BlackPawn )
7301 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7307 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7310 CanPromote (ChessSquare piece, int y)
7312 int zone = (gameInfo.variant == VariantChuChess ? 3 : 1);
7313 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7314 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7315 if(IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantXiangqi ||
7316 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
7317 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7318 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN) return FALSE;
7319 return (piece == BlackPawn && y <= zone ||
7320 piece == WhitePawn && y >= BOARD_HEIGHT-1-zone ||
7321 piece == BlackLance && y == 1 ||
7322 piece == WhiteLance && y == BOARD_HEIGHT-2 );
7326 HoverEvent (int xPix, int yPix, int x, int y)
7328 static int oldX = -1, oldY = -1, oldFromX = -1, oldFromY = -1;
7330 if(!first.highlight) return;
7331 if(fromX != oldFromX || fromY != oldFromY) oldX = oldY = -1; // kludge to fake entry on from-click
7332 if(x == oldX && y == oldY) return; // only do something if we enter new square
7333 oldFromX = fromX; oldFromY = fromY;
7334 if(oldX == -1 && oldY == -1 && x == fromX && y == fromY) { // record markings after from-change
7335 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7336 baseMarker[r][f] = marker[r][f], baseLegal[r][f] = legal[r][f];
7337 hoverSavedValid = 1;
7338 } else if(oldX != x || oldY != y) {
7339 // [HGM] lift: entered new to-square; redraw arrow, and inform engine
7340 if(hoverSavedValid) // don't restore markers that are supposed to be cleared
7341 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7342 marker[r][f] = baseMarker[r][f], legal[r][f] = baseLegal[r][f];
7343 if((marker[y][x] == 2 || marker[y][x] == 6) && legal[y][x]) {
7345 snprintf(buf, MSG_SIZ, "hover %c%d\n", x + AAA, y + ONE - '0');
7346 SendToProgram(buf, &first);
7349 // SetHighlights(fromX, fromY, x, y);
7353 void ReportClick(char *action, int x, int y)
7355 char buf[MSG_SIZ]; // Inform engine of what user does
7357 if(action[0] == 'l') // mark any target square of a lifted piece as legal to-square, clear markers
7358 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7359 legal[r][f] = !pieceDefs || !appData.markers, marker[r][f] = 0;
7360 if(!first.highlight || gameMode == EditPosition) return;
7361 snprintf(buf, MSG_SIZ, "%s %c%d%s\n", action, x+AAA, y+ONE-'0', controlKey && action[0]=='p' ? "," : "");
7362 SendToProgram(buf, &first);
7366 LeftClick (ClickType clickType, int xPix, int yPix)
7369 Boolean saveAnimate;
7370 static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0;
7371 char promoChoice = NULLCHAR;
7373 static TimeMark lastClickTime, prevClickTime;
7375 if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7377 prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7379 if (clickType == Press) ErrorPopDown();
7380 lastClickType = clickType, lastLeftX = xPix, lastLeftY = yPix; // [HGM] alien: remember state
7382 x = EventToSquare(xPix, BOARD_WIDTH);
7383 y = EventToSquare(yPix, BOARD_HEIGHT);
7384 if (!flipView && y >= 0) {
7385 y = BOARD_HEIGHT - 1 - y;
7387 if (flipView && x >= 0) {
7388 x = BOARD_WIDTH - 1 - x;
7391 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7392 defaultPromoChoice = promoSweep;
7393 promoSweep = EmptySquare; // terminate sweep
7394 promoDefaultAltered = TRUE;
7395 if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7398 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7399 if(clickType == Release) return; // ignore upclick of click-click destination
7400 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7401 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7402 if(gameInfo.holdingsWidth &&
7403 (WhiteOnMove(currentMove)
7404 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7405 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7406 // click in right holdings, for determining promotion piece
7407 ChessSquare p = boards[currentMove][y][x];
7408 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7409 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7410 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7411 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7416 DrawPosition(FALSE, boards[currentMove]);
7420 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7421 if(clickType == Press
7422 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7423 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7424 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7427 if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7428 // could be static click on premove from-square: abort premove
7430 ClearPremoveHighlights();
7433 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7434 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7436 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7437 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7438 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7439 defaultPromoChoice = DefaultPromoChoice(side);
7442 autoQueen = appData.alwaysPromoteToQueen;
7446 gatingPiece = EmptySquare;
7447 if (clickType != Press) {
7448 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7449 DragPieceEnd(xPix, yPix); dragging = 0;
7450 DrawPosition(FALSE, NULL);
7454 doubleClick = FALSE;
7455 if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7456 doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7458 fromX = x; fromY = y; toX = toY = killX = killY = -1;
7459 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7460 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7461 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7463 if (OKToStartUserMove(fromX, fromY)) {
7465 ReportClick("lift", x, y);
7466 MarkTargetSquares(0);
7467 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7468 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7469 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7470 promoSweep = defaultPromoChoice;
7471 selectFlag = 0; lastX = xPix; lastY = yPix;
7472 Sweep(0); // Pawn that is going to promote: preview promotion piece
7473 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7475 if (appData.highlightDragging) {
7476 SetHighlights(fromX, fromY, -1, -1);
7480 } else fromX = fromY = -1;
7486 if (clickType == Press && gameMode != EditPosition) {
7491 // ignore off-board to clicks
7492 if(y < 0 || x < 0) return;
7494 /* Check if clicking again on the same color piece */
7495 fromP = boards[currentMove][fromY][fromX];
7496 toP = boards[currentMove][y][x];
7497 frc = appData.fischerCastling || gameInfo.variant == VariantSChess;
7498 if( (killX < 0 || x != fromX || y != fromY) && // [HGM] lion: do not interpret igui as deselect!
7499 ((WhitePawn <= fromP && fromP <= WhiteKing &&
7500 WhitePawn <= toP && toP <= WhiteKing &&
7501 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7502 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7503 (BlackPawn <= fromP && fromP <= BlackKing &&
7504 BlackPawn <= toP && toP <= BlackKing &&
7505 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7506 !(fromP == BlackKing && toP == BlackRook && frc)))) {
7507 /* Clicked again on same color piece -- changed his mind */
7508 second = (x == fromX && y == fromY);
7510 if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7511 second = FALSE; // first double-click rather than scond click
7512 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7514 promoDefaultAltered = FALSE;
7515 MarkTargetSquares(1);
7516 if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
7517 if (appData.highlightDragging) {
7518 SetHighlights(x, y, -1, -1);
7522 if (OKToStartUserMove(x, y)) {
7523 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7524 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7525 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7526 gatingPiece = boards[currentMove][fromY][fromX];
7527 else gatingPiece = doubleClick ? fromP : EmptySquare;
7529 fromY = y; dragging = 1;
7530 ReportClick("lift", x, y);
7531 MarkTargetSquares(0);
7532 DragPieceBegin(xPix, yPix, FALSE);
7533 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7534 promoSweep = defaultPromoChoice;
7535 selectFlag = 0; lastX = xPix; lastY = yPix;
7536 Sweep(0); // Pawn that is going to promote: preview promotion piece
7540 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7543 // ignore clicks on holdings
7544 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7547 if (clickType == Release && x == fromX && y == fromY && killX < 0) {
7548 DragPieceEnd(xPix, yPix); dragging = 0;
7550 // a deferred attempt to click-click move an empty square on top of a piece
7551 boards[currentMove][y][x] = EmptySquare;
7553 DrawPosition(FALSE, boards[currentMove]);
7554 fromX = fromY = -1; clearFlag = 0;
7557 if (appData.animateDragging) {
7558 /* Undo animation damage if any */
7559 DrawPosition(FALSE, NULL);
7561 if (second || sweepSelecting) {
7562 /* Second up/down in same square; just abort move */
7563 if(sweepSelecting) DrawPosition(FALSE, boards[currentMove]);
7564 second = sweepSelecting = 0;
7566 gatingPiece = EmptySquare;
7567 MarkTargetSquares(1);
7570 ClearPremoveHighlights();
7572 /* First upclick in same square; start click-click mode */
7573 SetHighlights(x, y, -1, -1);
7580 if(gameMode != EditPosition && !appData.testLegality && !legal[y][x] &&
7581 fromX >= BOARD_LEFT && fromX < BOARD_RGHT && (x != killX || y != killY) && !sweepSelecting) {
7582 if(dragging) DragPieceEnd(xPix, yPix), dragging = 0;
7583 DisplayMessage(_("only marked squares are legal"),"");
7584 DrawPosition(TRUE, NULL);
7585 return; // ignore to-click
7588 /* we now have a different from- and (possibly off-board) to-square */
7589 /* Completed move */
7590 if(!sweepSelecting) {
7595 piece = boards[currentMove][fromY][fromX];
7597 saveAnimate = appData.animate;
7598 if (clickType == Press) {
7599 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7600 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7601 // must be Edit Position mode with empty-square selected
7602 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7603 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7606 if(dragging == 2) { // [HGM] lion: just turn buttonless drag into normal drag, and let release to the job
7609 if(x == killX && y == killY) { // second click on this square, which was selected as first-leg target
7610 killX = killY = -1; // this informs us no second leg is coming, so treat as to-click without intermediate
7612 if(marker[y][x] == 5) return; // [HGM] lion: to-click on cyan square; defer action to release
7613 if(legal[y][x] == 2 || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7614 if(appData.sweepSelect) {
7615 promoSweep = defaultPromoChoice;
7616 if(gameInfo.variant != VariantChuChess && PieceToChar(CHUPROMOTED piece) == '+') promoSweep = CHUPROMOTED piece;
7617 selectFlag = 0; lastX = xPix; lastY = yPix;
7618 Sweep(0); // Pawn that is going to promote: preview promotion piece
7620 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7621 MarkTargetSquares(1);
7623 return; // promo popup appears on up-click
7625 /* Finish clickclick move */
7626 if (appData.animate || appData.highlightLastMove) {
7627 SetHighlights(fromX, fromY, toX, toY);
7631 } else if(sweepSelecting) { // this must be the up-click corresponding to the down-click that started the sweep
7632 sweepSelecting = 0; appData.animate = FALSE; // do not animate, a selected piece already on to-square
7633 if (appData.animate || appData.highlightLastMove) {
7634 SetHighlights(fromX, fromY, toX, toY);
7640 // [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
7641 /* Finish drag move */
7642 if (appData.highlightLastMove) {
7643 SetHighlights(fromX, fromY, toX, toY);
7648 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7649 if(marker[y][x] == 5) { // [HGM] lion: this was the release of a to-click or drag on a cyan square
7650 dragging *= 2; // flag button-less dragging if we are dragging
7651 MarkTargetSquares(1);
7652 if(x == killX && y == killY) killX = killY = -1; else {
7653 killX = x; killY = y; //remeber this square as intermediate
7654 ReportClick("put", x, y); // and inform engine
7655 ReportClick("lift", x, y);
7656 MarkTargetSquares(0);
7660 DragPieceEnd(xPix, yPix); dragging = 0;
7661 /* Don't animate move and drag both */
7662 appData.animate = FALSE;
7665 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7666 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7667 ChessSquare piece = boards[currentMove][fromY][fromX];
7668 if(gameMode == EditPosition && piece != EmptySquare &&
7669 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7672 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7673 n = PieceToNumber(piece - (int)BlackPawn);
7674 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7675 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7676 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7678 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7679 n = PieceToNumber(piece);
7680 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7681 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7682 boards[currentMove][n][BOARD_WIDTH-2]++;
7684 boards[currentMove][fromY][fromX] = EmptySquare;
7688 MarkTargetSquares(1);
7689 DrawPosition(TRUE, boards[currentMove]);
7693 // off-board moves should not be highlighted
7694 if(x < 0 || y < 0) ClearHighlights();
7695 else ReportClick("put", x, y);
7697 if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7699 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7700 SetHighlights(fromX, fromY, toX, toY);
7701 MarkTargetSquares(1);
7702 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7703 // [HGM] super: promotion to captured piece selected from holdings
7704 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7705 promotionChoice = TRUE;
7706 // kludge follows to temporarily execute move on display, without promoting yet
7707 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7708 boards[currentMove][toY][toX] = p;
7709 DrawPosition(FALSE, boards[currentMove]);
7710 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7711 boards[currentMove][toY][toX] = q;
7712 DisplayMessage("Click in holdings to choose piece", "");
7715 PromotionPopUp(promoChoice);
7717 int oldMove = currentMove;
7718 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7719 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7720 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7721 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7722 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7723 DrawPosition(TRUE, boards[currentMove]);
7724 MarkTargetSquares(1);
7727 appData.animate = saveAnimate;
7728 if (appData.animate || appData.animateDragging) {
7729 /* Undo animation damage if needed */
7730 DrawPosition(FALSE, NULL);
7735 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7736 { // front-end-free part taken out of PieceMenuPopup
7737 int whichMenu; int xSqr, ySqr;
7739 if(seekGraphUp) { // [HGM] seekgraph
7740 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7741 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7745 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7746 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7747 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7748 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7749 if(action == Press) {
7750 originalFlip = flipView;
7751 flipView = !flipView; // temporarily flip board to see game from partners perspective
7752 DrawPosition(TRUE, partnerBoard);
7753 DisplayMessage(partnerStatus, "");
7755 } else if(action == Release) {
7756 flipView = originalFlip;
7757 DrawPosition(TRUE, boards[currentMove]);
7763 xSqr = EventToSquare(x, BOARD_WIDTH);
7764 ySqr = EventToSquare(y, BOARD_HEIGHT);
7765 if (action == Release) {
7766 if(pieceSweep != EmptySquare) {
7767 EditPositionMenuEvent(pieceSweep, toX, toY);
7768 pieceSweep = EmptySquare;
7769 } else UnLoadPV(); // [HGM] pv
7771 if (action != Press) return -2; // return code to be ignored
7774 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7776 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7777 if (xSqr < 0 || ySqr < 0) return -1;
7778 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7779 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7780 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7781 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7785 if(!appData.icsEngineAnalyze) return -1;
7786 case IcsPlayingWhite:
7787 case IcsPlayingBlack:
7788 if(!appData.zippyPlay) goto noZip;
7791 case MachinePlaysWhite:
7792 case MachinePlaysBlack:
7793 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7794 if (!appData.dropMenu) {
7796 return 2; // flag front-end to grab mouse events
7798 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7799 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7802 if (xSqr < 0 || ySqr < 0) return -1;
7803 if (!appData.dropMenu || appData.testLegality &&
7804 gameInfo.variant != VariantBughouse &&
7805 gameInfo.variant != VariantCrazyhouse) return -1;
7806 whichMenu = 1; // drop menu
7812 if (((*fromX = xSqr) < 0) ||
7813 ((*fromY = ySqr) < 0)) {
7814 *fromX = *fromY = -1;
7818 *fromX = BOARD_WIDTH - 1 - *fromX;
7820 *fromY = BOARD_HEIGHT - 1 - *fromY;
7826 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7828 // char * hint = lastHint;
7829 FrontEndProgramStats stats;
7831 stats.which = cps == &first ? 0 : 1;
7832 stats.depth = cpstats->depth;
7833 stats.nodes = cpstats->nodes;
7834 stats.score = cpstats->score;
7835 stats.time = cpstats->time;
7836 stats.pv = cpstats->movelist;
7837 stats.hint = lastHint;
7838 stats.an_move_index = 0;
7839 stats.an_move_count = 0;
7841 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7842 stats.hint = cpstats->move_name;
7843 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7844 stats.an_move_count = cpstats->nr_moves;
7847 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
7849 SetProgramStats( &stats );
7853 ClearEngineOutputPane (int which)
7855 static FrontEndProgramStats dummyStats;
7856 dummyStats.which = which;
7857 dummyStats.pv = "#";
7858 SetProgramStats( &dummyStats );
7861 #define MAXPLAYERS 500
7864 TourneyStandings (int display)
7866 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7867 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7868 char result, *p, *names[MAXPLAYERS];
7870 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7871 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7872 names[0] = p = strdup(appData.participants);
7873 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7875 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7877 while(result = appData.results[nr]) {
7878 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7879 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7880 wScore = bScore = 0;
7882 case '+': wScore = 2; break;
7883 case '-': bScore = 2; break;
7884 case '=': wScore = bScore = 1; break;
7886 case '*': return strdup("busy"); // tourney not finished
7894 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7895 for(w=0; w<nPlayers; w++) {
7897 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7898 ranking[w] = b; points[w] = bScore; score[b] = -2;
7900 p = malloc(nPlayers*34+1);
7901 for(w=0; w<nPlayers && w<display; w++)
7902 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7908 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7909 { // count all piece types
7911 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7912 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7913 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7916 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7917 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7918 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7919 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7920 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7921 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7926 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7928 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7929 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7931 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7932 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7933 if(myPawns == 2 && nMine == 3) // KPP
7934 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7935 if(myPawns == 1 && nMine == 2) // KP
7936 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7937 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7938 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7939 if(myPawns) return FALSE;
7940 if(pCnt[WhiteRook+side])
7941 return pCnt[BlackRook-side] ||
7942 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7943 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7944 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7945 if(pCnt[WhiteCannon+side]) {
7946 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7947 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7949 if(pCnt[WhiteKnight+side])
7950 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7955 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7957 VariantClass v = gameInfo.variant;
7959 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7960 if(v == VariantShatranj) return TRUE; // always winnable through baring
7961 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7962 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7964 if(v == VariantXiangqi) {
7965 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7967 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7968 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7969 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7970 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7971 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7972 if(stale) // we have at least one last-rank P plus perhaps C
7973 return majors // KPKX
7974 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7976 return pCnt[WhiteFerz+side] // KCAK
7977 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7978 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7979 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7981 } else if(v == VariantKnightmate) {
7982 if(nMine == 1) return FALSE;
7983 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
7984 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7985 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7987 if(nMine == 1) return FALSE; // bare King
7988 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
7989 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7990 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7991 // by now we have King + 1 piece (or multiple Bishops on the same color)
7992 if(pCnt[WhiteKnight+side])
7993 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7994 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7995 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7997 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7998 if(pCnt[WhiteAlfil+side])
7999 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
8000 if(pCnt[WhiteWazir+side])
8001 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
8008 CompareWithRights (Board b1, Board b2)
8011 if(!CompareBoards(b1, b2)) return FALSE;
8012 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
8013 /* compare castling rights */
8014 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
8015 rights++; /* King lost rights, while rook still had them */
8016 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
8017 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
8018 rights++; /* but at least one rook lost them */
8020 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
8022 if( b1[CASTLING][5] != NoRights ) {
8023 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
8030 Adjudicate (ChessProgramState *cps)
8031 { // [HGM] some adjudications useful with buggy engines
8032 // [HGM] adjudicate: made into separate routine, which now can be called after every move
8033 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
8034 // Actually ending the game is now based on the additional internal condition canAdjudicate.
8035 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
8036 int k, drop, count = 0; static int bare = 1;
8037 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
8038 Boolean canAdjudicate = !appData.icsActive;
8040 // most tests only when we understand the game, i.e. legality-checking on
8041 if( appData.testLegality )
8042 { /* [HGM] Some more adjudications for obstinate engines */
8043 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
8044 static int moveCount = 6;
8046 char *reason = NULL;
8048 /* Count what is on board. */
8049 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8051 /* Some material-based adjudications that have to be made before stalemate test */
8052 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
8053 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
8054 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
8055 if(canAdjudicate && appData.checkMates) {
8057 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8058 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
8059 "Xboard adjudication: King destroyed", GE_XBOARD );
8064 /* Bare King in Shatranj (loses) or Losers (wins) */
8065 if( nrW == 1 || nrB == 1) {
8066 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
8067 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
8068 if(canAdjudicate && appData.checkMates) {
8070 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
8071 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8072 "Xboard adjudication: Bare king", GE_XBOARD );
8076 if( gameInfo.variant == VariantShatranj && --bare < 0)
8078 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
8079 if(canAdjudicate && appData.checkMates) {
8080 /* but only adjudicate if adjudication enabled */
8082 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8083 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
8084 "Xboard adjudication: Bare king", GE_XBOARD );
8091 // don't wait for engine to announce game end if we can judge ourselves
8092 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8094 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
8095 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
8096 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
8097 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
8100 reason = "Xboard adjudication: 3rd check";
8101 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
8112 reason = "Xboard adjudication: Stalemate";
8113 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
8114 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
8115 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
8116 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
8117 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
8118 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
8119 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
8120 EP_CHECKMATE : EP_WINS);
8121 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
8122 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
8126 reason = "Xboard adjudication: Checkmate";
8127 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
8128 if(gameInfo.variant == VariantShogi) {
8129 if(forwardMostMove > backwardMostMove
8130 && moveList[forwardMostMove-1][1] == '@'
8131 && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
8132 reason = "XBoard adjudication: pawn-drop mate";
8133 boards[forwardMostMove][EP_STATUS] = EP_WINS;
8139 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
8141 result = GameIsDrawn; break;
8143 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
8145 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
8149 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
8151 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8152 GameEnds( result, reason, GE_XBOARD );
8156 /* Next absolutely insufficient mating material. */
8157 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
8158 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
8159 { /* includes KBK, KNK, KK of KBKB with like Bishops */
8161 /* always flag draws, for judging claims */
8162 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
8164 if(canAdjudicate && appData.materialDraws) {
8165 /* but only adjudicate them if adjudication enabled */
8166 if(engineOpponent) {
8167 SendToProgram("force\n", engineOpponent); // suppress reply
8168 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
8170 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
8175 /* Then some trivial draws (only adjudicate, cannot be claimed) */
8176 if(gameInfo.variant == VariantXiangqi ?
8177 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
8179 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
8180 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
8181 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
8182 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
8184 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
8185 { /* if the first 3 moves do not show a tactical win, declare draw */
8186 if(engineOpponent) {
8187 SendToProgram("force\n", engineOpponent); // suppress reply
8188 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8190 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
8193 } else moveCount = 6;
8196 // Repetition draws and 50-move rule can be applied independently of legality testing
8198 /* Check for rep-draws */
8200 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
8201 && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
8202 for(k = forwardMostMove-2;
8203 k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
8204 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
8205 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
8208 if(CompareBoards(boards[k], boards[forwardMostMove])) {
8209 /* compare castling rights */
8210 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
8211 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
8212 rights++; /* King lost rights, while rook still had them */
8213 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
8214 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
8215 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
8216 rights++; /* but at least one rook lost them */
8218 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
8219 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
8221 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
8222 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
8223 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
8226 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
8227 && appData.drawRepeats > 1) {
8228 /* adjudicate after user-specified nr of repeats */
8229 int result = GameIsDrawn;
8230 char *details = "XBoard adjudication: repetition draw";
8231 if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
8232 // [HGM] xiangqi: check for forbidden perpetuals
8233 int m, ourPerpetual = 1, hisPerpetual = 1;
8234 for(m=forwardMostMove; m>k; m-=2) {
8235 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
8236 ourPerpetual = 0; // the current mover did not always check
8237 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
8238 hisPerpetual = 0; // the opponent did not always check
8240 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
8241 ourPerpetual, hisPerpetual);
8242 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
8243 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8244 details = "Xboard adjudication: perpetual checking";
8246 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
8247 break; // (or we would have caught him before). Abort repetition-checking loop.
8249 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
8250 if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
8252 details = "Xboard adjudication: repetition";
8254 } else // it must be XQ
8255 // Now check for perpetual chases
8256 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
8257 hisPerpetual = PerpetualChase(k, forwardMostMove);
8258 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
8259 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
8260 static char resdet[MSG_SIZ];
8261 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8263 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
8265 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
8266 break; // Abort repetition-checking loop.
8268 // if neither of us is checking or chasing all the time, or both are, it is draw
8270 if(engineOpponent) {
8271 SendToProgram("force\n", engineOpponent); // suppress reply
8272 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8274 GameEnds( result, details, GE_XBOARD );
8277 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
8278 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
8282 /* Now we test for 50-move draws. Determine ply count */
8283 count = forwardMostMove;
8284 /* look for last irreversble move */
8285 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
8287 /* if we hit starting position, add initial plies */
8288 if( count == backwardMostMove )
8289 count -= initialRulePlies;
8290 count = forwardMostMove - count;
8291 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
8292 // adjust reversible move counter for checks in Xiangqi
8293 int i = forwardMostMove - count, inCheck = 0, lastCheck;
8294 if(i < backwardMostMove) i = backwardMostMove;
8295 while(i <= forwardMostMove) {
8296 lastCheck = inCheck; // check evasion does not count
8297 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
8298 if(inCheck || lastCheck) count--; // check does not count
8303 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8304 /* this is used to judge if draw claims are legal */
8305 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
8306 if(engineOpponent) {
8307 SendToProgram("force\n", engineOpponent); // suppress reply
8308 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8310 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
8314 /* if draw offer is pending, treat it as a draw claim
8315 * when draw condition present, to allow engines a way to
8316 * claim draws before making their move to avoid a race
8317 * condition occurring after their move
8319 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
8321 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
8322 p = "Draw claim: 50-move rule";
8323 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
8324 p = "Draw claim: 3-fold repetition";
8325 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
8326 p = "Draw claim: insufficient mating material";
8327 if( p != NULL && canAdjudicate) {
8328 if(engineOpponent) {
8329 SendToProgram("force\n", engineOpponent); // suppress reply
8330 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8332 GameEnds( GameIsDrawn, p, GE_XBOARD );
8337 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
8338 if(engineOpponent) {
8339 SendToProgram("force\n", engineOpponent); // suppress reply
8340 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8342 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
8348 typedef int (CDECL *PPROBE_EGBB) (int player, int *piece, int *square);
8349 typedef int (CDECL *PLOAD_EGBB) (char *path, int cache_size, int load_options);
8350 static int egbbCode[] = { 6, 5, 4, 3, 2, 1 };
8355 int pieces[10], squares[10], cnt=0, r, f, res;
8357 static PPROBE_EGBB probeBB;
8358 if(!appData.testLegality) return 10;
8359 if(BOARD_HEIGHT != 8 || BOARD_RGHT-BOARD_LEFT != 8) return 12;
8360 if(gameInfo.holdingsSize && gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess) return 12;
8361 if(loaded == 2 && forwardMostMove < 2) loaded = 0; // retry on new game
8362 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8363 ChessSquare piece = boards[forwardMostMove][r][f];
8364 int black = (piece >= BlackPawn);
8365 int type = piece - black*BlackPawn;
8366 if(piece == EmptySquare) continue;
8367 if(type != WhiteKing && type > WhiteQueen) return 12; // unorthodox piece
8368 if(type == WhiteKing) type = WhiteQueen + 1;
8369 type = egbbCode[type];
8370 squares[cnt] = r*(BOARD_RGHT - BOARD_LEFT) + f - BOARD_LEFT;
8371 pieces[cnt] = type + black*6;
8372 if(++cnt > 5) return 11;
8374 pieces[cnt] = squares[cnt] = 0;
8376 if(loaded == 2) return 13; // loading failed before
8378 char *p, *path = strstr(appData.egtFormats, "scorpio:"), buf[MSG_SIZ];
8381 loaded = 2; // prepare for failure
8382 if(!path) return 13; // no egbb installed
8383 strncpy(buf, path + 8, MSG_SIZ);
8384 if(p = strchr(buf, ',')) *p = NULLCHAR; else p = buf + strlen(buf);
8385 snprintf(p, MSG_SIZ - strlen(buf), "%c%s", SLASH, EGBB_NAME);
8386 lib = LoadLibrary(buf);
8387 if(!lib) { DisplayError(_("could not load EGBB library"), 0); return 13; }
8388 loadBB = (PLOAD_EGBB) GetProcAddress(lib, "load_egbb_xmen");
8389 probeBB = (PPROBE_EGBB) GetProcAddress(lib, "probe_egbb_xmen");
8390 if(!loadBB || !probeBB) { DisplayError(_("wrong EGBB version"), 0); return 13; }
8391 p[1] = NULLCHAR; loadBB(buf, 64*1028, 2); // 2 = SMART_LOAD
8392 loaded = 1; // success!
8394 res = probeBB(forwardMostMove & 1, pieces, squares);
8395 return res > 0 ? 1 : res < 0 ? -1 : 0;
8399 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8400 { // [HGM] book: this routine intercepts moves to simulate book replies
8401 char *bookHit = NULL;
8403 if(cps->drawDepth && BitbaseProbe() == 0) { // [HG} egbb: reduce depth in drawn position
8405 snprintf(buf, MSG_SIZ, "sd %d\n", cps->drawDepth);
8406 SendToProgram(buf, cps);
8408 //first determine if the incoming move brings opponent into his book
8409 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8410 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8411 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8412 if(bookHit != NULL && !cps->bookSuspend) {
8413 // make sure opponent is not going to reply after receiving move to book position
8414 SendToProgram("force\n", cps);
8415 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8417 if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
8418 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8419 // now arrange restart after book miss
8421 // after a book hit we never send 'go', and the code after the call to this routine
8422 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8423 char buf[MSG_SIZ], *move = bookHit;
8425 int fromX, fromY, toX, toY;
8429 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8430 &fromX, &fromY, &toX, &toY, &promoChar)) {
8431 (void) CoordsToAlgebraic(boards[forwardMostMove],
8432 PosFlags(forwardMostMove),
8433 fromY, fromX, toY, toX, promoChar, move);
8435 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8439 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8440 SendToProgram(buf, cps);
8441 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8442 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8443 SendToProgram("go\n", cps);
8444 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8445 } else { // 'go' might be sent based on 'firstMove' after this routine returns
8446 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8447 SendToProgram("go\n", cps);
8448 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8450 return bookHit; // notify caller of hit, so it can take action to send move to opponent
8454 LoadError (char *errmess, ChessProgramState *cps)
8455 { // unloads engine and switches back to -ncp mode if it was first
8456 if(cps->initDone) return FALSE;
8457 cps->isr = NULL; // this should suppress further error popups from breaking pipes
8458 DestroyChildProcess(cps->pr, 9 ); // just to be sure
8461 appData.noChessProgram = TRUE;
8462 gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8463 gameMode = BeginningOfGame; ModeHighlight();
8466 if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8467 DisplayMessage("", ""); // erase waiting message
8468 if(errmess) DisplayError(errmess, 0); // announce reason, if given
8473 ChessProgramState *savedState;
8475 DeferredBookMove (void)
8477 if(savedState->lastPing != savedState->lastPong)
8478 ScheduleDelayedEvent(DeferredBookMove, 10);
8480 HandleMachineMove(savedMessage, savedState);
8483 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8484 static ChessProgramState *stalledEngine;
8485 static char stashedInputMove[MSG_SIZ];
8488 HandleMachineMove (char *message, ChessProgramState *cps)
8490 static char firstLeg[20];
8491 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8492 char realname[MSG_SIZ];
8493 int fromX, fromY, toX, toY;
8495 char promoChar, roar;
8497 int machineWhite, oldError;
8500 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8501 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8502 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8503 DisplayError(_("Invalid pairing from pairing engine"), 0);
8506 pairingReceived = 1;
8508 return; // Skim the pairing messages here.
8511 oldError = cps->userError; cps->userError = 0;
8513 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8515 * Kludge to ignore BEL characters
8517 while (*message == '\007') message++;
8520 * [HGM] engine debug message: ignore lines starting with '#' character
8522 if(cps->debug && *message == '#') return;
8525 * Look for book output
8527 if (cps == &first && bookRequested) {
8528 if (message[0] == '\t' || message[0] == ' ') {
8529 /* Part of the book output is here; append it */
8530 strcat(bookOutput, message);
8531 strcat(bookOutput, " \n");
8533 } else if (bookOutput[0] != NULLCHAR) {
8534 /* All of book output has arrived; display it */
8535 char *p = bookOutput;
8536 while (*p != NULLCHAR) {
8537 if (*p == '\t') *p = ' ';
8540 DisplayInformation(bookOutput);
8541 bookRequested = FALSE;
8542 /* Fall through to parse the current output */
8547 * Look for machine move.
8549 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8550 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8552 if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8553 if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8554 safeStrCpy(stashedInputMove, message, MSG_SIZ);
8555 stalledEngine = cps;
8556 if(appData.ponderNextMove) { // bring opponent out of ponder
8557 if(gameMode == TwoMachinesPlay) {
8558 if(cps->other->pause)
8559 PauseEngine(cps->other);
8561 SendToProgram("easy\n", cps->other);
8568 /* This method is only useful on engines that support ping */
8569 if (cps->lastPing != cps->lastPong) {
8570 if (gameMode == BeginningOfGame) {
8571 /* Extra move from before last new; ignore */
8572 if (appData.debugMode) {
8573 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8576 if (appData.debugMode) {
8577 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8578 cps->which, gameMode);
8581 SendToProgram("undo\n", cps);
8587 case BeginningOfGame:
8588 /* Extra move from before last reset; ignore */
8589 if (appData.debugMode) {
8590 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8597 /* Extra move after we tried to stop. The mode test is
8598 not a reliable way of detecting this problem, but it's
8599 the best we can do on engines that don't support ping.
8601 if (appData.debugMode) {
8602 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8603 cps->which, gameMode);
8605 SendToProgram("undo\n", cps);
8608 case MachinePlaysWhite:
8609 case IcsPlayingWhite:
8610 machineWhite = TRUE;
8613 case MachinePlaysBlack:
8614 case IcsPlayingBlack:
8615 machineWhite = FALSE;
8618 case TwoMachinesPlay:
8619 machineWhite = (cps->twoMachinesColor[0] == 'w');
8622 if (WhiteOnMove(forwardMostMove) != machineWhite) {
8623 if (appData.debugMode) {
8625 "Ignoring move out of turn by %s, gameMode %d"
8626 ", forwardMost %d\n",
8627 cps->which, gameMode, forwardMostMove);
8632 if(cps->alphaRank) AlphaRank(machineMove, 4);
8634 // [HGM] lion: (some very limited) support for Alien protocol
8636 if(machineMove[strlen(machineMove)-1] == ',') { // move ends in coma: non-final leg of composite move
8637 safeStrCpy(firstLeg, machineMove, 20); // just remember it for processing when second leg arrives
8639 } else if(firstLeg[0]) { // there was a previous leg;
8640 // only support case where same piece makes two step (and don't even test that!)
8641 char buf[20], *p = machineMove+1, *q = buf+1, f;
8642 safeStrCpy(buf, machineMove, 20);
8643 while(isdigit(*q)) q++; // find start of to-square
8644 safeStrCpy(machineMove, firstLeg, 20);
8645 while(isdigit(*p)) p++;
8646 safeStrCpy(p, q, 20); // glue to-square of second leg to from-square of first, to process over-all move
8647 sscanf(buf, "%c%d", &f, &killY); killX = f - AAA; killY -= ONE - '0'; // pass intermediate square to MakeMove in global
8648 firstLeg[0] = NULLCHAR;
8651 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
8652 &fromX, &fromY, &toX, &toY, &promoChar)) {
8653 /* Machine move could not be parsed; ignore it. */
8654 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
8655 machineMove, _(cps->which));
8656 DisplayMoveError(buf1);
8657 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c via %c%c) res=%d",
8658 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, killX+AAA, killY+ONE, moveType);
8659 if (gameMode == TwoMachinesPlay) {
8660 GameEnds(machineWhite ? BlackWins : WhiteWins,
8666 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
8667 /* So we have to redo legality test with true e.p. status here, */
8668 /* to make sure an illegal e.p. capture does not slip through, */
8669 /* to cause a forfeit on a justified illegal-move complaint */
8670 /* of the opponent. */
8671 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
8673 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
8674 fromY, fromX, toY, toX, promoChar);
8675 if(moveType == IllegalMove) {
8676 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
8677 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
8678 GameEnds(machineWhite ? BlackWins : WhiteWins,
8681 } else if(!appData.fischerCastling)
8682 /* [HGM] Kludge to handle engines that send FRC-style castling
8683 when they shouldn't (like TSCP-Gothic) */
8685 case WhiteASideCastleFR:
8686 case BlackASideCastleFR:
8688 currentMoveString[2]++;
8690 case WhiteHSideCastleFR:
8691 case BlackHSideCastleFR:
8693 currentMoveString[2]--;
8695 default: ; // nothing to do, but suppresses warning of pedantic compilers
8698 hintRequested = FALSE;
8699 lastHint[0] = NULLCHAR;
8700 bookRequested = FALSE;
8701 /* Program may be pondering now */
8702 cps->maybeThinking = TRUE;
8703 if (cps->sendTime == 2) cps->sendTime = 1;
8704 if (cps->offeredDraw) cps->offeredDraw--;
8706 /* [AS] Save move info*/
8707 pvInfoList[ forwardMostMove ].score = programStats.score;
8708 pvInfoList[ forwardMostMove ].depth = programStats.depth;
8709 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
8711 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
8713 /* Test suites abort the 'game' after one move */
8714 if(*appData.finger) {
8716 char *fen = PositionToFEN(backwardMostMove, NULL, 0); // no counts in EPD
8717 if(!f) f = fopen(appData.finger, "w");
8718 if(f) fprintf(f, "%s bm %s;\n", fen, parseList[backwardMostMove]), fflush(f);
8719 else { DisplayFatalError("Bad output file", errno, 0); return; }
8721 GameEnds(GameUnfinished, NULL, GE_XBOARD);
8724 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
8725 if( gameMode == TwoMachinesPlay && appData.adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
8728 while( count < adjudicateLossPlies ) {
8729 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
8732 score = -score; /* Flip score for winning side */
8735 if( score > appData.adjudicateLossThreshold ) {
8742 if( count >= adjudicateLossPlies ) {
8743 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8745 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8746 "Xboard adjudication",
8753 if(Adjudicate(cps)) {
8754 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8755 return; // [HGM] adjudicate: for all automatic game ends
8759 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8761 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8762 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8764 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8766 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8768 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8769 char buf[3*MSG_SIZ];
8771 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8772 programStats.score / 100.,
8774 programStats.time / 100.,
8775 (unsigned int)programStats.nodes,
8776 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8777 programStats.movelist);
8783 /* [AS] Clear stats for next move */
8784 ClearProgramStats();
8785 thinkOutput[0] = NULLCHAR;
8786 hiddenThinkOutputState = 0;
8789 if (gameMode == TwoMachinesPlay) {
8790 /* [HGM] relaying draw offers moved to after reception of move */
8791 /* and interpreting offer as claim if it brings draw condition */
8792 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8793 SendToProgram("draw\n", cps->other);
8795 if (cps->other->sendTime) {
8796 SendTimeRemaining(cps->other,
8797 cps->other->twoMachinesColor[0] == 'w');
8799 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8800 if (firstMove && !bookHit) {
8802 if (cps->other->useColors) {
8803 SendToProgram(cps->other->twoMachinesColor, cps->other);
8805 SendToProgram("go\n", cps->other);
8807 cps->other->maybeThinking = TRUE;
8810 roar = (killX >= 0 && IS_LION(boards[forwardMostMove][toY][toX]));
8812 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8814 if (!pausing && appData.ringBellAfterMoves) {
8815 if(!roar) RingBell();
8819 * Reenable menu items that were disabled while
8820 * machine was thinking
8822 if (gameMode != TwoMachinesPlay)
8823 SetUserThinkingEnables();
8825 // [HGM] book: after book hit opponent has received move and is now in force mode
8826 // force the book reply into it, and then fake that it outputted this move by jumping
8827 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8829 static char bookMove[MSG_SIZ]; // a bit generous?
8831 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8832 strcat(bookMove, bookHit);
8835 programStats.nodes = programStats.depth = programStats.time =
8836 programStats.score = programStats.got_only_move = 0;
8837 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8839 if(cps->lastPing != cps->lastPong) {
8840 savedMessage = message; // args for deferred call
8842 ScheduleDelayedEvent(DeferredBookMove, 10);
8851 /* Set special modes for chess engines. Later something general
8852 * could be added here; for now there is just one kludge feature,
8853 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8854 * when "xboard" is given as an interactive command.
8856 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8857 cps->useSigint = FALSE;
8858 cps->useSigterm = FALSE;
8860 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8861 ParseFeatures(message+8, cps);
8862 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8865 if (!strncmp(message, "setup ", 6) &&
8866 (!appData.testLegality || gameInfo.variant == VariantFairy || gameInfo.variant == VariantUnknown ||
8867 NonStandardBoardSize(gameInfo.variant, gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize))
8868 ) { // [HGM] allow first engine to define opening position
8869 int dummy, w, h, hand, s=6; char buf[MSG_SIZ], varName[MSG_SIZ];
8870 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8872 if(sscanf(message, "setup (%s", buf) == 1) {
8873 s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8874 ASSIGN(appData.pieceToCharTable, buf);
8876 if(startedFromSetupPosition) return;
8877 dummy = sscanf(message+s, "%dx%d+%d_%s", &w, &h, &hand, varName);
8879 while(message[s] && message[s++] != ' ');
8880 if(BOARD_HEIGHT != h || BOARD_WIDTH != w + 4*(hand != 0) || gameInfo.holdingsSize != hand ||
8881 dummy == 4 && gameInfo.variant != StringToVariant(varName) ) { // engine wants to change board format or variant
8882 appData.NrFiles = w; appData.NrRanks = h; appData.holdingsSize = hand;
8883 if(dummy == 4) gameInfo.variant = StringToVariant(varName); // parent variant
8884 InitPosition(1); // calls InitDrawingSizes to let new parameters take effect
8885 if(*buf) SetCharTable(pieceToChar, buf); // do again, for it was spoiled by InitPosition
8888 ParseFEN(boards[0], &dummy, message+s, FALSE);
8889 DrawPosition(TRUE, boards[0]);
8890 startedFromSetupPosition = TRUE;
8893 if(sscanf(message, "piece %s %s", buf2, buf1) == 2) {
8894 ChessSquare piece = WhitePawn;
8896 if(cps != &first || appData.testLegality) return;
8897 if(*p == '+') piece = CHUPROMOTED WhitePawn, p++;
8898 piece += CharToPiece(*p) - WhitePawn;
8899 if(piece < EmptySquare) {
8901 ASSIGN(pieceDesc[piece], buf1);
8902 if(isupper(*p) && p[1] == '&') { ASSIGN(pieceDesc[WHITE_TO_BLACK piece], buf1); }
8906 /* [HGM] Allow engine to set up a position. Don't ask me why one would
8907 * want this, I was asked to put it in, and obliged.
8909 if (!strncmp(message, "setboard ", 9)) {
8910 Board initial_position;
8912 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8914 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9, FALSE)) {
8915 DisplayError(_("Bad FEN received from engine"), 0);
8919 CopyBoard(boards[0], initial_position);
8920 initialRulePlies = FENrulePlies;
8921 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8922 else gameMode = MachinePlaysBlack;
8923 DrawPosition(FALSE, boards[currentMove]);
8929 * Look for communication commands
8931 if (!strncmp(message, "telluser ", 9)) {
8932 if(message[9] == '\\' && message[10] == '\\')
8933 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8935 DisplayNote(message + 9);
8938 if (!strncmp(message, "tellusererror ", 14)) {
8940 if(message[14] == '\\' && message[15] == '\\')
8941 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8943 DisplayError(message + 14, 0);
8946 if (!strncmp(message, "tellopponent ", 13)) {
8947 if (appData.icsActive) {
8949 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8953 DisplayNote(message + 13);
8957 if (!strncmp(message, "tellothers ", 11)) {
8958 if (appData.icsActive) {
8960 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8963 } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
8966 if (!strncmp(message, "tellall ", 8)) {
8967 if (appData.icsActive) {
8969 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
8973 DisplayNote(message + 8);
8977 if (strncmp(message, "warning", 7) == 0) {
8978 /* Undocumented feature, use tellusererror in new code */
8979 DisplayError(message, 0);
8982 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
8983 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
8984 strcat(realname, " query");
8985 AskQuestion(realname, buf2, buf1, cps->pr);
8988 /* Commands from the engine directly to ICS. We don't allow these to be
8989 * sent until we are logged on. Crafty kibitzes have been known to
8990 * interfere with the login process.
8993 if (!strncmp(message, "tellics ", 8)) {
8994 SendToICS(message + 8);
8998 if (!strncmp(message, "tellicsnoalias ", 15)) {
8999 SendToICS(ics_prefix);
9000 SendToICS(message + 15);
9004 /* The following are for backward compatibility only */
9005 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
9006 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
9007 SendToICS(ics_prefix);
9013 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
9014 if(initPing == cps->lastPong) {
9015 if(gameInfo.variant == VariantUnknown) {
9016 DisplayError(_("Engine did not send setup for non-standard variant"), 0);
9017 *engineVariant = NULLCHAR; appData.variant = VariantNormal; // back to normal as error recovery?
9018 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9024 if(!strncmp(message, "highlight ", 10)) {
9025 if(appData.testLegality && appData.markers) return;
9026 MarkByFEN(message+10); // [HGM] alien: allow engine to mark board squares
9029 if(!strncmp(message, "click ", 6)) {
9030 char f, c=0; int x, y; // [HGM] alien: allow engine to finish user moves (i.e. engine-driven one-click moving)
9031 if(appData.testLegality || !appData.oneClick) return;
9032 sscanf(message+6, "%c%d%c", &f, &y, &c);
9033 x = f - 'a' + BOARD_LEFT, y -= ONE - '0';
9034 if(flipView) x = BOARD_WIDTH-1 - x; else y = BOARD_HEIGHT-1 - y;
9035 x = x*squareSize + (x+1)*lineGap + squareSize/2;
9036 y = y*squareSize + (y+1)*lineGap + squareSize/2;
9037 f = first.highlight; first.highlight = 0; // kludge to suppress lift/put in response to own clicks
9038 if(lastClickType == Press) // if button still down, fake release on same square, to be ready for next click
9039 LeftClick(Release, lastLeftX, lastLeftY);
9040 controlKey = (c == ',');
9041 LeftClick(Press, x, y);
9042 LeftClick(Release, x, y);
9043 first.highlight = f;
9047 * If the move is illegal, cancel it and redraw the board.
9048 * Also deal with other error cases. Matching is rather loose
9049 * here to accommodate engines written before the spec.
9051 if (strncmp(message + 1, "llegal move", 11) == 0 ||
9052 strncmp(message, "Error", 5) == 0) {
9053 if (StrStr(message, "name") ||
9054 StrStr(message, "rating") || StrStr(message, "?") ||
9055 StrStr(message, "result") || StrStr(message, "board") ||
9056 StrStr(message, "bk") || StrStr(message, "computer") ||
9057 StrStr(message, "variant") || StrStr(message, "hint") ||
9058 StrStr(message, "random") || StrStr(message, "depth") ||
9059 StrStr(message, "accepted")) {
9062 if (StrStr(message, "protover")) {
9063 /* Program is responding to input, so it's apparently done
9064 initializing, and this error message indicates it is
9065 protocol version 1. So we don't need to wait any longer
9066 for it to initialize and send feature commands. */
9067 FeatureDone(cps, 1);
9068 cps->protocolVersion = 1;
9071 cps->maybeThinking = FALSE;
9073 if (StrStr(message, "draw")) {
9074 /* Program doesn't have "draw" command */
9075 cps->sendDrawOffers = 0;
9078 if (cps->sendTime != 1 &&
9079 (StrStr(message, "time") || StrStr(message, "otim"))) {
9080 /* Program apparently doesn't have "time" or "otim" command */
9084 if (StrStr(message, "analyze")) {
9085 cps->analysisSupport = FALSE;
9086 cps->analyzing = FALSE;
9087 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
9088 EditGameEvent(); // [HGM] try to preserve loaded game
9089 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
9090 DisplayError(buf2, 0);
9093 if (StrStr(message, "(no matching move)st")) {
9094 /* Special kludge for GNU Chess 4 only */
9095 cps->stKludge = TRUE;
9096 SendTimeControl(cps, movesPerSession, timeControl,
9097 timeIncrement, appData.searchDepth,
9101 if (StrStr(message, "(no matching move)sd")) {
9102 /* Special kludge for GNU Chess 4 only */
9103 cps->sdKludge = TRUE;
9104 SendTimeControl(cps, movesPerSession, timeControl,
9105 timeIncrement, appData.searchDepth,
9109 if (!StrStr(message, "llegal")) {
9112 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9113 gameMode == IcsIdle) return;
9114 if (forwardMostMove <= backwardMostMove) return;
9115 if (pausing) PauseEvent();
9116 if(appData.forceIllegal) {
9117 // [HGM] illegal: machine refused move; force position after move into it
9118 SendToProgram("force\n", cps);
9119 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
9120 // we have a real problem now, as SendBoard will use the a2a3 kludge
9121 // when black is to move, while there might be nothing on a2 or black
9122 // might already have the move. So send the board as if white has the move.
9123 // But first we must change the stm of the engine, as it refused the last move
9124 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
9125 if(WhiteOnMove(forwardMostMove)) {
9126 SendToProgram("a7a6\n", cps); // for the engine black still had the move
9127 SendBoard(cps, forwardMostMove); // kludgeless board
9129 SendToProgram("a2a3\n", cps); // for the engine white still had the move
9130 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9131 SendBoard(cps, forwardMostMove+1); // kludgeless board
9133 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
9134 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
9135 gameMode == TwoMachinesPlay)
9136 SendToProgram("go\n", cps);
9139 if (gameMode == PlayFromGameFile) {
9140 /* Stop reading this game file */
9141 gameMode = EditGame;
9144 /* [HGM] illegal-move claim should forfeit game when Xboard */
9145 /* only passes fully legal moves */
9146 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
9147 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9148 "False illegal-move claim", GE_XBOARD );
9149 return; // do not take back move we tested as valid
9151 currentMove = forwardMostMove-1;
9152 DisplayMove(currentMove-1); /* before DisplayMoveError */
9153 SwitchClocks(forwardMostMove-1); // [HGM] race
9154 DisplayBothClocks();
9155 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
9156 parseList[currentMove], _(cps->which));
9157 DisplayMoveError(buf1);
9158 DrawPosition(FALSE, boards[currentMove]);
9160 SetUserThinkingEnables();
9163 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
9164 /* Program has a broken "time" command that
9165 outputs a string not ending in newline.
9169 if (cps->pseudo) { // [HGM] pseudo-engine, granted unusual powers
9170 if (sscanf(message, "wtime %ld\n", &whiteTimeRemaining) == 1 || // adjust clock times
9171 sscanf(message, "btime %ld\n", &blackTimeRemaining) == 1 ) return;
9175 * If chess program startup fails, exit with an error message.
9176 * Attempts to recover here are futile. [HGM] Well, we try anyway
9178 if ((StrStr(message, "unknown host") != NULL)
9179 || (StrStr(message, "No remote directory") != NULL)
9180 || (StrStr(message, "not found") != NULL)
9181 || (StrStr(message, "No such file") != NULL)
9182 || (StrStr(message, "can't alloc") != NULL)
9183 || (StrStr(message, "Permission denied") != NULL)) {
9185 cps->maybeThinking = FALSE;
9186 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
9187 _(cps->which), cps->program, cps->host, message);
9188 RemoveInputSource(cps->isr);
9189 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
9190 if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
9191 if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
9197 * Look for hint output
9199 if (sscanf(message, "Hint: %s", buf1) == 1) {
9200 if (cps == &first && hintRequested) {
9201 hintRequested = FALSE;
9202 if (ParseOneMove(buf1, forwardMostMove, &moveType,
9203 &fromX, &fromY, &toX, &toY, &promoChar)) {
9204 (void) CoordsToAlgebraic(boards[forwardMostMove],
9205 PosFlags(forwardMostMove),
9206 fromY, fromX, toY, toX, promoChar, buf1);
9207 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
9208 DisplayInformation(buf2);
9210 /* Hint move could not be parsed!? */
9211 snprintf(buf2, sizeof(buf2),
9212 _("Illegal hint move \"%s\"\nfrom %s chess program"),
9213 buf1, _(cps->which));
9214 DisplayError(buf2, 0);
9217 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
9223 * Ignore other messages if game is not in progress
9225 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9226 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
9229 * look for win, lose, draw, or draw offer
9231 if (strncmp(message, "1-0", 3) == 0) {
9232 char *p, *q, *r = "";
9233 p = strchr(message, '{');
9241 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
9243 } else if (strncmp(message, "0-1", 3) == 0) {
9244 char *p, *q, *r = "";
9245 p = strchr(message, '{');
9253 /* Kludge for Arasan 4.1 bug */
9254 if (strcmp(r, "Black resigns") == 0) {
9255 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
9258 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
9260 } else if (strncmp(message, "1/2", 3) == 0) {
9261 char *p, *q, *r = "";
9262 p = strchr(message, '{');
9271 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
9274 } else if (strncmp(message, "White resign", 12) == 0) {
9275 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9277 } else if (strncmp(message, "Black resign", 12) == 0) {
9278 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9280 } else if (strncmp(message, "White matches", 13) == 0 ||
9281 strncmp(message, "Black matches", 13) == 0 ) {
9282 /* [HGM] ignore GNUShogi noises */
9284 } else if (strncmp(message, "White", 5) == 0 &&
9285 message[5] != '(' &&
9286 StrStr(message, "Black") == NULL) {
9287 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9289 } else if (strncmp(message, "Black", 5) == 0 &&
9290 message[5] != '(') {
9291 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9293 } else if (strcmp(message, "resign") == 0 ||
9294 strcmp(message, "computer resigns") == 0) {
9296 case MachinePlaysBlack:
9297 case IcsPlayingBlack:
9298 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
9300 case MachinePlaysWhite:
9301 case IcsPlayingWhite:
9302 GameEnds(BlackWins, "White resigns", GE_ENGINE);
9304 case TwoMachinesPlay:
9305 if (cps->twoMachinesColor[0] == 'w')
9306 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9308 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9315 } else if (strncmp(message, "opponent mates", 14) == 0) {
9317 case MachinePlaysBlack:
9318 case IcsPlayingBlack:
9319 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9321 case MachinePlaysWhite:
9322 case IcsPlayingWhite:
9323 GameEnds(BlackWins, "Black mates", GE_ENGINE);
9325 case TwoMachinesPlay:
9326 if (cps->twoMachinesColor[0] == 'w')
9327 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9329 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9336 } else if (strncmp(message, "computer mates", 14) == 0) {
9338 case MachinePlaysBlack:
9339 case IcsPlayingBlack:
9340 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
9342 case MachinePlaysWhite:
9343 case IcsPlayingWhite:
9344 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9346 case TwoMachinesPlay:
9347 if (cps->twoMachinesColor[0] == 'w')
9348 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9350 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9357 } else if (strncmp(message, "checkmate", 9) == 0) {
9358 if (WhiteOnMove(forwardMostMove)) {
9359 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9361 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9364 } else if (strstr(message, "Draw") != NULL ||
9365 strstr(message, "game is a draw") != NULL) {
9366 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
9368 } else if (strstr(message, "offer") != NULL &&
9369 strstr(message, "draw") != NULL) {
9371 if (appData.zippyPlay && first.initDone) {
9372 /* Relay offer to ICS */
9373 SendToICS(ics_prefix);
9374 SendToICS("draw\n");
9377 cps->offeredDraw = 2; /* valid until this engine moves twice */
9378 if (gameMode == TwoMachinesPlay) {
9379 if (cps->other->offeredDraw) {
9380 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9381 /* [HGM] in two-machine mode we delay relaying draw offer */
9382 /* until after we also have move, to see if it is really claim */
9384 } else if (gameMode == MachinePlaysWhite ||
9385 gameMode == MachinePlaysBlack) {
9386 if (userOfferedDraw) {
9387 DisplayInformation(_("Machine accepts your draw offer"));
9388 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9390 DisplayInformation(_("Machine offers a draw.\nSelect Action / Draw to accept."));
9397 * Look for thinking output
9399 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
9400 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9402 int plylev, mvleft, mvtot, curscore, time;
9403 char mvname[MOVE_LEN];
9407 int prefixHint = FALSE;
9408 mvname[0] = NULLCHAR;
9411 case MachinePlaysBlack:
9412 case IcsPlayingBlack:
9413 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9415 case MachinePlaysWhite:
9416 case IcsPlayingWhite:
9417 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9422 case IcsObserving: /* [DM] icsEngineAnalyze */
9423 if (!appData.icsEngineAnalyze) ignore = TRUE;
9425 case TwoMachinesPlay:
9426 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
9436 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
9438 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9439 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
9441 if(nodes>>32 == u64Const(0xFFFFFFFF)) // [HGM] negative node count read
9442 nodes += u64Const(0x100000000);
9444 if (plyext != ' ' && plyext != '\t') {
9448 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9449 if( cps->scoreIsAbsolute &&
9450 ( gameMode == MachinePlaysBlack ||
9451 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
9452 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
9453 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
9454 !WhiteOnMove(currentMove)
9457 curscore = -curscore;
9460 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
9462 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
9465 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
9466 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
9467 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
9468 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
9469 if(f = fopen(buf, "w")) { // export PV to applicable PV file
9470 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
9474 /* TRANSLATORS: PV = principal variation, the variation the chess engine thinks is the best for everyone */
9475 DisplayError(_("failed writing PV"), 0);
9478 tempStats.depth = plylev;
9479 tempStats.nodes = nodes;
9480 tempStats.time = time;
9481 tempStats.score = curscore;
9482 tempStats.got_only_move = 0;
9484 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
9487 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
9488 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
9489 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
9490 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
9491 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
9492 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
9493 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
9494 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
9497 /* Buffer overflow protection */
9498 if (pv[0] != NULLCHAR) {
9499 if (strlen(pv) >= sizeof(tempStats.movelist)
9500 && appData.debugMode) {
9502 "PV is too long; using the first %u bytes.\n",
9503 (unsigned) sizeof(tempStats.movelist) - 1);
9506 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9508 sprintf(tempStats.movelist, " no PV\n");
9511 if (tempStats.seen_stat) {
9512 tempStats.ok_to_send = 1;
9515 if (strchr(tempStats.movelist, '(') != NULL) {
9516 tempStats.line_is_book = 1;
9517 tempStats.nr_moves = 0;
9518 tempStats.moves_left = 0;
9520 tempStats.line_is_book = 0;
9523 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9524 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9526 SendProgramStatsToFrontend( cps, &tempStats );
9529 [AS] Protect the thinkOutput buffer from overflow... this
9530 is only useful if buf1 hasn't overflowed first!
9532 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
9534 (gameMode == TwoMachinesPlay ?
9535 ToUpper(cps->twoMachinesColor[0]) : ' '),
9536 ((double) curscore) / 100.0,
9537 prefixHint ? lastHint : "",
9538 prefixHint ? " " : "" );
9540 if( buf1[0] != NULLCHAR ) {
9541 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
9543 if( strlen(pv) > max_len ) {
9544 if( appData.debugMode) {
9545 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
9547 pv[max_len+1] = '\0';
9550 strcat( thinkOutput, pv);
9553 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
9554 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9555 DisplayMove(currentMove - 1);
9559 } else if ((p=StrStr(message, "(only move)")) != NULL) {
9560 /* crafty (9.25+) says "(only move) <move>"
9561 * if there is only 1 legal move
9563 sscanf(p, "(only move) %s", buf1);
9564 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
9565 sprintf(programStats.movelist, "%s (only move)", buf1);
9566 programStats.depth = 1;
9567 programStats.nr_moves = 1;
9568 programStats.moves_left = 1;
9569 programStats.nodes = 1;
9570 programStats.time = 1;
9571 programStats.got_only_move = 1;
9573 /* Not really, but we also use this member to
9574 mean "line isn't going to change" (Crafty
9575 isn't searching, so stats won't change) */
9576 programStats.line_is_book = 1;
9578 SendProgramStatsToFrontend( cps, &programStats );
9580 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9581 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9582 DisplayMove(currentMove - 1);
9585 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
9586 &time, &nodes, &plylev, &mvleft,
9587 &mvtot, mvname) >= 5) {
9588 /* The stat01: line is from Crafty (9.29+) in response
9589 to the "." command */
9590 programStats.seen_stat = 1;
9591 cps->maybeThinking = TRUE;
9593 if (programStats.got_only_move || !appData.periodicUpdates)
9596 programStats.depth = plylev;
9597 programStats.time = time;
9598 programStats.nodes = nodes;
9599 programStats.moves_left = mvleft;
9600 programStats.nr_moves = mvtot;
9601 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
9602 programStats.ok_to_send = 1;
9603 programStats.movelist[0] = '\0';
9605 SendProgramStatsToFrontend( cps, &programStats );
9609 } else if (strncmp(message,"++",2) == 0) {
9610 /* Crafty 9.29+ outputs this */
9611 programStats.got_fail = 2;
9614 } else if (strncmp(message,"--",2) == 0) {
9615 /* Crafty 9.29+ outputs this */
9616 programStats.got_fail = 1;
9619 } else if (thinkOutput[0] != NULLCHAR &&
9620 strncmp(message, " ", 4) == 0) {
9621 unsigned message_len;
9624 while (*p && *p == ' ') p++;
9626 message_len = strlen( p );
9628 /* [AS] Avoid buffer overflow */
9629 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
9630 strcat(thinkOutput, " ");
9631 strcat(thinkOutput, p);
9634 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
9635 strcat(programStats.movelist, " ");
9636 strcat(programStats.movelist, p);
9639 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9640 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9641 DisplayMove(currentMove - 1);
9649 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9650 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
9652 ChessProgramStats cpstats;
9654 if (plyext != ' ' && plyext != '\t') {
9658 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9659 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
9660 curscore = -curscore;
9663 cpstats.depth = plylev;
9664 cpstats.nodes = nodes;
9665 cpstats.time = time;
9666 cpstats.score = curscore;
9667 cpstats.got_only_move = 0;
9668 cpstats.movelist[0] = '\0';
9670 if (buf1[0] != NULLCHAR) {
9671 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
9674 cpstats.ok_to_send = 0;
9675 cpstats.line_is_book = 0;
9676 cpstats.nr_moves = 0;
9677 cpstats.moves_left = 0;
9679 SendProgramStatsToFrontend( cps, &cpstats );
9686 /* Parse a game score from the character string "game", and
9687 record it as the history of the current game. The game
9688 score is NOT assumed to start from the standard position.
9689 The display is not updated in any way.
9692 ParseGameHistory (char *game)
9695 int fromX, fromY, toX, toY, boardIndex;
9700 if (appData.debugMode)
9701 fprintf(debugFP, "Parsing game history: %s\n", game);
9703 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
9704 gameInfo.site = StrSave(appData.icsHost);
9705 gameInfo.date = PGNDate();
9706 gameInfo.round = StrSave("-");
9708 /* Parse out names of players */
9709 while (*game == ' ') game++;
9711 while (*game != ' ') *p++ = *game++;
9713 gameInfo.white = StrSave(buf);
9714 while (*game == ' ') game++;
9716 while (*game != ' ' && *game != '\n') *p++ = *game++;
9718 gameInfo.black = StrSave(buf);
9721 boardIndex = blackPlaysFirst ? 1 : 0;
9724 yyboardindex = boardIndex;
9725 moveType = (ChessMove) Myylex();
9727 case IllegalMove: /* maybe suicide chess, etc. */
9728 if (appData.debugMode) {
9729 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
9730 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9731 setbuf(debugFP, NULL);
9733 case WhitePromotion:
9734 case BlackPromotion:
9735 case WhiteNonPromotion:
9736 case BlackNonPromotion:
9739 case WhiteCapturesEnPassant:
9740 case BlackCapturesEnPassant:
9741 case WhiteKingSideCastle:
9742 case WhiteQueenSideCastle:
9743 case BlackKingSideCastle:
9744 case BlackQueenSideCastle:
9745 case WhiteKingSideCastleWild:
9746 case WhiteQueenSideCastleWild:
9747 case BlackKingSideCastleWild:
9748 case BlackQueenSideCastleWild:
9750 case WhiteHSideCastleFR:
9751 case WhiteASideCastleFR:
9752 case BlackHSideCastleFR:
9753 case BlackASideCastleFR:
9755 fromX = currentMoveString[0] - AAA;
9756 fromY = currentMoveString[1] - ONE;
9757 toX = currentMoveString[2] - AAA;
9758 toY = currentMoveString[3] - ONE;
9759 promoChar = currentMoveString[4];
9763 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
9764 fromX = moveType == WhiteDrop ?
9765 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9766 (int) CharToPiece(ToLower(currentMoveString[0]));
9768 toX = currentMoveString[2] - AAA;
9769 toY = currentMoveString[3] - ONE;
9770 promoChar = NULLCHAR;
9774 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
9775 if (appData.debugMode) {
9776 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
9777 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9778 setbuf(debugFP, NULL);
9780 DisplayError(buf, 0);
9782 case ImpossibleMove:
9784 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
9785 if (appData.debugMode) {
9786 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
9787 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9788 setbuf(debugFP, NULL);
9790 DisplayError(buf, 0);
9793 if (boardIndex < backwardMostMove) {
9794 /* Oops, gap. How did that happen? */
9795 DisplayError(_("Gap in move list"), 0);
9798 backwardMostMove = blackPlaysFirst ? 1 : 0;
9799 if (boardIndex > forwardMostMove) {
9800 forwardMostMove = boardIndex;
9804 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
9805 strcat(parseList[boardIndex-1], " ");
9806 strcat(parseList[boardIndex-1], yy_text);
9818 case GameUnfinished:
9819 if (gameMode == IcsExamining) {
9820 if (boardIndex < backwardMostMove) {
9821 /* Oops, gap. How did that happen? */
9824 backwardMostMove = blackPlaysFirst ? 1 : 0;
9827 gameInfo.result = moveType;
9828 p = strchr(yy_text, '{');
9829 if (p == NULL) p = strchr(yy_text, '(');
9832 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9834 q = strchr(p, *p == '{' ? '}' : ')');
9835 if (q != NULL) *q = NULLCHAR;
9838 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9839 gameInfo.resultDetails = StrSave(p);
9842 if (boardIndex >= forwardMostMove &&
9843 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9844 backwardMostMove = blackPlaysFirst ? 1 : 0;
9847 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9848 fromY, fromX, toY, toX, promoChar,
9849 parseList[boardIndex]);
9850 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9851 /* currentMoveString is set as a side-effect of yylex */
9852 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9853 strcat(moveList[boardIndex], "\n");
9855 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9856 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9862 if(!IS_SHOGI(gameInfo.variant))
9863 strcat(parseList[boardIndex - 1], "+");
9867 strcat(parseList[boardIndex - 1], "#");
9874 /* Apply a move to the given board */
9876 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9878 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9879 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess ? 3 : 1;
9881 /* [HGM] compute & store e.p. status and castling rights for new position */
9882 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9884 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9885 oldEP = (signed char)board[EP_STATUS];
9886 board[EP_STATUS] = EP_NONE;
9887 board[EP_FILE] = board[EP_RANK] = 100;
9889 if (fromY == DROP_RANK) {
9891 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9892 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9895 piece = board[toY][toX] = (ChessSquare) fromX;
9897 // ChessSquare victim;
9900 if( killX >= 0 && killY >= 0 ) // [HGM] lion: Lion trampled over something
9901 // victim = board[killY][killX],
9902 board[killY][killX] = EmptySquare,
9903 board[EP_STATUS] = EP_CAPTURE;
9905 if( board[toY][toX] != EmptySquare ) {
9906 board[EP_STATUS] = EP_CAPTURE;
9907 if( (fromX != toX || fromY != toY) && // not igui!
9908 (captured == WhiteLion && board[fromY][fromX] != BlackLion ||
9909 captured == BlackLion && board[fromY][fromX] != WhiteLion ) ) { // [HGM] lion: Chu Lion-capture rules
9910 board[EP_STATUS] = EP_IRON_LION; // non-Lion x Lion: no counter-strike allowed
9914 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9915 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9916 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9918 if( board[fromY][fromX] == WhitePawn ) {
9919 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9920 board[EP_STATUS] = EP_PAWN_MOVE;
9922 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = (fromY + toY)/2;
9923 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9924 gameInfo.variant != VariantBerolina || toX < fromX)
9925 board[EP_STATUS] = toX | berolina;
9926 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9927 gameInfo.variant != VariantBerolina || toX > fromX)
9928 board[EP_STATUS] = toX;
9931 if( board[fromY][fromX] == BlackPawn ) {
9932 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9933 board[EP_STATUS] = EP_PAWN_MOVE;
9934 if( toY-fromY== -2) {
9935 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = (fromY + toY)/2;
9936 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9937 gameInfo.variant != VariantBerolina || toX < fromX)
9938 board[EP_STATUS] = toX | berolina;
9939 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9940 gameInfo.variant != VariantBerolina || toX > fromX)
9941 board[EP_STATUS] = toX;
9945 if(fromY == 0) board[TOUCHED_W] |= 1<<fromX; else // new way to keep track of virginity
9946 if(fromY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<fromX;
9947 if(toY == 0) board[TOUCHED_W] |= 1<<toX; else
9948 if(toY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<toX;
9950 for(i=0; i<nrCastlingRights; i++) {
9951 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9952 board[CASTLING][i] == toX && castlingRank[i] == toY
9953 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9956 if(gameInfo.variant == VariantSChess) { // update virginity
9957 if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
9958 if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
9959 if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
9960 if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
9963 if (fromX == toX && fromY == toY) return;
9965 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9966 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9967 if(gameInfo.variant == VariantKnightmate)
9968 king += (int) WhiteUnicorn - (int) WhiteKing;
9970 /* Code added by Tord: */
9971 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9972 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9973 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9974 board[fromY][fromX] = EmptySquare;
9975 board[toY][toX] = EmptySquare;
9976 if((toX > fromX) != (piece == WhiteRook)) {
9977 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9979 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9981 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9982 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9983 board[fromY][fromX] = EmptySquare;
9984 board[toY][toX] = EmptySquare;
9985 if((toX > fromX) != (piece == BlackRook)) {
9986 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9988 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9990 /* End of code added by Tord */
9992 } else if (board[fromY][fromX] == king
9993 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9994 && toY == fromY && toX > fromX+1) {
9995 board[fromY][fromX] = EmptySquare;
9996 board[toY][toX] = king;
9997 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9998 board[fromY][BOARD_RGHT-1] = EmptySquare;
9999 } else if (board[fromY][fromX] == king
10000 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10001 && toY == fromY && toX < fromX-1) {
10002 board[fromY][fromX] = EmptySquare;
10003 board[toY][toX] = king;
10004 board[toY][toX+1] = board[fromY][BOARD_LEFT];
10005 board[fromY][BOARD_LEFT] = EmptySquare;
10006 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
10007 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10008 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
10010 /* white pawn promotion */
10011 board[toY][toX] = CharToPiece(ToUpper(promoChar));
10012 if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
10013 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
10014 board[fromY][fromX] = EmptySquare;
10015 } else if ((fromY >= BOARD_HEIGHT>>1)
10016 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10018 && gameInfo.variant != VariantXiangqi
10019 && gameInfo.variant != VariantBerolina
10020 && (board[fromY][fromX] == WhitePawn)
10021 && (board[toY][toX] == EmptySquare)) {
10022 board[fromY][fromX] = EmptySquare;
10023 board[toY][toX] = WhitePawn;
10024 captured = board[toY - 1][toX];
10025 board[toY - 1][toX] = EmptySquare;
10026 } else if ((fromY == BOARD_HEIGHT-4)
10028 && gameInfo.variant == VariantBerolina
10029 && (board[fromY][fromX] == WhitePawn)
10030 && (board[toY][toX] == EmptySquare)) {
10031 board[fromY][fromX] = EmptySquare;
10032 board[toY][toX] = WhitePawn;
10033 if(oldEP & EP_BEROLIN_A) {
10034 captured = board[fromY][fromX-1];
10035 board[fromY][fromX-1] = EmptySquare;
10036 }else{ captured = board[fromY][fromX+1];
10037 board[fromY][fromX+1] = EmptySquare;
10039 } else if (board[fromY][fromX] == king
10040 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10041 && toY == fromY && toX > fromX+1) {
10042 board[fromY][fromX] = EmptySquare;
10043 board[toY][toX] = king;
10044 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
10045 board[fromY][BOARD_RGHT-1] = EmptySquare;
10046 } else if (board[fromY][fromX] == king
10047 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10048 && toY == fromY && toX < fromX-1) {
10049 board[fromY][fromX] = EmptySquare;
10050 board[toY][toX] = king;
10051 board[toY][toX+1] = board[fromY][BOARD_LEFT];
10052 board[fromY][BOARD_LEFT] = EmptySquare;
10053 } else if (fromY == 7 && fromX == 3
10054 && board[fromY][fromX] == BlackKing
10055 && toY == 7 && toX == 5) {
10056 board[fromY][fromX] = EmptySquare;
10057 board[toY][toX] = BlackKing;
10058 board[fromY][7] = EmptySquare;
10059 board[toY][4] = BlackRook;
10060 } else if (fromY == 7 && fromX == 3
10061 && board[fromY][fromX] == BlackKing
10062 && toY == 7 && toX == 1) {
10063 board[fromY][fromX] = EmptySquare;
10064 board[toY][toX] = BlackKing;
10065 board[fromY][0] = EmptySquare;
10066 board[toY][2] = BlackRook;
10067 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
10068 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10069 && toY < promoRank && promoChar
10071 /* black pawn promotion */
10072 board[toY][toX] = CharToPiece(ToLower(promoChar));
10073 if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
10074 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
10075 board[fromY][fromX] = EmptySquare;
10076 } else if ((fromY < BOARD_HEIGHT>>1)
10077 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10079 && gameInfo.variant != VariantXiangqi
10080 && gameInfo.variant != VariantBerolina
10081 && (board[fromY][fromX] == BlackPawn)
10082 && (board[toY][toX] == EmptySquare)) {
10083 board[fromY][fromX] = EmptySquare;
10084 board[toY][toX] = BlackPawn;
10085 captured = board[toY + 1][toX];
10086 board[toY + 1][toX] = EmptySquare;
10087 } else if ((fromY == 3)
10089 && gameInfo.variant == VariantBerolina
10090 && (board[fromY][fromX] == BlackPawn)
10091 && (board[toY][toX] == EmptySquare)) {
10092 board[fromY][fromX] = EmptySquare;
10093 board[toY][toX] = BlackPawn;
10094 if(oldEP & EP_BEROLIN_A) {
10095 captured = board[fromY][fromX-1];
10096 board[fromY][fromX-1] = EmptySquare;
10097 }else{ captured = board[fromY][fromX+1];
10098 board[fromY][fromX+1] = EmptySquare;
10101 ChessSquare piece = board[fromY][fromX]; // [HGM] lion: allow for igui (where from == to)
10102 board[fromY][fromX] = EmptySquare;
10103 board[toY][toX] = piece;
10107 if (gameInfo.holdingsWidth != 0) {
10109 /* !!A lot more code needs to be written to support holdings */
10110 /* [HGM] OK, so I have written it. Holdings are stored in the */
10111 /* penultimate board files, so they are automaticlly stored */
10112 /* in the game history. */
10113 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
10114 && promoChar && piece != WhitePawn && piece != BlackPawn) {
10115 /* Delete from holdings, by decreasing count */
10116 /* and erasing image if necessary */
10117 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
10118 if(p < (int) BlackPawn) { /* white drop */
10119 p -= (int)WhitePawn;
10120 p = PieceToNumber((ChessSquare)p);
10121 if(p >= gameInfo.holdingsSize) p = 0;
10122 if(--board[p][BOARD_WIDTH-2] <= 0)
10123 board[p][BOARD_WIDTH-1] = EmptySquare;
10124 if((int)board[p][BOARD_WIDTH-2] < 0)
10125 board[p][BOARD_WIDTH-2] = 0;
10126 } else { /* black drop */
10127 p -= (int)BlackPawn;
10128 p = PieceToNumber((ChessSquare)p);
10129 if(p >= gameInfo.holdingsSize) p = 0;
10130 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
10131 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
10132 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
10133 board[BOARD_HEIGHT-1-p][1] = 0;
10136 if (captured != EmptySquare && gameInfo.holdingsSize > 0
10137 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
10138 /* [HGM] holdings: Add to holdings, if holdings exist */
10139 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
10140 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
10141 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
10143 p = (int) captured;
10144 if (p >= (int) BlackPawn) {
10145 p -= (int)BlackPawn;
10146 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
10147 /* in Shogi restore piece to its original first */
10148 captured = (ChessSquare) (DEMOTED captured);
10151 p = PieceToNumber((ChessSquare)p);
10152 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
10153 board[p][BOARD_WIDTH-2]++;
10154 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
10156 p -= (int)WhitePawn;
10157 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
10158 captured = (ChessSquare) (DEMOTED captured);
10161 p = PieceToNumber((ChessSquare)p);
10162 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
10163 board[BOARD_HEIGHT-1-p][1]++;
10164 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
10167 } else if (gameInfo.variant == VariantAtomic) {
10168 if (captured != EmptySquare) {
10170 for (y = toY-1; y <= toY+1; y++) {
10171 for (x = toX-1; x <= toX+1; x++) {
10172 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
10173 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
10174 board[y][x] = EmptySquare;
10178 board[toY][toX] = EmptySquare;
10182 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
10183 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
10185 if(promoChar == '+') {
10186 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
10187 board[toY][toX] = (ChessSquare) (CHUPROMOTED piece);
10188 if(gameInfo.variant == VariantChuChess && (piece == WhiteKnight || piece == BlackKnight))
10189 board[toY][toX] = piece + WhiteLion - WhiteKnight; // adjust Knight promotions to Lion
10190 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
10191 ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
10192 if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
10193 && pieceToChar[PROMOTED newPiece] == '~') newPiece = PROMOTED newPiece; // but promoted version available
10194 board[toY][toX] = newPiece;
10196 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10197 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
10198 // [HGM] superchess: take promotion piece out of holdings
10199 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
10200 if((int)piece < (int)BlackPawn) { // determine stm from piece color
10201 if(!--board[k][BOARD_WIDTH-2])
10202 board[k][BOARD_WIDTH-1] = EmptySquare;
10204 if(!--board[BOARD_HEIGHT-1-k][1])
10205 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
10210 /* Updates forwardMostMove */
10212 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
10214 int x = toX, y = toY;
10215 char *s = parseList[forwardMostMove];
10216 ChessSquare p = boards[forwardMostMove][toY][toX];
10217 // forwardMostMove++; // [HGM] bare: moved downstream
10219 if(killX >= 0 && killY >= 0) x = killX, y = killY; // [HGM] lion: make SAN move to intermediate square, if there is one
10220 (void) CoordsToAlgebraic(boards[forwardMostMove],
10221 PosFlags(forwardMostMove),
10222 fromY, fromX, y, x, promoChar,
10224 if(killX >= 0 && killY >= 0)
10225 sprintf(s + strlen(s), "%c%c%d", p == EmptySquare || toX == fromX && toY == fromY ? '-' : 'x', toX + AAA, toY + ONE - '0');
10227 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
10228 int timeLeft; static int lastLoadFlag=0; int king, piece;
10229 piece = boards[forwardMostMove][fromY][fromX];
10230 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
10231 if(gameInfo.variant == VariantKnightmate)
10232 king += (int) WhiteUnicorn - (int) WhiteKing;
10233 if(forwardMostMove == 0) {
10234 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
10235 fprintf(serverMoves, "%s;", UserName());
10236 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
10237 fprintf(serverMoves, "%s;", second.tidy);
10238 fprintf(serverMoves, "%s;", first.tidy);
10239 if(gameMode == MachinePlaysWhite)
10240 fprintf(serverMoves, "%s;", UserName());
10241 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
10242 fprintf(serverMoves, "%s;", second.tidy);
10243 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
10244 lastLoadFlag = loadFlag;
10246 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
10247 // print castling suffix
10248 if( toY == fromY && piece == king ) {
10250 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
10252 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
10255 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
10256 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
10257 boards[forwardMostMove][toY][toX] == EmptySquare
10258 && fromX != toX && fromY != toY)
10259 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
10260 // promotion suffix
10261 if(promoChar != NULLCHAR) {
10262 if(fromY == 0 || fromY == BOARD_HEIGHT-1)
10263 fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
10264 ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
10265 else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
10268 char buf[MOVE_LEN*2], *p; int len;
10269 fprintf(serverMoves, "/%d/%d",
10270 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
10271 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
10272 else timeLeft = blackTimeRemaining/1000;
10273 fprintf(serverMoves, "/%d", timeLeft);
10274 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
10275 if(p = strchr(buf, '/')) *p = NULLCHAR; else
10276 if(p = strchr(buf, '=')) *p = NULLCHAR;
10277 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
10278 fprintf(serverMoves, "/%s", buf);
10280 fflush(serverMoves);
10283 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
10284 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
10287 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
10288 if (commentList[forwardMostMove+1] != NULL) {
10289 free(commentList[forwardMostMove+1]);
10290 commentList[forwardMostMove+1] = NULL;
10292 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
10293 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
10294 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
10295 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
10296 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10297 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10298 adjustedClock = FALSE;
10299 gameInfo.result = GameUnfinished;
10300 if (gameInfo.resultDetails != NULL) {
10301 free(gameInfo.resultDetails);
10302 gameInfo.resultDetails = NULL;
10304 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
10305 moveList[forwardMostMove - 1]);
10306 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
10312 if(!IS_SHOGI(gameInfo.variant))
10313 strcat(parseList[forwardMostMove - 1], "+");
10317 strcat(parseList[forwardMostMove - 1], "#");
10322 /* Updates currentMove if not pausing */
10324 ShowMove (int fromX, int fromY, int toX, int toY)
10326 int instant = (gameMode == PlayFromGameFile) ?
10327 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
10328 if(appData.noGUI) return;
10329 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10331 if (forwardMostMove == currentMove + 1) {
10332 AnimateMove(boards[forwardMostMove - 1],
10333 fromX, fromY, toX, toY);
10336 currentMove = forwardMostMove;
10339 killX = killY = -1; // [HGM] lion: used up
10341 if (instant) return;
10343 DisplayMove(currentMove - 1);
10344 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10345 if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
10346 SetHighlights(fromX, fromY, toX, toY);
10349 DrawPosition(FALSE, boards[currentMove]);
10350 DisplayBothClocks();
10351 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
10355 SendEgtPath (ChessProgramState *cps)
10356 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
10357 char buf[MSG_SIZ], name[MSG_SIZ], *p;
10359 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
10362 char c, *q = name+1, *r, *s;
10364 name[0] = ','; // extract next format name from feature and copy with prefixed ','
10365 while(*p && *p != ',') *q++ = *p++;
10366 *q++ = ':'; *q = 0;
10367 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
10368 strcmp(name, ",nalimov:") == 0 ) {
10369 // take nalimov path from the menu-changeable option first, if it is defined
10370 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
10371 SendToProgram(buf,cps); // send egtbpath command for nalimov
10373 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
10374 (s = StrStr(appData.egtFormats, name)) != NULL) {
10375 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
10376 s = r = StrStr(s, ":") + 1; // beginning of path info
10377 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
10378 c = *r; *r = 0; // temporarily null-terminate path info
10379 *--q = 0; // strip of trailig ':' from name
10380 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
10382 SendToProgram(buf,cps); // send egtbpath command for this format
10384 if(*p == ',') p++; // read away comma to position for next format name
10389 NonStandardBoardSize (VariantClass v, int boardWidth, int boardHeight, int holdingsSize)
10391 int width = 8, height = 8, holdings = 0; // most common sizes
10392 if( v == VariantUnknown || *engineVariant) return 0; // engine-defined name never needs prefix
10393 // correct the deviations default for each variant
10394 if( v == VariantXiangqi ) width = 9, height = 10;
10395 if( v == VariantShogi ) width = 9, height = 9, holdings = 7;
10396 if( v == VariantBughouse || v == VariantCrazyhouse) holdings = 5;
10397 if( v == VariantCapablanca || v == VariantCapaRandom ||
10398 v == VariantGothic || v == VariantFalcon || v == VariantJanus )
10400 if( v == VariantCourier ) width = 12;
10401 if( v == VariantSuper ) holdings = 8;
10402 if( v == VariantGreat ) width = 10, holdings = 8;
10403 if( v == VariantSChess ) holdings = 7;
10404 if( v == VariantGrand ) width = 10, height = 10, holdings = 7;
10405 if( v == VariantChuChess) width = 10, height = 10;
10406 if( v == VariantChu ) width = 12, height = 12;
10407 return boardWidth >= 0 && boardWidth != width || // -1 is default,
10408 boardHeight >= 0 && boardHeight != height || // and thus by definition OK
10409 holdingsSize >= 0 && holdingsSize != holdings;
10412 char variantError[MSG_SIZ];
10415 SupportedVariant (char *list, VariantClass v, int boardWidth, int boardHeight, int holdingsSize, int proto, char *engine)
10416 { // returns error message (recognizable by upper-case) if engine does not support the variant
10417 char *p, *variant = VariantName(v);
10418 static char b[MSG_SIZ];
10419 if(NonStandardBoardSize(v, boardWidth, boardHeight, holdingsSize)) { /* [HGM] make prefix for non-standard board size. */
10420 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", boardWidth, boardHeight,
10421 holdingsSize, variant); // cook up sized variant name
10422 /* [HGM] varsize: try first if this deviant size variant is specifically known */
10423 if(StrStr(list, b) == NULL) {
10424 // specific sized variant not known, check if general sizing allowed
10425 if(proto != 1 && StrStr(list, "boardsize") == NULL) {
10426 snprintf(variantError, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
10427 boardWidth, boardHeight, holdingsSize, engine);
10430 /* [HGM] here we really should compare with the maximum supported board size */
10432 } else snprintf(b, MSG_SIZ,"%s", variant);
10433 if(proto == 1) return b; // for protocol 1 we cannot check and hope for the best
10434 p = StrStr(list, b);
10435 while(p && (p != list && p[-1] != ',' || p[strlen(b)] && p[strlen(b)] != ',') ) p = StrStr(p+1, b);
10437 // occurs not at all in list, or only as sub-string
10438 snprintf(variantError, MSG_SIZ, _("Variant %s not supported by %s"), b, engine);
10439 if(p = StrStr(list, b)) { // handle requesting parent variant when only size-overridden is supported
10440 int l = strlen(variantError);
10442 while(p != list && p[-1] != ',') p--;
10443 q = strchr(p, ',');
10444 if(q) *q = NULLCHAR;
10445 snprintf(variantError + l, MSG_SIZ - l, _(", but %s is"), p);
10454 InitChessProgram (ChessProgramState *cps, int setup)
10455 /* setup needed to setup FRC opening position */
10457 char buf[MSG_SIZ], *b;
10458 if (appData.noChessProgram) return;
10459 hintRequested = FALSE;
10460 bookRequested = FALSE;
10462 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
10463 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
10464 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
10465 if(cps->memSize) { /* [HGM] memory */
10466 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
10467 SendToProgram(buf, cps);
10469 SendEgtPath(cps); /* [HGM] EGT */
10470 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
10471 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
10472 SendToProgram(buf, cps);
10475 setboardSpoiledMachineBlack = FALSE;
10476 SendToProgram(cps->initString, cps);
10477 if (gameInfo.variant != VariantNormal &&
10478 gameInfo.variant != VariantLoadable
10479 /* [HGM] also send variant if board size non-standard */
10480 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0) {
10482 b = SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
10483 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, cps->tidy);
10485 DisplayFatalError(variantError, 0, 1);
10489 snprintf(buf, MSG_SIZ, "variant %s\n", b);
10490 SendToProgram(buf, cps);
10492 currentlyInitializedVariant = gameInfo.variant;
10494 /* [HGM] send opening position in FRC to first engine */
10496 SendToProgram("force\n", cps);
10498 /* engine is now in force mode! Set flag to wake it up after first move. */
10499 setboardSpoiledMachineBlack = 1;
10502 if (cps->sendICS) {
10503 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
10504 SendToProgram(buf, cps);
10506 cps->maybeThinking = FALSE;
10507 cps->offeredDraw = 0;
10508 if (!appData.icsActive) {
10509 SendTimeControl(cps, movesPerSession, timeControl,
10510 timeIncrement, appData.searchDepth,
10513 if (appData.showThinking
10514 // [HGM] thinking: four options require thinking output to be sent
10515 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
10517 SendToProgram("post\n", cps);
10519 SendToProgram("hard\n", cps);
10520 if (!appData.ponderNextMove) {
10521 /* Warning: "easy" is a toggle in GNU Chess, so don't send
10522 it without being sure what state we are in first. "hard"
10523 is not a toggle, so that one is OK.
10525 SendToProgram("easy\n", cps);
10527 if (cps->usePing) {
10528 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++cps->lastPing);
10529 SendToProgram(buf, cps);
10531 cps->initDone = TRUE;
10532 ClearEngineOutputPane(cps == &second);
10537 ResendOptions (ChessProgramState *cps)
10538 { // send the stored value of the options
10541 Option *opt = cps->option;
10542 for(i=0; i<cps->nrOptions; i++, opt++) {
10543 switch(opt->type) {
10547 snprintf(buf, MSG_SIZ, "option %s=%d\n", opt->name, opt->value);
10550 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->choice[opt->value]);
10553 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->textValue);
10559 SendToProgram(buf, cps);
10564 StartChessProgram (ChessProgramState *cps)
10569 if (appData.noChessProgram) return;
10570 cps->initDone = FALSE;
10572 if (strcmp(cps->host, "localhost") == 0) {
10573 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
10574 } else if (*appData.remoteShell == NULLCHAR) {
10575 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
10577 if (*appData.remoteUser == NULLCHAR) {
10578 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
10581 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
10582 cps->host, appData.remoteUser, cps->program);
10584 err = StartChildProcess(buf, "", &cps->pr);
10588 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
10589 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
10590 if(cps != &first) return;
10591 appData.noChessProgram = TRUE;
10594 // DisplayFatalError(buf, err, 1);
10595 // cps->pr = NoProc;
10596 // cps->isr = NULL;
10600 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
10601 if (cps->protocolVersion > 1) {
10602 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
10603 if(!cps->reload) { // do not clear options when reloading because of -xreuse
10604 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
10605 cps->comboCnt = 0; // and values of combo boxes
10607 SendToProgram(buf, cps);
10608 if(cps->reload) ResendOptions(cps);
10610 SendToProgram("xboard\n", cps);
10615 TwoMachinesEventIfReady P((void))
10617 static int curMess = 0;
10618 if (first.lastPing != first.lastPong) {
10619 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
10620 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10623 if (second.lastPing != second.lastPong) {
10624 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
10625 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10628 DisplayMessage("", ""); curMess = 0;
10629 TwoMachinesEvent();
10633 MakeName (char *template)
10637 static char buf[MSG_SIZ];
10641 clock = time((time_t *)NULL);
10642 tm = localtime(&clock);
10644 while(*p++ = *template++) if(p[-1] == '%') {
10645 switch(*template++) {
10646 case 0: *p = 0; return buf;
10647 case 'Y': i = tm->tm_year+1900; break;
10648 case 'y': i = tm->tm_year-100; break;
10649 case 'M': i = tm->tm_mon+1; break;
10650 case 'd': i = tm->tm_mday; break;
10651 case 'h': i = tm->tm_hour; break;
10652 case 'm': i = tm->tm_min; break;
10653 case 's': i = tm->tm_sec; break;
10656 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
10662 CountPlayers (char *p)
10665 while(p = strchr(p, '\n')) p++, n++; // count participants
10670 WriteTourneyFile (char *results, FILE *f)
10671 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
10672 if(f == NULL) f = fopen(appData.tourneyFile, "w");
10673 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
10674 // create a file with tournament description
10675 fprintf(f, "-participants {%s}\n", appData.participants);
10676 fprintf(f, "-seedBase %d\n", appData.seedBase);
10677 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
10678 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
10679 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
10680 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
10681 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
10682 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
10683 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
10684 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
10685 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
10686 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
10687 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
10688 fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
10689 fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
10690 fprintf(f, "-bookDepth %d\n", appData.bookDepth);
10691 fprintf(f, "-bookVariation %d\n", appData.bookStrength);
10692 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
10693 fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
10694 fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
10695 fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
10696 fprintf(f, "-smpCores %d\n", appData.smpCores);
10698 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
10700 fprintf(f, "-mps %d\n", appData.movesPerSession);
10701 fprintf(f, "-tc %s\n", appData.timeControl);
10702 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
10704 fprintf(f, "-results \"%s\"\n", results);
10709 char *command[MAXENGINES], *mnemonic[MAXENGINES];
10712 Substitute (char *participants, int expunge)
10714 int i, changed, changes=0, nPlayers=0;
10715 char *p, *q, *r, buf[MSG_SIZ];
10716 if(participants == NULL) return;
10717 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
10718 r = p = participants; q = appData.participants;
10719 while(*p && *p == *q) {
10720 if(*p == '\n') r = p+1, nPlayers++;
10723 if(*p) { // difference
10724 while(*p && *p++ != '\n');
10725 while(*q && *q++ != '\n');
10726 changed = nPlayers;
10727 changes = 1 + (strcmp(p, q) != 0);
10729 if(changes == 1) { // a single engine mnemonic was changed
10730 q = r; while(*q) nPlayers += (*q++ == '\n');
10731 p = buf; while(*r && (*p = *r++) != '\n') p++;
10733 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10734 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
10735 if(mnemonic[i]) { // The substitute is valid
10737 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
10738 flock(fileno(f), LOCK_EX);
10739 ParseArgsFromFile(f);
10740 fseek(f, 0, SEEK_SET);
10741 FREE(appData.participants); appData.participants = participants;
10742 if(expunge) { // erase results of replaced engine
10743 int len = strlen(appData.results), w, b, dummy;
10744 for(i=0; i<len; i++) {
10745 Pairing(i, nPlayers, &w, &b, &dummy);
10746 if((w == changed || b == changed) && appData.results[i] == '*') {
10747 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
10752 for(i=0; i<len; i++) {
10753 Pairing(i, nPlayers, &w, &b, &dummy);
10754 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
10757 WriteTourneyFile(appData.results, f);
10758 fclose(f); // release lock
10761 } else DisplayError(_("No engine with the name you gave is installed"), 0);
10763 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
10764 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
10765 free(participants);
10770 CheckPlayers (char *participants)
10773 char buf[MSG_SIZ], *p;
10774 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10775 while(p = strchr(participants, '\n')) {
10777 for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
10779 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
10781 DisplayError(buf, 0);
10785 participants = p + 1;
10791 CreateTourney (char *name)
10794 if(matchMode && strcmp(name, appData.tourneyFile)) {
10795 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
10797 if(name[0] == NULLCHAR) {
10798 if(appData.participants[0])
10799 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
10802 f = fopen(name, "r");
10803 if(f) { // file exists
10804 ASSIGN(appData.tourneyFile, name);
10805 ParseArgsFromFile(f); // parse it
10807 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
10808 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
10809 DisplayError(_("Not enough participants"), 0);
10812 if(CheckPlayers(appData.participants)) return 0;
10813 ASSIGN(appData.tourneyFile, name);
10814 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
10815 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
10818 appData.noChessProgram = FALSE;
10819 appData.clockMode = TRUE;
10825 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
10827 char buf[MSG_SIZ], *p, *q;
10828 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
10829 insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
10830 skip = !all && group[0]; // if group requested, we start in skip mode
10831 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
10832 p = names; q = buf; header = 0;
10833 while(*p && *p != '\n') *q++ = *p++;
10835 if(*p == '\n') p++;
10836 if(buf[0] == '#') {
10837 if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
10838 depth++; // we must be entering a new group
10839 if(all) continue; // suppress printing group headers when complete list requested
10841 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
10843 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
10844 if(engineList[i]) free(engineList[i]);
10845 engineList[i] = strdup(buf);
10846 if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
10847 if(engineMnemonic[i]) free(engineMnemonic[i]);
10848 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
10850 sscanf(q + 8, "%s", buf + strlen(buf));
10853 engineMnemonic[i] = strdup(buf);
10856 engineList[i] = engineMnemonic[i] = NULL;
10860 // following implemented as macro to avoid type limitations
10861 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
10864 SwapEngines (int n)
10865 { // swap settings for first engine and other engine (so far only some selected options)
10870 SWAP(chessProgram, p)
10872 SWAP(hasOwnBookUCI, h)
10873 SWAP(protocolVersion, h)
10875 SWAP(scoreIsAbsolute, h)
10880 SWAP(engOptions, p)
10881 SWAP(engInitString, p)
10882 SWAP(computerString, p)
10884 SWAP(fenOverride, p)
10886 SWAP(accumulateTC, h)
10893 GetEngineLine (char *s, int n)
10897 extern char *icsNames;
10898 if(!s || !*s) return 0;
10899 NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
10900 for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
10901 if(!mnemonic[i]) return 0;
10902 if(n == 11) return 1; // just testing if there was a match
10903 snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
10904 if(n == 1) SwapEngines(n);
10905 ParseArgsFromString(buf);
10906 if(n == 1) SwapEngines(n);
10907 if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
10908 SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
10909 ParseArgsFromString(buf);
10915 SetPlayer (int player, char *p)
10916 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
10918 char buf[MSG_SIZ], *engineName;
10919 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
10920 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
10921 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
10923 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
10924 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
10925 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
10926 ParseArgsFromString(buf);
10927 } else { // no engine with this nickname is installed!
10928 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
10929 ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
10930 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10932 DisplayError(buf, 0);
10939 char *recentEngines;
10942 RecentEngineEvent (int nr)
10945 // SwapEngines(1); // bump first to second
10946 // ReplaceEngine(&second, 1); // and load it there
10947 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10948 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
10949 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
10950 ReplaceEngine(&first, 0);
10951 FloatToFront(&appData.recentEngineList, command[n]);
10956 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
10957 { // determine players from game number
10958 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
10960 if(appData.tourneyType == 0) {
10961 roundsPerCycle = (nPlayers - 1) | 1;
10962 pairingsPerRound = nPlayers / 2;
10963 } else if(appData.tourneyType > 0) {
10964 roundsPerCycle = nPlayers - appData.tourneyType;
10965 pairingsPerRound = appData.tourneyType;
10967 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
10968 gamesPerCycle = gamesPerRound * roundsPerCycle;
10969 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
10970 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
10971 curRound = nr / gamesPerRound; nr %= gamesPerRound;
10972 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
10973 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
10974 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
10976 if(appData.cycleSync) *syncInterval = gamesPerCycle;
10977 if(appData.roundSync) *syncInterval = gamesPerRound;
10979 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
10981 if(appData.tourneyType == 0) {
10982 if(curPairing == (nPlayers-1)/2 ) {
10983 *whitePlayer = curRound;
10984 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
10986 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
10987 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
10988 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
10989 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
10991 } else if(appData.tourneyType > 1) {
10992 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
10993 *whitePlayer = curRound + appData.tourneyType;
10994 } else if(appData.tourneyType > 0) {
10995 *whitePlayer = curPairing;
10996 *blackPlayer = curRound + appData.tourneyType;
10999 // take care of white/black alternation per round.
11000 // For cycles and games this is already taken care of by default, derived from matchGame!
11001 return curRound & 1;
11005 NextTourneyGame (int nr, int *swapColors)
11006 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
11008 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
11010 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
11011 tf = fopen(appData.tourneyFile, "r");
11012 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
11013 ParseArgsFromFile(tf); fclose(tf);
11014 InitTimeControls(); // TC might be altered from tourney file
11016 nPlayers = CountPlayers(appData.participants); // count participants
11017 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
11018 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
11021 p = q = appData.results;
11022 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
11023 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
11024 DisplayMessage(_("Waiting for other game(s)"),"");
11025 waitingForGame = TRUE;
11026 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
11029 waitingForGame = FALSE;
11032 if(appData.tourneyType < 0) {
11033 if(nr>=0 && !pairingReceived) {
11035 if(pairing.pr == NoProc) {
11036 if(!appData.pairingEngine[0]) {
11037 DisplayFatalError(_("No pairing engine specified"), 0, 1);
11040 StartChessProgram(&pairing); // starts the pairing engine
11042 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
11043 SendToProgram(buf, &pairing);
11044 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
11045 SendToProgram(buf, &pairing);
11046 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
11048 pairingReceived = 0; // ... so we continue here
11050 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
11051 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
11052 matchGame = 1; roundNr = nr / syncInterval + 1;
11055 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
11057 // redefine engines, engine dir, etc.
11058 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11059 if(first.pr == NoProc) {
11060 if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
11061 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
11063 if(second.pr == NoProc) {
11065 if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
11066 SwapEngines(1); // and make that valid for second engine by swapping
11067 InitEngine(&second, 1);
11069 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
11070 UpdateLogos(FALSE); // leave display to ModeHiglight()
11076 { // performs game initialization that does not invoke engines, and then tries to start the game
11077 int res, firstWhite, swapColors = 0;
11078 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
11079 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
11081 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
11082 if(strcmp(buf, currentDebugFile)) { // name has changed
11083 FILE *f = fopen(buf, "w");
11084 if(f) { // if opening the new file failed, just keep using the old one
11085 ASSIGN(currentDebugFile, buf);
11089 if(appData.serverFileName) {
11090 if(serverFP) fclose(serverFP);
11091 serverFP = fopen(appData.serverFileName, "w");
11092 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
11093 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
11097 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
11098 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
11099 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
11100 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11101 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
11102 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
11103 Reset(FALSE, first.pr != NoProc);
11104 res = LoadGameOrPosition(matchGame); // setup game
11105 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
11106 if(!res) return; // abort when bad game/pos file
11107 TwoMachinesEvent();
11111 UserAdjudicationEvent (int result)
11113 ChessMove gameResult = GameIsDrawn;
11116 gameResult = WhiteWins;
11118 else if( result < 0 ) {
11119 gameResult = BlackWins;
11122 if( gameMode == TwoMachinesPlay ) {
11123 GameEnds( gameResult, "User adjudication", GE_XBOARD );
11128 // [HGM] save: calculate checksum of game to make games easily identifiable
11130 StringCheckSum (char *s)
11133 if(s==NULL) return 0;
11134 while(*s) i = i*259 + *s++;
11142 for(i=backwardMostMove; i<forwardMostMove; i++) {
11143 sum += pvInfoList[i].depth;
11144 sum += StringCheckSum(parseList[i]);
11145 sum += StringCheckSum(commentList[i]);
11148 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
11149 return sum + StringCheckSum(commentList[i]);
11150 } // end of save patch
11153 GameEnds (ChessMove result, char *resultDetails, int whosays)
11155 GameMode nextGameMode;
11157 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
11159 if(endingGame) return; /* [HGM] crash: forbid recursion */
11161 if(twoBoards) { // [HGM] dual: switch back to one board
11162 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
11163 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
11165 if (appData.debugMode) {
11166 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
11167 result, resultDetails ? resultDetails : "(null)", whosays);
11170 fromX = fromY = killX = killY = -1; // [HGM] abort any move the user is entering. // [HGM] lion
11172 if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
11174 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
11175 /* If we are playing on ICS, the server decides when the
11176 game is over, but the engine can offer to draw, claim
11180 if (appData.zippyPlay && first.initDone) {
11181 if (result == GameIsDrawn) {
11182 /* In case draw still needs to be claimed */
11183 SendToICS(ics_prefix);
11184 SendToICS("draw\n");
11185 } else if (StrCaseStr(resultDetails, "resign")) {
11186 SendToICS(ics_prefix);
11187 SendToICS("resign\n");
11191 endingGame = 0; /* [HGM] crash */
11195 /* If we're loading the game from a file, stop */
11196 if (whosays == GE_FILE) {
11197 (void) StopLoadGameTimer();
11201 /* Cancel draw offers */
11202 first.offeredDraw = second.offeredDraw = 0;
11204 /* If this is an ICS game, only ICS can really say it's done;
11205 if not, anyone can. */
11206 isIcsGame = (gameMode == IcsPlayingWhite ||
11207 gameMode == IcsPlayingBlack ||
11208 gameMode == IcsObserving ||
11209 gameMode == IcsExamining);
11211 if (!isIcsGame || whosays == GE_ICS) {
11212 /* OK -- not an ICS game, or ICS said it was done */
11214 if (!isIcsGame && !appData.noChessProgram)
11215 SetUserThinkingEnables();
11217 /* [HGM] if a machine claims the game end we verify this claim */
11218 if(gameMode == TwoMachinesPlay && appData.testClaims) {
11219 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
11221 ChessMove trueResult = (ChessMove) -1;
11223 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
11224 first.twoMachinesColor[0] :
11225 second.twoMachinesColor[0] ;
11227 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
11228 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
11229 /* [HGM] verify: engine mate claims accepted if they were flagged */
11230 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
11232 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
11233 /* [HGM] verify: engine mate claims accepted if they were flagged */
11234 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
11236 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
11237 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
11240 // now verify win claims, but not in drop games, as we don't understand those yet
11241 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11242 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
11243 (result == WhiteWins && claimer == 'w' ||
11244 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
11245 if (appData.debugMode) {
11246 fprintf(debugFP, "result=%d sp=%d move=%d\n",
11247 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
11249 if(result != trueResult) {
11250 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
11251 result = claimer == 'w' ? BlackWins : WhiteWins;
11252 resultDetails = buf;
11255 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
11256 && (forwardMostMove <= backwardMostMove ||
11257 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
11258 (claimer=='b')==(forwardMostMove&1))
11260 /* [HGM] verify: draws that were not flagged are false claims */
11261 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
11262 result = claimer == 'w' ? BlackWins : WhiteWins;
11263 resultDetails = buf;
11265 /* (Claiming a loss is accepted no questions asked!) */
11266 } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
11267 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
11268 result = GameUnfinished;
11269 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
11271 /* [HGM] bare: don't allow bare King to win */
11272 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11273 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
11274 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
11275 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
11276 && result != GameIsDrawn)
11277 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
11278 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
11279 int p = (signed char)boards[forwardMostMove][i][j] - color;
11280 if(p >= 0 && p <= (int)WhiteKing) k++;
11282 if (appData.debugMode) {
11283 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
11284 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
11287 result = GameIsDrawn;
11288 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
11289 resultDetails = buf;
11295 if(serverMoves != NULL && !loadFlag) { char c = '=';
11296 if(result==WhiteWins) c = '+';
11297 if(result==BlackWins) c = '-';
11298 if(resultDetails != NULL)
11299 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
11301 if (resultDetails != NULL) {
11302 gameInfo.result = result;
11303 gameInfo.resultDetails = StrSave(resultDetails);
11305 /* display last move only if game was not loaded from file */
11306 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
11307 DisplayMove(currentMove - 1);
11309 if (forwardMostMove != 0) {
11310 if (gameMode != PlayFromGameFile && gameMode != EditGame
11311 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
11313 if (*appData.saveGameFile != NULLCHAR) {
11314 if(result == GameUnfinished && matchMode && *appData.tourneyFile)
11315 AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
11317 SaveGameToFile(appData.saveGameFile, TRUE);
11318 } else if (appData.autoSaveGames) {
11319 if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
11321 if (*appData.savePositionFile != NULLCHAR) {
11322 SavePositionToFile(appData.savePositionFile);
11324 AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
11328 /* Tell program how game ended in case it is learning */
11329 /* [HGM] Moved this to after saving the PGN, just in case */
11330 /* engine died and we got here through time loss. In that */
11331 /* case we will get a fatal error writing the pipe, which */
11332 /* would otherwise lose us the PGN. */
11333 /* [HGM] crash: not needed anymore, but doesn't hurt; */
11334 /* output during GameEnds should never be fatal anymore */
11335 if (gameMode == MachinePlaysWhite ||
11336 gameMode == MachinePlaysBlack ||
11337 gameMode == TwoMachinesPlay ||
11338 gameMode == IcsPlayingWhite ||
11339 gameMode == IcsPlayingBlack ||
11340 gameMode == BeginningOfGame) {
11342 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
11344 if (first.pr != NoProc) {
11345 SendToProgram(buf, &first);
11347 if (second.pr != NoProc &&
11348 gameMode == TwoMachinesPlay) {
11349 SendToProgram(buf, &second);
11354 if (appData.icsActive) {
11355 if (appData.quietPlay &&
11356 (gameMode == IcsPlayingWhite ||
11357 gameMode == IcsPlayingBlack)) {
11358 SendToICS(ics_prefix);
11359 SendToICS("set shout 1\n");
11361 nextGameMode = IcsIdle;
11362 ics_user_moved = FALSE;
11363 /* clean up premove. It's ugly when the game has ended and the
11364 * premove highlights are still on the board.
11367 gotPremove = FALSE;
11368 ClearPremoveHighlights();
11369 DrawPosition(FALSE, boards[currentMove]);
11371 if (whosays == GE_ICS) {
11374 if (gameMode == IcsPlayingWhite)
11376 else if(gameMode == IcsPlayingBlack)
11377 PlayIcsLossSound();
11380 if (gameMode == IcsPlayingBlack)
11382 else if(gameMode == IcsPlayingWhite)
11383 PlayIcsLossSound();
11386 PlayIcsDrawSound();
11389 PlayIcsUnfinishedSound();
11392 if(appData.quitNext) { ExitEvent(0); return; }
11393 } else if (gameMode == EditGame ||
11394 gameMode == PlayFromGameFile ||
11395 gameMode == AnalyzeMode ||
11396 gameMode == AnalyzeFile) {
11397 nextGameMode = gameMode;
11399 nextGameMode = EndOfGame;
11404 nextGameMode = gameMode;
11407 if (appData.noChessProgram) {
11408 gameMode = nextGameMode;
11410 endingGame = 0; /* [HGM] crash */
11415 /* Put first chess program into idle state */
11416 if (first.pr != NoProc &&
11417 (gameMode == MachinePlaysWhite ||
11418 gameMode == MachinePlaysBlack ||
11419 gameMode == TwoMachinesPlay ||
11420 gameMode == IcsPlayingWhite ||
11421 gameMode == IcsPlayingBlack ||
11422 gameMode == BeginningOfGame)) {
11423 SendToProgram("force\n", &first);
11424 if (first.usePing) {
11426 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
11427 SendToProgram(buf, &first);
11430 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
11431 /* Kill off first chess program */
11432 if (first.isr != NULL)
11433 RemoveInputSource(first.isr);
11436 if (first.pr != NoProc) {
11438 DoSleep( appData.delayBeforeQuit );
11439 SendToProgram("quit\n", &first);
11440 DestroyChildProcess(first.pr, 4 + first.useSigterm);
11441 first.reload = TRUE;
11445 if (second.reuse) {
11446 /* Put second chess program into idle state */
11447 if (second.pr != NoProc &&
11448 gameMode == TwoMachinesPlay) {
11449 SendToProgram("force\n", &second);
11450 if (second.usePing) {
11452 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
11453 SendToProgram(buf, &second);
11456 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
11457 /* Kill off second chess program */
11458 if (second.isr != NULL)
11459 RemoveInputSource(second.isr);
11462 if (second.pr != NoProc) {
11463 DoSleep( appData.delayBeforeQuit );
11464 SendToProgram("quit\n", &second);
11465 DestroyChildProcess(second.pr, 4 + second.useSigterm);
11466 second.reload = TRUE;
11468 second.pr = NoProc;
11471 if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
11472 char resChar = '=';
11476 if (first.twoMachinesColor[0] == 'w') {
11479 second.matchWins++;
11484 if (first.twoMachinesColor[0] == 'b') {
11487 second.matchWins++;
11490 case GameUnfinished:
11496 if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
11497 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
11498 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
11499 ReserveGame(nextGame, resChar); // sets nextGame
11500 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
11501 else ranking = strdup("busy"); //suppress popup when aborted but not finished
11502 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
11504 if (nextGame <= appData.matchGames && !abortMatch) {
11505 gameMode = nextGameMode;
11506 matchGame = nextGame; // this will be overruled in tourney mode!
11507 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
11508 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
11509 endingGame = 0; /* [HGM] crash */
11512 gameMode = nextGameMode;
11513 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
11514 first.tidy, second.tidy,
11515 first.matchWins, second.matchWins,
11516 appData.matchGames - (first.matchWins + second.matchWins));
11517 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
11518 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
11519 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
11520 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
11521 first.twoMachinesColor = "black\n";
11522 second.twoMachinesColor = "white\n";
11524 first.twoMachinesColor = "white\n";
11525 second.twoMachinesColor = "black\n";
11529 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
11530 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
11532 gameMode = nextGameMode;
11534 endingGame = 0; /* [HGM] crash */
11535 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
11536 if(matchMode == TRUE) { // match through command line: exit with or without popup
11538 ToNrEvent(forwardMostMove);
11539 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
11541 } else DisplayFatalError(buf, 0, 0);
11542 } else { // match through menu; just stop, with or without popup
11543 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
11546 if(strcmp(ranking, "busy")) DisplayNote(ranking);
11547 } else DisplayNote(buf);
11549 if(ranking) free(ranking);
11553 /* Assumes program was just initialized (initString sent).
11554 Leaves program in force mode. */
11556 FeedMovesToProgram (ChessProgramState *cps, int upto)
11560 if (appData.debugMode)
11561 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
11562 startedFromSetupPosition ? "position and " : "",
11563 backwardMostMove, upto, cps->which);
11564 if(currentlyInitializedVariant != gameInfo.variant) {
11566 // [HGM] variantswitch: make engine aware of new variant
11567 if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
11568 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
11569 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
11570 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
11571 SendToProgram(buf, cps);
11572 currentlyInitializedVariant = gameInfo.variant;
11574 SendToProgram("force\n", cps);
11575 if (startedFromSetupPosition) {
11576 SendBoard(cps, backwardMostMove);
11577 if (appData.debugMode) {
11578 fprintf(debugFP, "feedMoves\n");
11581 for (i = backwardMostMove; i < upto; i++) {
11582 SendMoveToProgram(i, cps);
11588 ResurrectChessProgram ()
11590 /* The chess program may have exited.
11591 If so, restart it and feed it all the moves made so far. */
11592 static int doInit = 0;
11594 if (appData.noChessProgram) return 1;
11596 if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
11597 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
11598 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
11599 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
11601 if (first.pr != NoProc) return 1;
11602 StartChessProgram(&first);
11604 InitChessProgram(&first, FALSE);
11605 FeedMovesToProgram(&first, currentMove);
11607 if (!first.sendTime) {
11608 /* can't tell gnuchess what its clock should read,
11609 so we bow to its notion. */
11611 timeRemaining[0][currentMove] = whiteTimeRemaining;
11612 timeRemaining[1][currentMove] = blackTimeRemaining;
11615 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
11616 appData.icsEngineAnalyze) && first.analysisSupport) {
11617 SendToProgram("analyze\n", &first);
11618 first.analyzing = TRUE;
11624 * Button procedures
11627 Reset (int redraw, int init)
11631 if (appData.debugMode) {
11632 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
11633 redraw, init, gameMode);
11635 pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
11636 for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
11637 CleanupTail(); // [HGM] vari: delete any stored variations
11638 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
11639 pausing = pauseExamInvalid = FALSE;
11640 startedFromSetupPosition = blackPlaysFirst = FALSE;
11642 whiteFlag = blackFlag = FALSE;
11643 userOfferedDraw = FALSE;
11644 hintRequested = bookRequested = FALSE;
11645 first.maybeThinking = FALSE;
11646 second.maybeThinking = FALSE;
11647 first.bookSuspend = FALSE; // [HGM] book
11648 second.bookSuspend = FALSE;
11649 thinkOutput[0] = NULLCHAR;
11650 lastHint[0] = NULLCHAR;
11651 ClearGameInfo(&gameInfo);
11652 gameInfo.variant = StringToVariant(appData.variant);
11653 if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) gameInfo.variant = VariantUnknown;
11654 ics_user_moved = ics_clock_paused = FALSE;
11655 ics_getting_history = H_FALSE;
11657 white_holding[0] = black_holding[0] = NULLCHAR;
11658 ClearProgramStats();
11659 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
11663 flipView = appData.flipView;
11664 ClearPremoveHighlights();
11665 gotPremove = FALSE;
11666 alarmSounded = FALSE;
11667 killX = killY = -1; // [HGM] lion
11669 GameEnds(EndOfFile, NULL, GE_PLAYER);
11670 if(appData.serverMovesName != NULL) {
11671 /* [HGM] prepare to make moves file for broadcasting */
11672 clock_t t = clock();
11673 if(serverMoves != NULL) fclose(serverMoves);
11674 serverMoves = fopen(appData.serverMovesName, "r");
11675 if(serverMoves != NULL) {
11676 fclose(serverMoves);
11677 /* delay 15 sec before overwriting, so all clients can see end */
11678 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
11680 serverMoves = fopen(appData.serverMovesName, "w");
11684 gameMode = BeginningOfGame;
11686 if(appData.icsActive) gameInfo.variant = VariantNormal;
11687 currentMove = forwardMostMove = backwardMostMove = 0;
11688 MarkTargetSquares(1);
11689 InitPosition(redraw);
11690 for (i = 0; i < MAX_MOVES; i++) {
11691 if (commentList[i] != NULL) {
11692 free(commentList[i]);
11693 commentList[i] = NULL;
11697 timeRemaining[0][0] = whiteTimeRemaining;
11698 timeRemaining[1][0] = blackTimeRemaining;
11700 if (first.pr == NoProc) {
11701 StartChessProgram(&first);
11704 InitChessProgram(&first, startedFromSetupPosition);
11707 DisplayMessage("", "");
11708 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11709 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
11710 ClearMap(); // [HGM] exclude: invalidate map
11714 AutoPlayGameLoop ()
11717 if (!AutoPlayOneMove())
11719 if (matchMode || appData.timeDelay == 0)
11721 if (appData.timeDelay < 0)
11723 StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
11731 ReloadGame(1); // next game
11737 int fromX, fromY, toX, toY;
11739 if (appData.debugMode) {
11740 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
11743 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
11746 if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
11747 pvInfoList[currentMove].depth = programStats.depth;
11748 pvInfoList[currentMove].score = programStats.score;
11749 pvInfoList[currentMove].time = 0;
11750 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
11751 else { // append analysis of final position as comment
11753 snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
11754 AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
11756 programStats.depth = 0;
11759 if (currentMove >= forwardMostMove) {
11760 if(gameMode == AnalyzeFile) {
11761 if(appData.loadGameIndex == -1) {
11762 GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
11763 ScheduleDelayedEvent(AnalyzeNextGame, 10);
11765 ExitAnalyzeMode(); SendToProgram("force\n", &first);
11768 // gameMode = EndOfGame;
11769 // ModeHighlight();
11771 /* [AS] Clear current move marker at the end of a game */
11772 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
11777 toX = moveList[currentMove][2] - AAA;
11778 toY = moveList[currentMove][3] - ONE;
11780 if (moveList[currentMove][1] == '@') {
11781 if (appData.highlightLastMove) {
11782 SetHighlights(-1, -1, toX, toY);
11785 int viaX = moveList[currentMove][5] - AAA;
11786 int viaY = moveList[currentMove][6] - ONE;
11787 fromX = moveList[currentMove][0] - AAA;
11788 fromY = moveList[currentMove][1] - ONE;
11790 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
11792 if(moveList[currentMove][4] == ';') { // multi-leg
11793 ChessSquare piece = boards[currentMove][viaY][viaX];
11794 AnimateMove(boards[currentMove], fromX, fromY, viaX, viaY);
11795 boards[currentMove][viaY][viaX] = boards[currentMove][fromY][fromX];
11796 AnimateMove(boards[currentMove], fromX=viaX, fromY=viaY, toX, toY);
11797 boards[currentMove][viaY][viaX] = piece;
11799 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11801 if (appData.highlightLastMove) {
11802 SetHighlights(fromX, fromY, toX, toY);
11805 DisplayMove(currentMove);
11806 SendMoveToProgram(currentMove++, &first);
11807 DisplayBothClocks();
11808 DrawPosition(FALSE, boards[currentMove]);
11809 // [HGM] PV info: always display, routine tests if empty
11810 DisplayComment(currentMove - 1, commentList[currentMove]);
11816 LoadGameOneMove (ChessMove readAhead)
11818 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
11819 char promoChar = NULLCHAR;
11820 ChessMove moveType;
11821 char move[MSG_SIZ];
11824 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
11825 gameMode != AnalyzeMode && gameMode != Training) {
11830 yyboardindex = forwardMostMove;
11831 if (readAhead != EndOfFile) {
11832 moveType = readAhead;
11834 if (gameFileFP == NULL)
11836 moveType = (ChessMove) Myylex();
11840 switch (moveType) {
11842 if (appData.debugMode)
11843 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11846 /* append the comment but don't display it */
11847 AppendComment(currentMove, p, FALSE);
11850 case WhiteCapturesEnPassant:
11851 case BlackCapturesEnPassant:
11852 case WhitePromotion:
11853 case BlackPromotion:
11854 case WhiteNonPromotion:
11855 case BlackNonPromotion:
11858 case WhiteKingSideCastle:
11859 case WhiteQueenSideCastle:
11860 case BlackKingSideCastle:
11861 case BlackQueenSideCastle:
11862 case WhiteKingSideCastleWild:
11863 case WhiteQueenSideCastleWild:
11864 case BlackKingSideCastleWild:
11865 case BlackQueenSideCastleWild:
11867 case WhiteHSideCastleFR:
11868 case WhiteASideCastleFR:
11869 case BlackHSideCastleFR:
11870 case BlackASideCastleFR:
11872 if (appData.debugMode)
11873 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11874 fromX = currentMoveString[0] - AAA;
11875 fromY = currentMoveString[1] - ONE;
11876 toX = currentMoveString[2] - AAA;
11877 toY = currentMoveString[3] - ONE;
11878 promoChar = currentMoveString[4];
11879 if(promoChar == ';') promoChar = NULLCHAR;
11884 if (appData.debugMode)
11885 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11886 fromX = moveType == WhiteDrop ?
11887 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11888 (int) CharToPiece(ToLower(currentMoveString[0]));
11890 toX = currentMoveString[2] - AAA;
11891 toY = currentMoveString[3] - ONE;
11897 case GameUnfinished:
11898 if (appData.debugMode)
11899 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
11900 p = strchr(yy_text, '{');
11901 if (p == NULL) p = strchr(yy_text, '(');
11904 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
11906 q = strchr(p, *p == '{' ? '}' : ')');
11907 if (q != NULL) *q = NULLCHAR;
11910 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
11911 GameEnds(moveType, p, GE_FILE);
11913 if (cmailMsgLoaded) {
11915 flipView = WhiteOnMove(currentMove);
11916 if (moveType == GameUnfinished) flipView = !flipView;
11917 if (appData.debugMode)
11918 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
11923 if (appData.debugMode)
11924 fprintf(debugFP, "Parser hit end of file\n");
11925 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11931 if (WhiteOnMove(currentMove)) {
11932 GameEnds(BlackWins, "Black mates", GE_FILE);
11934 GameEnds(WhiteWins, "White mates", GE_FILE);
11938 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11944 case MoveNumberOne:
11945 if (lastLoadGameStart == GNUChessGame) {
11946 /* GNUChessGames have numbers, but they aren't move numbers */
11947 if (appData.debugMode)
11948 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11949 yy_text, (int) moveType);
11950 return LoadGameOneMove(EndOfFile); /* tail recursion */
11952 /* else fall thru */
11957 /* Reached start of next game in file */
11958 if (appData.debugMode)
11959 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
11960 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11966 if (WhiteOnMove(currentMove)) {
11967 GameEnds(BlackWins, "Black mates", GE_FILE);
11969 GameEnds(WhiteWins, "White mates", GE_FILE);
11973 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11979 case PositionDiagram: /* should not happen; ignore */
11980 case ElapsedTime: /* ignore */
11981 case NAG: /* ignore */
11982 if (appData.debugMode)
11983 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11984 yy_text, (int) moveType);
11985 return LoadGameOneMove(EndOfFile); /* tail recursion */
11988 if (appData.testLegality) {
11989 if (appData.debugMode)
11990 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
11991 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11992 (forwardMostMove / 2) + 1,
11993 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11994 DisplayError(move, 0);
11997 if (appData.debugMode)
11998 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
11999 yy_text, currentMoveString);
12000 fromX = currentMoveString[0] - AAA;
12001 fromY = currentMoveString[1] - ONE;
12002 toX = currentMoveString[2] - AAA;
12003 toY = currentMoveString[3] - ONE;
12004 promoChar = currentMoveString[4];
12008 case AmbiguousMove:
12009 if (appData.debugMode)
12010 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
12011 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
12012 (forwardMostMove / 2) + 1,
12013 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12014 DisplayError(move, 0);
12019 case ImpossibleMove:
12020 if (appData.debugMode)
12021 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
12022 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12023 (forwardMostMove / 2) + 1,
12024 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12025 DisplayError(move, 0);
12031 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
12032 DrawPosition(FALSE, boards[currentMove]);
12033 DisplayBothClocks();
12034 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
12035 DisplayComment(currentMove - 1, commentList[currentMove]);
12037 (void) StopLoadGameTimer();
12039 cmailOldMove = forwardMostMove;
12042 /* currentMoveString is set as a side-effect of yylex */
12044 thinkOutput[0] = NULLCHAR;
12045 MakeMove(fromX, fromY, toX, toY, promoChar);
12046 killX = killY = -1; // [HGM] lion: used up
12047 currentMove = forwardMostMove;
12052 /* Load the nth game from the given file */
12054 LoadGameFromFile (char *filename, int n, char *title, int useList)
12059 if (strcmp(filename, "-") == 0) {
12063 f = fopen(filename, "rb");
12065 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12066 DisplayError(buf, errno);
12070 if (fseek(f, 0, 0) == -1) {
12071 /* f is not seekable; probably a pipe */
12074 if (useList && n == 0) {
12075 int error = GameListBuild(f);
12077 DisplayError(_("Cannot build game list"), error);
12078 } else if (!ListEmpty(&gameList) &&
12079 ((ListGame *) gameList.tailPred)->number > 1) {
12080 GameListPopUp(f, title);
12087 return LoadGame(f, n, title, FALSE);
12092 MakeRegisteredMove ()
12094 int fromX, fromY, toX, toY;
12096 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12097 switch (cmailMoveType[lastLoadGameNumber - 1]) {
12100 if (appData.debugMode)
12101 fprintf(debugFP, "Restoring %s for game %d\n",
12102 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12104 thinkOutput[0] = NULLCHAR;
12105 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
12106 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
12107 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
12108 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
12109 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
12110 promoChar = cmailMove[lastLoadGameNumber - 1][4];
12111 MakeMove(fromX, fromY, toX, toY, promoChar);
12112 ShowMove(fromX, fromY, toX, toY);
12114 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12121 if (WhiteOnMove(currentMove)) {
12122 GameEnds(BlackWins, "Black mates", GE_PLAYER);
12124 GameEnds(WhiteWins, "White mates", GE_PLAYER);
12129 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
12136 if (WhiteOnMove(currentMove)) {
12137 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12139 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12144 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12155 /* Wrapper around LoadGame for use when a Cmail message is loaded */
12157 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
12161 if (gameNumber > nCmailGames) {
12162 DisplayError(_("No more games in this message"), 0);
12165 if (f == lastLoadGameFP) {
12166 int offset = gameNumber - lastLoadGameNumber;
12168 cmailMsg[0] = NULLCHAR;
12169 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12170 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12171 nCmailMovesRegistered--;
12173 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12174 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
12175 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
12178 if (! RegisterMove()) return FALSE;
12182 retVal = LoadGame(f, gameNumber, title, useList);
12184 /* Make move registered during previous look at this game, if any */
12185 MakeRegisteredMove();
12187 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
12188 commentList[currentMove]
12189 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
12190 DisplayComment(currentMove - 1, commentList[currentMove]);
12196 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
12198 ReloadGame (int offset)
12200 int gameNumber = lastLoadGameNumber + offset;
12201 if (lastLoadGameFP == NULL) {
12202 DisplayError(_("No game has been loaded yet"), 0);
12205 if (gameNumber <= 0) {
12206 DisplayError(_("Can't back up any further"), 0);
12209 if (cmailMsgLoaded) {
12210 return CmailLoadGame(lastLoadGameFP, gameNumber,
12211 lastLoadGameTitle, lastLoadGameUseList);
12213 return LoadGame(lastLoadGameFP, gameNumber,
12214 lastLoadGameTitle, lastLoadGameUseList);
12218 int keys[EmptySquare+1];
12221 PositionMatches (Board b1, Board b2)
12224 switch(appData.searchMode) {
12225 case 1: return CompareWithRights(b1, b2);
12227 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12228 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
12232 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12233 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
12234 sum += keys[b1[r][f]] - keys[b2[r][f]];
12238 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12239 sum += keys[b1[r][f]] - keys[b2[r][f]];
12251 int pieceList[256], quickBoard[256];
12252 ChessSquare pieceType[256] = { EmptySquare };
12253 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
12254 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
12255 int soughtTotal, turn;
12256 Boolean epOK, flipSearch;
12259 unsigned char piece, to;
12262 #define DSIZE (250000)
12264 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
12265 Move *moveDatabase = initialSpace;
12266 unsigned int movePtr, dataSize = DSIZE;
12269 MakePieceList (Board board, int *counts)
12271 int r, f, n=Q_PROMO, total=0;
12272 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
12273 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12274 int sq = f + (r<<4);
12275 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
12276 quickBoard[sq] = ++n;
12278 pieceType[n] = board[r][f];
12279 counts[board[r][f]]++;
12280 if(board[r][f] == WhiteKing) pieceList[1] = n; else
12281 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
12285 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
12290 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
12292 int sq = fromX + (fromY<<4);
12293 int piece = quickBoard[sq], rook;
12294 quickBoard[sq] = 0;
12295 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
12296 if(piece == pieceList[1] && fromY == toY) {
12297 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12298 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
12299 moveDatabase[movePtr++].piece = Q_WCASTL;
12300 quickBoard[sq] = piece;
12301 piece = quickBoard[from]; quickBoard[from] = 0;
12302 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12303 } else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
12304 quickBoard[sq] = 0; // remove Rook
12305 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
12306 moveDatabase[movePtr++].piece = Q_WCASTL;
12307 quickBoard[sq] = pieceList[1]; // put King
12309 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12312 if(piece == pieceList[2] && fromY == toY) {
12313 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12314 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
12315 moveDatabase[movePtr++].piece = Q_BCASTL;
12316 quickBoard[sq] = piece;
12317 piece = quickBoard[from]; quickBoard[from] = 0;
12318 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12319 } else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
12320 quickBoard[sq] = 0; // remove Rook
12321 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
12322 moveDatabase[movePtr++].piece = Q_BCASTL;
12323 quickBoard[sq] = pieceList[2]; // put King
12325 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12328 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
12329 quickBoard[(fromY<<4)+toX] = 0;
12330 moveDatabase[movePtr].piece = Q_EP;
12331 moveDatabase[movePtr++].to = (fromY<<4)+toX;
12332 moveDatabase[movePtr].to = sq;
12334 if(promoPiece != pieceType[piece]) {
12335 moveDatabase[movePtr++].piece = Q_PROMO;
12336 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
12338 moveDatabase[movePtr].piece = piece;
12339 quickBoard[sq] = piece;
12344 PackGame (Board board)
12346 Move *newSpace = NULL;
12347 moveDatabase[movePtr].piece = 0; // terminate previous game
12348 if(movePtr > dataSize) {
12349 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
12350 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
12351 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
12354 Move *p = moveDatabase, *q = newSpace;
12355 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
12356 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
12357 moveDatabase = newSpace;
12358 } else { // calloc failed, we must be out of memory. Too bad...
12359 dataSize = 0; // prevent calloc events for all subsequent games
12360 return 0; // and signal this one isn't cached
12364 MakePieceList(board, counts);
12369 QuickCompare (Board board, int *minCounts, int *maxCounts)
12370 { // compare according to search mode
12372 switch(appData.searchMode)
12374 case 1: // exact position match
12375 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
12376 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12377 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12380 case 2: // can have extra material on empty squares
12381 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12382 if(board[r][f] == EmptySquare) continue;
12383 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12386 case 3: // material with exact Pawn structure
12387 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12388 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
12389 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12390 } // fall through to material comparison
12391 case 4: // exact material
12392 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
12394 case 6: // material range with given imbalance
12395 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
12396 // fall through to range comparison
12397 case 5: // material range
12398 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
12404 QuickScan (Board board, Move *move)
12405 { // reconstruct game,and compare all positions in it
12406 int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
12408 int piece = move->piece;
12409 int to = move->to, from = pieceList[piece];
12410 if(found < 0) { // if already found just scan to game end for final piece count
12411 if(QuickCompare(soughtBoard, minSought, maxSought) ||
12412 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
12413 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
12414 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
12416 static int lastCounts[EmptySquare+1];
12418 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
12419 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
12420 } else stretch = 0;
12421 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
12422 if(found >= 0 && !appData.minPieces) return found;
12424 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
12425 if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
12426 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
12427 piece = (++move)->piece;
12428 from = pieceList[piece];
12429 counts[pieceType[piece]]--;
12430 pieceType[piece] = (ChessSquare) move->to;
12431 counts[move->to]++;
12432 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
12433 counts[pieceType[quickBoard[to]]]--;
12434 quickBoard[to] = 0; total--;
12437 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
12438 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
12439 from = pieceList[piece]; // so this must be King
12440 quickBoard[from] = 0;
12441 pieceList[piece] = to;
12442 from = pieceList[(++move)->piece]; // for FRC this has to be done here
12443 quickBoard[from] = 0; // rook
12444 quickBoard[to] = piece;
12445 to = move->to; piece = move->piece;
12449 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
12450 if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
12451 quickBoard[from] = 0;
12453 quickBoard[to] = piece;
12454 pieceList[piece] = to;
12464 flipSearch = FALSE;
12465 CopyBoard(soughtBoard, boards[currentMove]);
12466 soughtTotal = MakePieceList(soughtBoard, maxSought);
12467 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
12468 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
12469 CopyBoard(reverseBoard, boards[currentMove]);
12470 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12471 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
12472 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
12473 reverseBoard[r][f] = piece;
12475 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
12476 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
12477 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
12478 || (boards[currentMove][CASTLING][2] == NoRights ||
12479 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
12480 && (boards[currentMove][CASTLING][5] == NoRights ||
12481 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
12484 CopyBoard(flipBoard, soughtBoard);
12485 CopyBoard(rotateBoard, reverseBoard);
12486 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12487 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
12488 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
12491 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
12492 if(appData.searchMode >= 5) {
12493 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
12494 MakePieceList(soughtBoard, minSought);
12495 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
12497 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
12498 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
12501 GameInfo dummyInfo;
12502 static int creatingBook;
12505 GameContainsPosition (FILE *f, ListGame *lg)
12507 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
12508 int fromX, fromY, toX, toY;
12510 static int initDone=FALSE;
12512 // weed out games based on numerical tag comparison
12513 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
12514 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
12515 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
12516 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
12518 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
12521 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
12522 else CopyBoard(boards[scratch], initialPosition); // default start position
12525 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
12526 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
12529 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12530 fseek(f, lg->offset, 0);
12533 yyboardindex = scratch;
12534 quickFlag = plyNr+1;
12539 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
12545 if(plyNr) return -1; // after we have seen moves, this is for new game
12548 case AmbiguousMove: // we cannot reconstruct the game beyond these two
12549 case ImpossibleMove:
12550 case WhiteWins: // game ends here with these four
12553 case GameUnfinished:
12557 if(appData.testLegality) return -1;
12558 case WhiteCapturesEnPassant:
12559 case BlackCapturesEnPassant:
12560 case WhitePromotion:
12561 case BlackPromotion:
12562 case WhiteNonPromotion:
12563 case BlackNonPromotion:
12566 case WhiteKingSideCastle:
12567 case WhiteQueenSideCastle:
12568 case BlackKingSideCastle:
12569 case BlackQueenSideCastle:
12570 case WhiteKingSideCastleWild:
12571 case WhiteQueenSideCastleWild:
12572 case BlackKingSideCastleWild:
12573 case BlackQueenSideCastleWild:
12574 case WhiteHSideCastleFR:
12575 case WhiteASideCastleFR:
12576 case BlackHSideCastleFR:
12577 case BlackASideCastleFR:
12578 fromX = currentMoveString[0] - AAA;
12579 fromY = currentMoveString[1] - ONE;
12580 toX = currentMoveString[2] - AAA;
12581 toY = currentMoveString[3] - ONE;
12582 promoChar = currentMoveString[4];
12586 fromX = next == WhiteDrop ?
12587 (int) CharToPiece(ToUpper(currentMoveString[0])) :
12588 (int) CharToPiece(ToLower(currentMoveString[0]));
12590 toX = currentMoveString[2] - AAA;
12591 toY = currentMoveString[3] - ONE;
12595 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
12597 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
12598 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12599 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
12600 if(appData.findMirror) {
12601 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
12602 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
12607 /* Load the nth game from open file f */
12609 LoadGame (FILE *f, int gameNumber, char *title, int useList)
12613 int gn = gameNumber;
12614 ListGame *lg = NULL;
12615 int numPGNTags = 0;
12617 GameMode oldGameMode;
12618 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
12620 if (appData.debugMode)
12621 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
12623 if (gameMode == Training )
12624 SetTrainingModeOff();
12626 oldGameMode = gameMode;
12627 if (gameMode != BeginningOfGame) {
12628 Reset(FALSE, TRUE);
12630 killX = killY = -1; // [HGM] lion: in case we did not Reset
12633 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
12634 fclose(lastLoadGameFP);
12638 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
12641 fseek(f, lg->offset, 0);
12642 GameListHighlight(gameNumber);
12643 pos = lg->position;
12647 if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
12648 appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
12650 DisplayError(_("Game number out of range"), 0);
12655 if (fseek(f, 0, 0) == -1) {
12656 if (f == lastLoadGameFP ?
12657 gameNumber == lastLoadGameNumber + 1 :
12661 DisplayError(_("Can't seek on game file"), 0);
12666 lastLoadGameFP = f;
12667 lastLoadGameNumber = gameNumber;
12668 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
12669 lastLoadGameUseList = useList;
12673 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
12674 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
12675 lg->gameInfo.black);
12677 } else if (*title != NULLCHAR) {
12678 if (gameNumber > 1) {
12679 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
12682 DisplayTitle(title);
12686 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
12687 gameMode = PlayFromGameFile;
12691 currentMove = forwardMostMove = backwardMostMove = 0;
12692 CopyBoard(boards[0], initialPosition);
12696 * Skip the first gn-1 games in the file.
12697 * Also skip over anything that precedes an identifiable
12698 * start of game marker, to avoid being confused by
12699 * garbage at the start of the file. Currently
12700 * recognized start of game markers are the move number "1",
12701 * the pattern "gnuchess .* game", the pattern
12702 * "^[#;%] [^ ]* game file", and a PGN tag block.
12703 * A game that starts with one of the latter two patterns
12704 * will also have a move number 1, possibly
12705 * following a position diagram.
12706 * 5-4-02: Let's try being more lenient and allowing a game to
12707 * start with an unnumbered move. Does that break anything?
12709 cm = lastLoadGameStart = EndOfFile;
12711 yyboardindex = forwardMostMove;
12712 cm = (ChessMove) Myylex();
12715 if (cmailMsgLoaded) {
12716 nCmailGames = CMAIL_MAX_GAMES - gn;
12719 DisplayError(_("Game not found in file"), 0);
12726 lastLoadGameStart = cm;
12729 case MoveNumberOne:
12730 switch (lastLoadGameStart) {
12735 case MoveNumberOne:
12737 gn--; /* count this game */
12738 lastLoadGameStart = cm;
12747 switch (lastLoadGameStart) {
12750 case MoveNumberOne:
12752 gn--; /* count this game */
12753 lastLoadGameStart = cm;
12756 lastLoadGameStart = cm; /* game counted already */
12764 yyboardindex = forwardMostMove;
12765 cm = (ChessMove) Myylex();
12766 } while (cm == PGNTag || cm == Comment);
12773 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
12774 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
12775 != CMAIL_OLD_RESULT) {
12777 cmailResult[ CMAIL_MAX_GAMES
12778 - gn - 1] = CMAIL_OLD_RESULT;
12785 /* Only a NormalMove can be at the start of a game
12786 * without a position diagram. */
12787 if (lastLoadGameStart == EndOfFile ) {
12789 lastLoadGameStart = MoveNumberOne;
12798 if (appData.debugMode)
12799 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
12801 if (cm == XBoardGame) {
12802 /* Skip any header junk before position diagram and/or move 1 */
12804 yyboardindex = forwardMostMove;
12805 cm = (ChessMove) Myylex();
12807 if (cm == EndOfFile ||
12808 cm == GNUChessGame || cm == XBoardGame) {
12809 /* Empty game; pretend end-of-file and handle later */
12814 if (cm == MoveNumberOne || cm == PositionDiagram ||
12815 cm == PGNTag || cm == Comment)
12818 } else if (cm == GNUChessGame) {
12819 if (gameInfo.event != NULL) {
12820 free(gameInfo.event);
12822 gameInfo.event = StrSave(yy_text);
12825 startedFromSetupPosition = FALSE;
12826 while (cm == PGNTag) {
12827 if (appData.debugMode)
12828 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
12829 err = ParsePGNTag(yy_text, &gameInfo);
12830 if (!err) numPGNTags++;
12832 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
12833 if(gameInfo.variant != oldVariant) {
12834 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
12835 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
12836 InitPosition(TRUE);
12837 oldVariant = gameInfo.variant;
12838 if (appData.debugMode)
12839 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
12843 if (gameInfo.fen != NULL) {
12844 Board initial_position;
12845 startedFromSetupPosition = TRUE;
12846 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
12848 DisplayError(_("Bad FEN position in file"), 0);
12851 CopyBoard(boards[0], initial_position);
12852 if (blackPlaysFirst) {
12853 currentMove = forwardMostMove = backwardMostMove = 1;
12854 CopyBoard(boards[1], initial_position);
12855 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12856 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12857 timeRemaining[0][1] = whiteTimeRemaining;
12858 timeRemaining[1][1] = blackTimeRemaining;
12859 if (commentList[0] != NULL) {
12860 commentList[1] = commentList[0];
12861 commentList[0] = NULL;
12864 currentMove = forwardMostMove = backwardMostMove = 0;
12866 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
12868 initialRulePlies = FENrulePlies;
12869 for( i=0; i< nrCastlingRights; i++ )
12870 initialRights[i] = initial_position[CASTLING][i];
12872 yyboardindex = forwardMostMove;
12873 free(gameInfo.fen);
12874 gameInfo.fen = NULL;
12877 yyboardindex = forwardMostMove;
12878 cm = (ChessMove) Myylex();
12880 /* Handle comments interspersed among the tags */
12881 while (cm == Comment) {
12883 if (appData.debugMode)
12884 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12886 AppendComment(currentMove, p, FALSE);
12887 yyboardindex = forwardMostMove;
12888 cm = (ChessMove) Myylex();
12892 /* don't rely on existence of Event tag since if game was
12893 * pasted from clipboard the Event tag may not exist
12895 if (numPGNTags > 0){
12897 if (gameInfo.variant == VariantNormal) {
12898 VariantClass v = StringToVariant(gameInfo.event);
12899 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
12900 if(v < VariantShogi) gameInfo.variant = v;
12903 if( appData.autoDisplayTags ) {
12904 tags = PGNTags(&gameInfo);
12905 TagsPopUp(tags, CmailMsg());
12910 /* Make something up, but don't display it now */
12915 if (cm == PositionDiagram) {
12918 Board initial_position;
12920 if (appData.debugMode)
12921 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
12923 if (!startedFromSetupPosition) {
12925 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
12926 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
12937 initial_position[i][j++] = CharToPiece(*p);
12940 while (*p == ' ' || *p == '\t' ||
12941 *p == '\n' || *p == '\r') p++;
12943 if (strncmp(p, "black", strlen("black"))==0)
12944 blackPlaysFirst = TRUE;
12946 blackPlaysFirst = FALSE;
12947 startedFromSetupPosition = TRUE;
12949 CopyBoard(boards[0], initial_position);
12950 if (blackPlaysFirst) {
12951 currentMove = forwardMostMove = backwardMostMove = 1;
12952 CopyBoard(boards[1], initial_position);
12953 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12954 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12955 timeRemaining[0][1] = whiteTimeRemaining;
12956 timeRemaining[1][1] = blackTimeRemaining;
12957 if (commentList[0] != NULL) {
12958 commentList[1] = commentList[0];
12959 commentList[0] = NULL;
12962 currentMove = forwardMostMove = backwardMostMove = 0;
12965 yyboardindex = forwardMostMove;
12966 cm = (ChessMove) Myylex();
12969 if(!creatingBook) {
12970 if (first.pr == NoProc) {
12971 StartChessProgram(&first);
12973 InitChessProgram(&first, FALSE);
12974 SendToProgram("force\n", &first);
12975 if (startedFromSetupPosition) {
12976 SendBoard(&first, forwardMostMove);
12977 if (appData.debugMode) {
12978 fprintf(debugFP, "Load Game\n");
12980 DisplayBothClocks();
12984 /* [HGM] server: flag to write setup moves in broadcast file as one */
12985 loadFlag = appData.suppressLoadMoves;
12987 while (cm == Comment) {
12989 if (appData.debugMode)
12990 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12992 AppendComment(currentMove, p, FALSE);
12993 yyboardindex = forwardMostMove;
12994 cm = (ChessMove) Myylex();
12997 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
12998 cm == WhiteWins || cm == BlackWins ||
12999 cm == GameIsDrawn || cm == GameUnfinished) {
13000 DisplayMessage("", _("No moves in game"));
13001 if (cmailMsgLoaded) {
13002 if (appData.debugMode)
13003 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
13007 DrawPosition(FALSE, boards[currentMove]);
13008 DisplayBothClocks();
13009 gameMode = EditGame;
13016 // [HGM] PV info: routine tests if comment empty
13017 if (!matchMode && (pausing || appData.timeDelay != 0)) {
13018 DisplayComment(currentMove - 1, commentList[currentMove]);
13020 if (!matchMode && appData.timeDelay != 0)
13021 DrawPosition(FALSE, boards[currentMove]);
13023 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
13024 programStats.ok_to_send = 1;
13027 /* if the first token after the PGN tags is a move
13028 * and not move number 1, retrieve it from the parser
13030 if (cm != MoveNumberOne)
13031 LoadGameOneMove(cm);
13033 /* load the remaining moves from the file */
13034 while (LoadGameOneMove(EndOfFile)) {
13035 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13036 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13039 /* rewind to the start of the game */
13040 currentMove = backwardMostMove;
13042 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13044 if (oldGameMode == AnalyzeFile) {
13045 appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
13046 AnalyzeFileEvent();
13048 if (oldGameMode == AnalyzeMode) {
13049 AnalyzeFileEvent();
13052 if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
13053 long int w, b; // [HGM] adjourn: restore saved clock times
13054 char *p = strstr(gameInfo.resultDetails, "(Clocks:");
13055 if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
13056 timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
13057 timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
13061 if(creatingBook) return TRUE;
13062 if (!matchMode && pos > 0) {
13063 ToNrEvent(pos); // [HGM] no autoplay if selected on position
13065 if (matchMode || appData.timeDelay == 0) {
13067 } else if (appData.timeDelay > 0) {
13068 AutoPlayGameLoop();
13071 if (appData.debugMode)
13072 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
13074 loadFlag = 0; /* [HGM] true game starts */
13078 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
13080 ReloadPosition (int offset)
13082 int positionNumber = lastLoadPositionNumber + offset;
13083 if (lastLoadPositionFP == NULL) {
13084 DisplayError(_("No position has been loaded yet"), 0);
13087 if (positionNumber <= 0) {
13088 DisplayError(_("Can't back up any further"), 0);
13091 return LoadPosition(lastLoadPositionFP, positionNumber,
13092 lastLoadPositionTitle);
13095 /* Load the nth position from the given file */
13097 LoadPositionFromFile (char *filename, int n, char *title)
13102 if (strcmp(filename, "-") == 0) {
13103 return LoadPosition(stdin, n, "stdin");
13105 f = fopen(filename, "rb");
13107 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13108 DisplayError(buf, errno);
13111 return LoadPosition(f, n, title);
13116 /* Load the nth position from the given open file, and close it */
13118 LoadPosition (FILE *f, int positionNumber, char *title)
13120 char *p, line[MSG_SIZ];
13121 Board initial_position;
13122 int i, j, fenMode, pn;
13124 if (gameMode == Training )
13125 SetTrainingModeOff();
13127 if (gameMode != BeginningOfGame) {
13128 Reset(FALSE, TRUE);
13130 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
13131 fclose(lastLoadPositionFP);
13133 if (positionNumber == 0) positionNumber = 1;
13134 lastLoadPositionFP = f;
13135 lastLoadPositionNumber = positionNumber;
13136 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
13137 if (first.pr == NoProc && !appData.noChessProgram) {
13138 StartChessProgram(&first);
13139 InitChessProgram(&first, FALSE);
13141 pn = positionNumber;
13142 if (positionNumber < 0) {
13143 /* Negative position number means to seek to that byte offset */
13144 if (fseek(f, -positionNumber, 0) == -1) {
13145 DisplayError(_("Can't seek on position file"), 0);
13150 if (fseek(f, 0, 0) == -1) {
13151 if (f == lastLoadPositionFP ?
13152 positionNumber == lastLoadPositionNumber + 1 :
13153 positionNumber == 1) {
13156 DisplayError(_("Can't seek on position file"), 0);
13161 /* See if this file is FEN or old-style xboard */
13162 if (fgets(line, MSG_SIZ, f) == NULL) {
13163 DisplayError(_("Position not found in file"), 0);
13166 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
13167 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
13170 if (fenMode || line[0] == '#') pn--;
13172 /* skip positions before number pn */
13173 if (fgets(line, MSG_SIZ, f) == NULL) {
13175 DisplayError(_("Position not found in file"), 0);
13178 if (fenMode || line[0] == '#') pn--;
13183 if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
13184 DisplayError(_("Bad FEN position in file"), 0);
13188 (void) fgets(line, MSG_SIZ, f);
13189 (void) fgets(line, MSG_SIZ, f);
13191 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13192 (void) fgets(line, MSG_SIZ, f);
13193 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
13196 initial_position[i][j++] = CharToPiece(*p);
13200 blackPlaysFirst = FALSE;
13202 (void) fgets(line, MSG_SIZ, f);
13203 if (strncmp(line, "black", strlen("black"))==0)
13204 blackPlaysFirst = TRUE;
13207 startedFromSetupPosition = TRUE;
13209 CopyBoard(boards[0], initial_position);
13210 if (blackPlaysFirst) {
13211 currentMove = forwardMostMove = backwardMostMove = 1;
13212 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13213 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13214 CopyBoard(boards[1], initial_position);
13215 DisplayMessage("", _("Black to play"));
13217 currentMove = forwardMostMove = backwardMostMove = 0;
13218 DisplayMessage("", _("White to play"));
13220 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
13221 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
13222 SendToProgram("force\n", &first);
13223 SendBoard(&first, forwardMostMove);
13225 if (appData.debugMode) {
13227 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
13228 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
13229 fprintf(debugFP, "Load Position\n");
13232 if (positionNumber > 1) {
13233 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
13234 DisplayTitle(line);
13236 DisplayTitle(title);
13238 gameMode = EditGame;
13241 timeRemaining[0][1] = whiteTimeRemaining;
13242 timeRemaining[1][1] = blackTimeRemaining;
13243 DrawPosition(FALSE, boards[currentMove]);
13250 CopyPlayerNameIntoFileName (char **dest, char *src)
13252 while (*src != NULLCHAR && *src != ',') {
13257 *(*dest)++ = *src++;
13263 DefaultFileName (char *ext)
13265 static char def[MSG_SIZ];
13268 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
13270 CopyPlayerNameIntoFileName(&p, gameInfo.white);
13272 CopyPlayerNameIntoFileName(&p, gameInfo.black);
13274 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
13281 /* Save the current game to the given file */
13283 SaveGameToFile (char *filename, int append)
13287 int result, i, t,tot=0;
13289 if (strcmp(filename, "-") == 0) {
13290 return SaveGame(stdout, 0, NULL);
13292 for(i=0; i<10; i++) { // upto 10 tries
13293 f = fopen(filename, append ? "a" : "w");
13294 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
13295 if(f || errno != 13) break;
13296 DoSleep(t = 5 + random()%11); // wait 5-15 msec
13300 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13301 DisplayError(buf, errno);
13304 safeStrCpy(buf, lastMsg, MSG_SIZ);
13305 DisplayMessage(_("Waiting for access to save file"), "");
13306 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
13307 DisplayMessage(_("Saving game"), "");
13308 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
13309 result = SaveGame(f, 0, NULL);
13310 DisplayMessage(buf, "");
13317 SavePart (char *str)
13319 static char buf[MSG_SIZ];
13322 p = strchr(str, ' ');
13323 if (p == NULL) return str;
13324 strncpy(buf, str, p - str);
13325 buf[p - str] = NULLCHAR;
13329 #define PGN_MAX_LINE 75
13331 #define PGN_SIDE_WHITE 0
13332 #define PGN_SIDE_BLACK 1
13335 FindFirstMoveOutOfBook (int side)
13339 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
13340 int index = backwardMostMove;
13341 int has_book_hit = 0;
13343 if( (index % 2) != side ) {
13347 while( index < forwardMostMove ) {
13348 /* Check to see if engine is in book */
13349 int depth = pvInfoList[index].depth;
13350 int score = pvInfoList[index].score;
13356 else if( score == 0 && depth == 63 ) {
13357 in_book = 1; /* Zappa */
13359 else if( score == 2 && depth == 99 ) {
13360 in_book = 1; /* Abrok */
13363 has_book_hit += in_book;
13379 GetOutOfBookInfo (char * buf)
13383 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13385 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
13386 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
13390 if( oob[0] >= 0 || oob[1] >= 0 ) {
13391 for( i=0; i<2; i++ ) {
13395 if( i > 0 && oob[0] >= 0 ) {
13396 strcat( buf, " " );
13399 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
13400 sprintf( buf+strlen(buf), "%s%.2f",
13401 pvInfoList[idx].score >= 0 ? "+" : "",
13402 pvInfoList[idx].score / 100.0 );
13408 /* Save game in PGN style */
13410 SaveGamePGN2 (FILE *f)
13412 int i, offset, linelen, newblock;
13415 int movelen, numlen, blank;
13416 char move_buffer[100]; /* [AS] Buffer for move+PV info */
13418 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13420 PrintPGNTags(f, &gameInfo);
13422 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
13424 if (backwardMostMove > 0 || startedFromSetupPosition) {
13425 char *fen = PositionToFEN(backwardMostMove, NULL, 1);
13426 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
13427 fprintf(f, "\n{--------------\n");
13428 PrintPosition(f, backwardMostMove);
13429 fprintf(f, "--------------}\n");
13433 /* [AS] Out of book annotation */
13434 if( appData.saveOutOfBookInfo ) {
13437 GetOutOfBookInfo( buf );
13439 if( buf[0] != '\0' ) {
13440 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
13447 i = backwardMostMove;
13451 while (i < forwardMostMove) {
13452 /* Print comments preceding this move */
13453 if (commentList[i] != NULL) {
13454 if (linelen > 0) fprintf(f, "\n");
13455 fprintf(f, "%s", commentList[i]);
13460 /* Format move number */
13462 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
13465 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
13467 numtext[0] = NULLCHAR;
13469 numlen = strlen(numtext);
13472 /* Print move number */
13473 blank = linelen > 0 && numlen > 0;
13474 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
13483 fprintf(f, "%s", numtext);
13487 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
13488 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
13491 blank = linelen > 0 && movelen > 0;
13492 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
13501 fprintf(f, "%s", move_buffer);
13502 linelen += movelen;
13504 /* [AS] Add PV info if present */
13505 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
13506 /* [HGM] add time */
13507 char buf[MSG_SIZ]; int seconds;
13509 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
13515 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
13518 seconds = (seconds + 4)/10; // round to full seconds
13520 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
13522 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
13525 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
13526 pvInfoList[i].score >= 0 ? "+" : "",
13527 pvInfoList[i].score / 100.0,
13528 pvInfoList[i].depth,
13531 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
13533 /* Print score/depth */
13534 blank = linelen > 0 && movelen > 0;
13535 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
13544 fprintf(f, "%s", move_buffer);
13545 linelen += movelen;
13551 /* Start a new line */
13552 if (linelen > 0) fprintf(f, "\n");
13554 /* Print comments after last move */
13555 if (commentList[i] != NULL) {
13556 fprintf(f, "%s\n", commentList[i]);
13560 if (gameInfo.resultDetails != NULL &&
13561 gameInfo.resultDetails[0] != NULLCHAR) {
13562 char buf[MSG_SIZ], *p = gameInfo.resultDetails;
13563 if(gameInfo.result == GameUnfinished && appData.clockMode &&
13564 (gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
13565 snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
13566 fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
13568 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13572 /* Save game in PGN style and close the file */
13574 SaveGamePGN (FILE *f)
13578 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13582 /* Save game in old style and close the file */
13584 SaveGameOldStyle (FILE *f)
13589 tm = time((time_t *) NULL);
13591 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
13594 if (backwardMostMove > 0 || startedFromSetupPosition) {
13595 fprintf(f, "\n[--------------\n");
13596 PrintPosition(f, backwardMostMove);
13597 fprintf(f, "--------------]\n");
13602 i = backwardMostMove;
13603 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13605 while (i < forwardMostMove) {
13606 if (commentList[i] != NULL) {
13607 fprintf(f, "[%s]\n", commentList[i]);
13610 if ((i % 2) == 1) {
13611 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
13614 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
13616 if (commentList[i] != NULL) {
13620 if (i >= forwardMostMove) {
13624 fprintf(f, "%s\n", parseList[i]);
13629 if (commentList[i] != NULL) {
13630 fprintf(f, "[%s]\n", commentList[i]);
13633 /* This isn't really the old style, but it's close enough */
13634 if (gameInfo.resultDetails != NULL &&
13635 gameInfo.resultDetails[0] != NULLCHAR) {
13636 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
13637 gameInfo.resultDetails);
13639 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13646 /* Save the current game to open file f and close the file */
13648 SaveGame (FILE *f, int dummy, char *dummy2)
13650 if (gameMode == EditPosition) EditPositionDone(TRUE);
13651 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13652 if (appData.oldSaveStyle)
13653 return SaveGameOldStyle(f);
13655 return SaveGamePGN(f);
13658 /* Save the current position to the given file */
13660 SavePositionToFile (char *filename)
13665 if (strcmp(filename, "-") == 0) {
13666 return SavePosition(stdout, 0, NULL);
13668 f = fopen(filename, "a");
13670 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13671 DisplayError(buf, errno);
13674 safeStrCpy(buf, lastMsg, MSG_SIZ);
13675 DisplayMessage(_("Waiting for access to save file"), "");
13676 flock(fileno(f), LOCK_EX); // [HGM] lock
13677 DisplayMessage(_("Saving position"), "");
13678 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
13679 SavePosition(f, 0, NULL);
13680 DisplayMessage(buf, "");
13686 /* Save the current position to the given open file and close the file */
13688 SavePosition (FILE *f, int dummy, char *dummy2)
13693 if (gameMode == EditPosition) EditPositionDone(TRUE);
13694 if (appData.oldSaveStyle) {
13695 tm = time((time_t *) NULL);
13697 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
13699 fprintf(f, "[--------------\n");
13700 PrintPosition(f, currentMove);
13701 fprintf(f, "--------------]\n");
13703 fen = PositionToFEN(currentMove, NULL, 1);
13704 fprintf(f, "%s\n", fen);
13712 ReloadCmailMsgEvent (int unregister)
13715 static char *inFilename = NULL;
13716 static char *outFilename;
13718 struct stat inbuf, outbuf;
13721 /* Any registered moves are unregistered if unregister is set, */
13722 /* i.e. invoked by the signal handler */
13724 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13725 cmailMoveRegistered[i] = FALSE;
13726 if (cmailCommentList[i] != NULL) {
13727 free(cmailCommentList[i]);
13728 cmailCommentList[i] = NULL;
13731 nCmailMovesRegistered = 0;
13734 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13735 cmailResult[i] = CMAIL_NOT_RESULT;
13739 if (inFilename == NULL) {
13740 /* Because the filenames are static they only get malloced once */
13741 /* and they never get freed */
13742 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
13743 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
13745 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
13746 sprintf(outFilename, "%s.out", appData.cmailGameName);
13749 status = stat(outFilename, &outbuf);
13751 cmailMailedMove = FALSE;
13753 status = stat(inFilename, &inbuf);
13754 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
13757 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
13758 counts the games, notes how each one terminated, etc.
13760 It would be nice to remove this kludge and instead gather all
13761 the information while building the game list. (And to keep it
13762 in the game list nodes instead of having a bunch of fixed-size
13763 parallel arrays.) Note this will require getting each game's
13764 termination from the PGN tags, as the game list builder does
13765 not process the game moves. --mann
13767 cmailMsgLoaded = TRUE;
13768 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
13770 /* Load first game in the file or popup game menu */
13771 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
13773 #endif /* !WIN32 */
13781 char string[MSG_SIZ];
13783 if ( cmailMailedMove
13784 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
13785 return TRUE; /* Allow free viewing */
13788 /* Unregister move to ensure that we don't leave RegisterMove */
13789 /* with the move registered when the conditions for registering no */
13791 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
13792 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
13793 nCmailMovesRegistered --;
13795 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
13797 free(cmailCommentList[lastLoadGameNumber - 1]);
13798 cmailCommentList[lastLoadGameNumber - 1] = NULL;
13802 if (cmailOldMove == -1) {
13803 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
13807 if (currentMove > cmailOldMove + 1) {
13808 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
13812 if (currentMove < cmailOldMove) {
13813 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
13817 if (forwardMostMove > currentMove) {
13818 /* Silently truncate extra moves */
13822 if ( (currentMove == cmailOldMove + 1)
13823 || ( (currentMove == cmailOldMove)
13824 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
13825 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
13826 if (gameInfo.result != GameUnfinished) {
13827 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
13830 if (commentList[currentMove] != NULL) {
13831 cmailCommentList[lastLoadGameNumber - 1]
13832 = StrSave(commentList[currentMove]);
13834 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
13836 if (appData.debugMode)
13837 fprintf(debugFP, "Saving %s for game %d\n",
13838 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
13840 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
13842 f = fopen(string, "w");
13843 if (appData.oldSaveStyle) {
13844 SaveGameOldStyle(f); /* also closes the file */
13846 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
13847 f = fopen(string, "w");
13848 SavePosition(f, 0, NULL); /* also closes the file */
13850 fprintf(f, "{--------------\n");
13851 PrintPosition(f, currentMove);
13852 fprintf(f, "--------------}\n\n");
13854 SaveGame(f, 0, NULL); /* also closes the file*/
13857 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
13858 nCmailMovesRegistered ++;
13859 } else if (nCmailGames == 1) {
13860 DisplayError(_("You have not made a move yet"), 0);
13871 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
13872 FILE *commandOutput;
13873 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
13874 int nBytes = 0; /* Suppress warnings on uninitialized variables */
13880 if (! cmailMsgLoaded) {
13881 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
13885 if (nCmailGames == nCmailResults) {
13886 DisplayError(_("No unfinished games"), 0);
13890 #if CMAIL_PROHIBIT_REMAIL
13891 if (cmailMailedMove) {
13892 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);
13893 DisplayError(msg, 0);
13898 if (! (cmailMailedMove || RegisterMove())) return;
13900 if ( cmailMailedMove
13901 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
13902 snprintf(string, MSG_SIZ, partCommandString,
13903 appData.debugMode ? " -v" : "", appData.cmailGameName);
13904 commandOutput = popen(string, "r");
13906 if (commandOutput == NULL) {
13907 DisplayError(_("Failed to invoke cmail"), 0);
13909 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
13910 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
13912 if (nBuffers > 1) {
13913 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
13914 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
13915 nBytes = MSG_SIZ - 1;
13917 (void) memcpy(msg, buffer, nBytes);
13919 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
13921 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
13922 cmailMailedMove = TRUE; /* Prevent >1 moves */
13925 for (i = 0; i < nCmailGames; i ++) {
13926 if (cmailResult[i] == CMAIL_NOT_RESULT) {
13931 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
13933 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
13935 appData.cmailGameName,
13937 LoadGameFromFile(buffer, 1, buffer, FALSE);
13938 cmailMsgLoaded = FALSE;
13942 DisplayInformation(msg);
13943 pclose(commandOutput);
13946 if ((*cmailMsg) != '\0') {
13947 DisplayInformation(cmailMsg);
13952 #endif /* !WIN32 */
13961 int prependComma = 0;
13963 char string[MSG_SIZ]; /* Space for game-list */
13966 if (!cmailMsgLoaded) return "";
13968 if (cmailMailedMove) {
13969 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
13971 /* Create a list of games left */
13972 snprintf(string, MSG_SIZ, "[");
13973 for (i = 0; i < nCmailGames; i ++) {
13974 if (! ( cmailMoveRegistered[i]
13975 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
13976 if (prependComma) {
13977 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
13979 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
13983 strcat(string, number);
13986 strcat(string, "]");
13988 if (nCmailMovesRegistered + nCmailResults == 0) {
13989 switch (nCmailGames) {
13991 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
13995 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
13999 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
14004 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
14006 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
14011 if (nCmailResults == nCmailGames) {
14012 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
14014 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
14019 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
14031 if (gameMode == Training)
14032 SetTrainingModeOff();
14035 cmailMsgLoaded = FALSE;
14036 if (appData.icsActive) {
14037 SendToICS(ics_prefix);
14038 SendToICS("refresh\n");
14043 ExitEvent (int status)
14047 /* Give up on clean exit */
14051 /* Keep trying for clean exit */
14055 if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
14056 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
14058 if (telnetISR != NULL) {
14059 RemoveInputSource(telnetISR);
14061 if (icsPR != NoProc) {
14062 DestroyChildProcess(icsPR, TRUE);
14065 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
14066 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
14068 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
14069 /* make sure this other one finishes before killing it! */
14070 if(endingGame) { int count = 0;
14071 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
14072 while(endingGame && count++ < 10) DoSleep(1);
14073 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
14076 /* Kill off chess programs */
14077 if (first.pr != NoProc) {
14080 DoSleep( appData.delayBeforeQuit );
14081 SendToProgram("quit\n", &first);
14082 DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
14084 if (second.pr != NoProc) {
14085 DoSleep( appData.delayBeforeQuit );
14086 SendToProgram("quit\n", &second);
14087 DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
14089 if (first.isr != NULL) {
14090 RemoveInputSource(first.isr);
14092 if (second.isr != NULL) {
14093 RemoveInputSource(second.isr);
14096 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
14097 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
14099 ShutDownFrontEnd();
14104 PauseEngine (ChessProgramState *cps)
14106 SendToProgram("pause\n", cps);
14111 UnPauseEngine (ChessProgramState *cps)
14113 SendToProgram("resume\n", cps);
14120 if (appData.debugMode)
14121 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
14125 if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
14127 if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
14128 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
14129 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
14131 if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
14132 HandleMachineMove(stashedInputMove, stalledEngine);
14133 stalledEngine = NULL;
14136 if (gameMode == MachinePlaysWhite ||
14137 gameMode == TwoMachinesPlay ||
14138 gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
14139 if(first.pause) UnPauseEngine(&first);
14140 else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
14141 if(second.pause) UnPauseEngine(&second);
14142 else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
14145 DisplayBothClocks();
14147 if (gameMode == PlayFromGameFile) {
14148 if (appData.timeDelay >= 0)
14149 AutoPlayGameLoop();
14150 } else if (gameMode == IcsExamining && pauseExamInvalid) {
14151 Reset(FALSE, TRUE);
14152 SendToICS(ics_prefix);
14153 SendToICS("refresh\n");
14154 } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
14155 ForwardInner(forwardMostMove);
14157 pauseExamInvalid = FALSE;
14159 switch (gameMode) {
14163 pauseExamForwardMostMove = forwardMostMove;
14164 pauseExamInvalid = FALSE;
14167 case IcsPlayingWhite:
14168 case IcsPlayingBlack:
14172 case PlayFromGameFile:
14173 (void) StopLoadGameTimer();
14177 case BeginningOfGame:
14178 if (appData.icsActive) return;
14179 /* else fall through */
14180 case MachinePlaysWhite:
14181 case MachinePlaysBlack:
14182 case TwoMachinesPlay:
14183 if (forwardMostMove == 0)
14184 return; /* don't pause if no one has moved */
14185 if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
14186 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
14187 if(onMove->pause) { // thinking engine can be paused
14188 PauseEngine(onMove); // do it
14189 if(onMove->other->pause) // pondering opponent can always be paused immediately
14190 PauseEngine(onMove->other);
14192 SendToProgram("easy\n", onMove->other);
14194 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
14195 } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
14197 PauseEngine(&first);
14199 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
14200 } else { // human on move, pause pondering by either method
14202 PauseEngine(&first);
14203 else if(appData.ponderNextMove)
14204 SendToProgram("easy\n", &first);
14207 // if no immediate pausing is possible, wait for engine to move, and stop clocks then
14217 EditCommentEvent ()
14219 char title[MSG_SIZ];
14221 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
14222 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
14224 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
14225 WhiteOnMove(currentMove - 1) ? " " : ".. ",
14226 parseList[currentMove - 1]);
14229 EditCommentPopUp(currentMove, title, commentList[currentMove]);
14236 char *tags = PGNTags(&gameInfo);
14238 EditTagsPopUp(tags, NULL);
14245 if(second.analyzing) {
14246 SendToProgram("exit\n", &second);
14247 second.analyzing = FALSE;
14249 if (second.pr == NoProc) StartChessProgram(&second);
14250 InitChessProgram(&second, FALSE);
14251 FeedMovesToProgram(&second, currentMove);
14253 SendToProgram("analyze\n", &second);
14254 second.analyzing = TRUE;
14258 /* Toggle ShowThinking */
14260 ToggleShowThinking()
14262 appData.showThinking = !appData.showThinking;
14263 ShowThinkingEvent();
14267 AnalyzeModeEvent ()
14271 if (!first.analysisSupport) {
14272 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14273 DisplayError(buf, 0);
14276 /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
14277 if (appData.icsActive) {
14278 if (gameMode != IcsObserving) {
14279 snprintf(buf, MSG_SIZ, _("You are not observing a game"));
14280 DisplayError(buf, 0);
14282 if (appData.icsEngineAnalyze) {
14283 if (appData.debugMode)
14284 fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
14290 /* if enable, user wants to disable icsEngineAnalyze */
14291 if (appData.icsEngineAnalyze) {
14296 appData.icsEngineAnalyze = TRUE;
14297 if (appData.debugMode)
14298 fprintf(debugFP, "ICS engine analyze starting... \n");
14301 if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
14302 if (appData.noChessProgram || gameMode == AnalyzeMode)
14305 if (gameMode != AnalyzeFile) {
14306 if (!appData.icsEngineAnalyze) {
14308 if (gameMode != EditGame) return 0;
14310 if (!appData.showThinking) ToggleShowThinking();
14311 ResurrectChessProgram();
14312 SendToProgram("analyze\n", &first);
14313 first.analyzing = TRUE;
14314 /*first.maybeThinking = TRUE;*/
14315 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14316 EngineOutputPopUp();
14318 if (!appData.icsEngineAnalyze) {
14319 gameMode = AnalyzeMode;
14320 ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
14326 StartAnalysisClock();
14327 GetTimeMark(&lastNodeCountTime);
14333 AnalyzeFileEvent ()
14335 if (appData.noChessProgram || gameMode == AnalyzeFile)
14338 if (!first.analysisSupport) {
14340 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14341 DisplayError(buf, 0);
14345 if (gameMode != AnalyzeMode) {
14346 keepInfo = 1; // mere annotating should not alter PGN tags
14349 if (gameMode != EditGame) return;
14350 if (!appData.showThinking) ToggleShowThinking();
14351 ResurrectChessProgram();
14352 SendToProgram("analyze\n", &first);
14353 first.analyzing = TRUE;
14354 /*first.maybeThinking = TRUE;*/
14355 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14356 EngineOutputPopUp();
14358 gameMode = AnalyzeFile;
14362 StartAnalysisClock();
14363 GetTimeMark(&lastNodeCountTime);
14365 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
14366 AnalysisPeriodicEvent(1);
14370 MachineWhiteEvent ()
14373 char *bookHit = NULL;
14375 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
14379 if (gameMode == PlayFromGameFile ||
14380 gameMode == TwoMachinesPlay ||
14381 gameMode == Training ||
14382 gameMode == AnalyzeMode ||
14383 gameMode == EndOfGame)
14386 if (gameMode == EditPosition)
14387 EditPositionDone(TRUE);
14389 if (!WhiteOnMove(currentMove)) {
14390 DisplayError(_("It is not White's turn"), 0);
14394 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
14397 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14398 gameMode == AnalyzeFile)
14401 ResurrectChessProgram(); /* in case it isn't running */
14402 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
14403 gameMode = MachinePlaysWhite;
14406 gameMode = MachinePlaysWhite;
14410 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14412 if (first.sendName) {
14413 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
14414 SendToProgram(buf, &first);
14416 if (first.sendTime) {
14417 if (first.useColors) {
14418 SendToProgram("black\n", &first); /*gnu kludge*/
14420 SendTimeRemaining(&first, TRUE);
14422 if (first.useColors) {
14423 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
14425 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
14426 SetMachineThinkingEnables();
14427 first.maybeThinking = TRUE;
14431 if (appData.autoFlipView && !flipView) {
14432 flipView = !flipView;
14433 DrawPosition(FALSE, NULL);
14434 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
14437 if(bookHit) { // [HGM] book: simulate book reply
14438 static char bookMove[MSG_SIZ]; // a bit generous?
14440 programStats.nodes = programStats.depth = programStats.time =
14441 programStats.score = programStats.got_only_move = 0;
14442 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14444 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14445 strcat(bookMove, bookHit);
14446 HandleMachineMove(bookMove, &first);
14451 MachineBlackEvent ()
14454 char *bookHit = NULL;
14456 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
14460 if (gameMode == PlayFromGameFile ||
14461 gameMode == TwoMachinesPlay ||
14462 gameMode == Training ||
14463 gameMode == AnalyzeMode ||
14464 gameMode == EndOfGame)
14467 if (gameMode == EditPosition)
14468 EditPositionDone(TRUE);
14470 if (WhiteOnMove(currentMove)) {
14471 DisplayError(_("It is not Black's turn"), 0);
14475 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
14478 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14479 gameMode == AnalyzeFile)
14482 ResurrectChessProgram(); /* in case it isn't running */
14483 gameMode = MachinePlaysBlack;
14487 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14489 if (first.sendName) {
14490 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
14491 SendToProgram(buf, &first);
14493 if (first.sendTime) {
14494 if (first.useColors) {
14495 SendToProgram("white\n", &first); /*gnu kludge*/
14497 SendTimeRemaining(&first, FALSE);
14499 if (first.useColors) {
14500 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
14502 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
14503 SetMachineThinkingEnables();
14504 first.maybeThinking = TRUE;
14507 if (appData.autoFlipView && flipView) {
14508 flipView = !flipView;
14509 DrawPosition(FALSE, NULL);
14510 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
14512 if(bookHit) { // [HGM] book: simulate book reply
14513 static char bookMove[MSG_SIZ]; // a bit generous?
14515 programStats.nodes = programStats.depth = programStats.time =
14516 programStats.score = programStats.got_only_move = 0;
14517 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14519 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14520 strcat(bookMove, bookHit);
14521 HandleMachineMove(bookMove, &first);
14527 DisplayTwoMachinesTitle ()
14530 if (appData.matchGames > 0) {
14531 if(appData.tourneyFile[0]) {
14532 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
14533 gameInfo.white, _("vs."), gameInfo.black,
14534 nextGame+1, appData.matchGames+1,
14535 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
14537 if (first.twoMachinesColor[0] == 'w') {
14538 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
14539 gameInfo.white, _("vs."), gameInfo.black,
14540 first.matchWins, second.matchWins,
14541 matchGame - 1 - (first.matchWins + second.matchWins));
14543 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
14544 gameInfo.white, _("vs."), gameInfo.black,
14545 second.matchWins, first.matchWins,
14546 matchGame - 1 - (first.matchWins + second.matchWins));
14549 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14555 SettingsMenuIfReady ()
14557 if (second.lastPing != second.lastPong) {
14558 DisplayMessage("", _("Waiting for second chess program"));
14559 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
14563 DisplayMessage("", "");
14564 SettingsPopUp(&second);
14568 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
14571 if (cps->pr == NoProc) {
14572 StartChessProgram(cps);
14573 if (cps->protocolVersion == 1) {
14575 ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
14577 /* kludge: allow timeout for initial "feature" command */
14578 if(retry != TwoMachinesEventIfReady) FreezeUI();
14579 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
14580 DisplayMessage("", buf);
14581 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
14589 TwoMachinesEvent P((void))
14593 ChessProgramState *onmove;
14594 char *bookHit = NULL;
14595 static int stalling = 0;
14599 if (appData.noChessProgram) return;
14601 switch (gameMode) {
14602 case TwoMachinesPlay:
14604 case MachinePlaysWhite:
14605 case MachinePlaysBlack:
14606 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
14607 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
14611 case BeginningOfGame:
14612 case PlayFromGameFile:
14615 if (gameMode != EditGame) return;
14618 EditPositionDone(TRUE);
14629 // forwardMostMove = currentMove;
14630 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
14631 startingEngine = TRUE;
14633 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
14635 if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
14636 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
14637 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14640 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
14642 if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
14643 gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
14644 startingEngine = FALSE;
14645 DisplayError("second engine does not play this", 0);
14650 InitChessProgram(&second, FALSE); // unbalances ping of second engine
14651 SendToProgram("force\n", &second);
14653 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14656 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
14657 if(appData.matchPause>10000 || appData.matchPause<10)
14658 appData.matchPause = 10000; /* [HGM] make pause adjustable */
14659 wait = SubtractTimeMarks(&now, &pauseStart);
14660 if(wait < appData.matchPause) {
14661 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
14664 // we are now committed to starting the game
14666 DisplayMessage("", "");
14667 if (startedFromSetupPosition) {
14668 SendBoard(&second, backwardMostMove);
14669 if (appData.debugMode) {
14670 fprintf(debugFP, "Two Machines\n");
14673 for (i = backwardMostMove; i < forwardMostMove; i++) {
14674 SendMoveToProgram(i, &second);
14677 gameMode = TwoMachinesPlay;
14678 pausing = startingEngine = FALSE;
14679 ModeHighlight(); // [HGM] logo: this triggers display update of logos
14681 DisplayTwoMachinesTitle();
14683 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
14688 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
14689 SendToProgram(first.computerString, &first);
14690 if (first.sendName) {
14691 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
14692 SendToProgram(buf, &first);
14694 SendToProgram(second.computerString, &second);
14695 if (second.sendName) {
14696 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
14697 SendToProgram(buf, &second);
14701 if (!first.sendTime || !second.sendTime) {
14702 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14703 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14705 if (onmove->sendTime) {
14706 if (onmove->useColors) {
14707 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
14709 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
14711 if (onmove->useColors) {
14712 SendToProgram(onmove->twoMachinesColor, onmove);
14714 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
14715 // SendToProgram("go\n", onmove);
14716 onmove->maybeThinking = TRUE;
14717 SetMachineThinkingEnables();
14721 if(bookHit) { // [HGM] book: simulate book reply
14722 static char bookMove[MSG_SIZ]; // a bit generous?
14724 programStats.nodes = programStats.depth = programStats.time =
14725 programStats.score = programStats.got_only_move = 0;
14726 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14728 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14729 strcat(bookMove, bookHit);
14730 savedMessage = bookMove; // args for deferred call
14731 savedState = onmove;
14732 ScheduleDelayedEvent(DeferredBookMove, 1);
14739 if (gameMode == Training) {
14740 SetTrainingModeOff();
14741 gameMode = PlayFromGameFile;
14742 DisplayMessage("", _("Training mode off"));
14744 gameMode = Training;
14745 animateTraining = appData.animate;
14747 /* make sure we are not already at the end of the game */
14748 if (currentMove < forwardMostMove) {
14749 SetTrainingModeOn();
14750 DisplayMessage("", _("Training mode on"));
14752 gameMode = PlayFromGameFile;
14753 DisplayError(_("Already at end of game"), 0);
14762 if (!appData.icsActive) return;
14763 switch (gameMode) {
14764 case IcsPlayingWhite:
14765 case IcsPlayingBlack:
14768 case BeginningOfGame:
14776 EditPositionDone(TRUE);
14789 gameMode = IcsIdle;
14799 switch (gameMode) {
14801 SetTrainingModeOff();
14803 case MachinePlaysWhite:
14804 case MachinePlaysBlack:
14805 case BeginningOfGame:
14806 SendToProgram("force\n", &first);
14807 SetUserThinkingEnables();
14809 case PlayFromGameFile:
14810 (void) StopLoadGameTimer();
14811 if (gameFileFP != NULL) {
14816 EditPositionDone(TRUE);
14821 SendToProgram("force\n", &first);
14823 case TwoMachinesPlay:
14824 GameEnds(EndOfFile, NULL, GE_PLAYER);
14825 ResurrectChessProgram();
14826 SetUserThinkingEnables();
14829 ResurrectChessProgram();
14831 case IcsPlayingBlack:
14832 case IcsPlayingWhite:
14833 DisplayError(_("Warning: You are still playing a game"), 0);
14836 DisplayError(_("Warning: You are still observing a game"), 0);
14839 DisplayError(_("Warning: You are still examining a game"), 0);
14850 first.offeredDraw = second.offeredDraw = 0;
14852 if (gameMode == PlayFromGameFile) {
14853 whiteTimeRemaining = timeRemaining[0][currentMove];
14854 blackTimeRemaining = timeRemaining[1][currentMove];
14858 if (gameMode == MachinePlaysWhite ||
14859 gameMode == MachinePlaysBlack ||
14860 gameMode == TwoMachinesPlay ||
14861 gameMode == EndOfGame) {
14862 i = forwardMostMove;
14863 while (i > currentMove) {
14864 SendToProgram("undo\n", &first);
14867 if(!adjustedClock) {
14868 whiteTimeRemaining = timeRemaining[0][currentMove];
14869 blackTimeRemaining = timeRemaining[1][currentMove];
14870 DisplayBothClocks();
14872 if (whiteFlag || blackFlag) {
14873 whiteFlag = blackFlag = 0;
14878 gameMode = EditGame;
14885 EditPositionEvent ()
14887 if (gameMode == EditPosition) {
14893 if (gameMode != EditGame) return;
14895 gameMode = EditPosition;
14898 if (currentMove > 0)
14899 CopyBoard(boards[0], boards[currentMove]);
14901 blackPlaysFirst = !WhiteOnMove(currentMove);
14903 currentMove = forwardMostMove = backwardMostMove = 0;
14904 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14906 if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
14912 /* [DM] icsEngineAnalyze - possible call from other functions */
14913 if (appData.icsEngineAnalyze) {
14914 appData.icsEngineAnalyze = FALSE;
14916 DisplayMessage("",_("Close ICS engine analyze..."));
14918 if (first.analysisSupport && first.analyzing) {
14919 SendToBoth("exit\n");
14920 first.analyzing = second.analyzing = FALSE;
14922 thinkOutput[0] = NULLCHAR;
14926 EditPositionDone (Boolean fakeRights)
14928 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
14930 startedFromSetupPosition = TRUE;
14931 InitChessProgram(&first, FALSE);
14932 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
14933 boards[0][EP_STATUS] = EP_NONE;
14934 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
14935 if(boards[0][0][BOARD_WIDTH>>1] == king) {
14936 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? BOARD_LEFT : NoRights;
14937 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
14938 } else boards[0][CASTLING][2] = NoRights;
14939 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
14940 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? BOARD_LEFT : NoRights;
14941 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
14942 } else boards[0][CASTLING][5] = NoRights;
14943 if(gameInfo.variant == VariantSChess) {
14945 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // pieces in their original position are assumed virgin
14946 boards[0][VIRGIN][i] = 0;
14947 if(boards[0][0][i] == FIDEArray[0][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_W;
14948 if(boards[0][BOARD_HEIGHT-1][i] == FIDEArray[1][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_B;
14952 SendToProgram("force\n", &first);
14953 if (blackPlaysFirst) {
14954 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
14955 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
14956 currentMove = forwardMostMove = backwardMostMove = 1;
14957 CopyBoard(boards[1], boards[0]);
14959 currentMove = forwardMostMove = backwardMostMove = 0;
14961 SendBoard(&first, forwardMostMove);
14962 if (appData.debugMode) {
14963 fprintf(debugFP, "EditPosDone\n");
14966 DisplayMessage("", "");
14967 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14968 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14969 gameMode = EditGame;
14971 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14972 ClearHighlights(); /* [AS] */
14975 /* Pause for `ms' milliseconds */
14976 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14978 TimeDelay (long ms)
14985 } while (SubtractTimeMarks(&m2, &m1) < ms);
14988 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14990 SendMultiLineToICS (char *buf)
14992 char temp[MSG_SIZ+1], *p;
14999 strncpy(temp, buf, len);
15004 if (*p == '\n' || *p == '\r')
15009 strcat(temp, "\n");
15011 SendToPlayer(temp, strlen(temp));
15015 SetWhiteToPlayEvent ()
15017 if (gameMode == EditPosition) {
15018 blackPlaysFirst = FALSE;
15019 DisplayBothClocks(); /* works because currentMove is 0 */
15020 } else if (gameMode == IcsExamining) {
15021 SendToICS(ics_prefix);
15022 SendToICS("tomove white\n");
15027 SetBlackToPlayEvent ()
15029 if (gameMode == EditPosition) {
15030 blackPlaysFirst = TRUE;
15031 currentMove = 1; /* kludge */
15032 DisplayBothClocks();
15034 } else if (gameMode == IcsExamining) {
15035 SendToICS(ics_prefix);
15036 SendToICS("tomove black\n");
15041 EditPositionMenuEvent (ChessSquare selection, int x, int y)
15044 ChessSquare piece = boards[0][y][x];
15045 static Board erasedBoard, currentBoard, menuBoard, nullBoard;
15046 static int lastVariant;
15048 if (gameMode != EditPosition && gameMode != IcsExamining) return;
15050 switch (selection) {
15052 CopyBoard(currentBoard, boards[0]);
15053 CopyBoard(menuBoard, initialPosition);
15054 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
15055 SendToICS(ics_prefix);
15056 SendToICS("bsetup clear\n");
15057 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
15058 SendToICS(ics_prefix);
15059 SendToICS("clearboard\n");
15062 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
15063 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
15064 for (y = 0; y < BOARD_HEIGHT; y++) {
15065 if (gameMode == IcsExamining) {
15066 if (boards[currentMove][y][x] != EmptySquare) {
15067 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
15072 if(boards[0][y][x] != p) nonEmpty++;
15073 boards[0][y][x] = p;
15077 if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
15079 for(r = 0; r < BOARD_HEIGHT; r++) {
15080 for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates
15081 ChessSquare p = menuBoard[r][x];
15082 for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
15085 DisplayMessage("Clicking clock again restores position", "");
15086 if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
15087 if(!nonEmpty) { // asked to clear an empty board
15088 CopyBoard(boards[0], menuBoard);
15090 if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
15091 CopyBoard(boards[0], initialPosition);
15093 if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
15094 && !CompareBoards(nullBoard, erasedBoard)) {
15095 CopyBoard(boards[0], erasedBoard);
15097 CopyBoard(erasedBoard, currentBoard);
15101 if (gameMode == EditPosition) {
15102 DrawPosition(FALSE, boards[0]);
15107 SetWhiteToPlayEvent();
15111 SetBlackToPlayEvent();
15115 if (gameMode == IcsExamining) {
15116 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15117 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
15120 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15121 if(x == BOARD_LEFT-2) {
15122 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
15123 boards[0][y][1] = 0;
15125 if(x == BOARD_RGHT+1) {
15126 if(y >= gameInfo.holdingsSize) break;
15127 boards[0][y][BOARD_WIDTH-2] = 0;
15130 boards[0][y][x] = EmptySquare;
15131 DrawPosition(FALSE, boards[0]);
15136 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
15137 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
15138 selection = (ChessSquare) (PROMOTED piece);
15139 } else if(piece == EmptySquare) selection = WhiteSilver;
15140 else selection = (ChessSquare)((int)piece - 1);
15144 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
15145 piece > (int)BlackMan && piece <= (int)BlackKing ) {
15146 selection = (ChessSquare) (DEMOTED piece);
15147 } else if(piece == EmptySquare) selection = BlackSilver;
15148 else selection = (ChessSquare)((int)piece + 1);
15153 if(gameInfo.variant == VariantShatranj ||
15154 gameInfo.variant == VariantXiangqi ||
15155 gameInfo.variant == VariantCourier ||
15156 gameInfo.variant == VariantASEAN ||
15157 gameInfo.variant == VariantMakruk )
15158 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
15163 if(gameInfo.variant == VariantXiangqi)
15164 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
15165 if(gameInfo.variant == VariantKnightmate)
15166 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
15169 if (gameMode == IcsExamining) {
15170 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15171 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
15172 PieceToChar(selection), AAA + x, ONE + y);
15175 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15177 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
15178 n = PieceToNumber(selection - BlackPawn);
15179 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
15180 boards[0][BOARD_HEIGHT-1-n][0] = selection;
15181 boards[0][BOARD_HEIGHT-1-n][1]++;
15183 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
15184 n = PieceToNumber(selection);
15185 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
15186 boards[0][n][BOARD_WIDTH-1] = selection;
15187 boards[0][n][BOARD_WIDTH-2]++;
15190 boards[0][y][x] = selection;
15191 DrawPosition(TRUE, boards[0]);
15193 fromX = fromY = -1;
15201 DropMenuEvent (ChessSquare selection, int x, int y)
15203 ChessMove moveType;
15205 switch (gameMode) {
15206 case IcsPlayingWhite:
15207 case MachinePlaysBlack:
15208 if (!WhiteOnMove(currentMove)) {
15209 DisplayMoveError(_("It is Black's turn"));
15212 moveType = WhiteDrop;
15214 case IcsPlayingBlack:
15215 case MachinePlaysWhite:
15216 if (WhiteOnMove(currentMove)) {
15217 DisplayMoveError(_("It is White's turn"));
15220 moveType = BlackDrop;
15223 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
15229 if (moveType == BlackDrop && selection < BlackPawn) {
15230 selection = (ChessSquare) ((int) selection
15231 + (int) BlackPawn - (int) WhitePawn);
15233 if (boards[currentMove][y][x] != EmptySquare) {
15234 DisplayMoveError(_("That square is occupied"));
15238 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
15244 /* Accept a pending offer of any kind from opponent */
15246 if (appData.icsActive) {
15247 SendToICS(ics_prefix);
15248 SendToICS("accept\n");
15249 } else if (cmailMsgLoaded) {
15250 if (currentMove == cmailOldMove &&
15251 commentList[cmailOldMove] != NULL &&
15252 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15253 "Black offers a draw" : "White offers a draw")) {
15255 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15256 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15258 DisplayError(_("There is no pending offer on this move"), 0);
15259 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15262 /* Not used for offers from chess program */
15269 /* Decline a pending offer of any kind from opponent */
15271 if (appData.icsActive) {
15272 SendToICS(ics_prefix);
15273 SendToICS("decline\n");
15274 } else if (cmailMsgLoaded) {
15275 if (currentMove == cmailOldMove &&
15276 commentList[cmailOldMove] != NULL &&
15277 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15278 "Black offers a draw" : "White offers a draw")) {
15280 AppendComment(cmailOldMove, "Draw declined", TRUE);
15281 DisplayComment(cmailOldMove - 1, "Draw declined");
15284 DisplayError(_("There is no pending offer on this move"), 0);
15287 /* Not used for offers from chess program */
15294 /* Issue ICS rematch command */
15295 if (appData.icsActive) {
15296 SendToICS(ics_prefix);
15297 SendToICS("rematch\n");
15304 /* Call your opponent's flag (claim a win on time) */
15305 if (appData.icsActive) {
15306 SendToICS(ics_prefix);
15307 SendToICS("flag\n");
15309 switch (gameMode) {
15312 case MachinePlaysWhite:
15315 GameEnds(GameIsDrawn, "Both players ran out of time",
15318 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
15320 DisplayError(_("Your opponent is not out of time"), 0);
15323 case MachinePlaysBlack:
15326 GameEnds(GameIsDrawn, "Both players ran out of time",
15329 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
15331 DisplayError(_("Your opponent is not out of time"), 0);
15339 ClockClick (int which)
15340 { // [HGM] code moved to back-end from winboard.c
15341 if(which) { // black clock
15342 if (gameMode == EditPosition || gameMode == IcsExamining) {
15343 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
15344 SetBlackToPlayEvent();
15345 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
15346 gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
15347 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
15348 } else if (shiftKey) {
15349 AdjustClock(which, -1);
15350 } else if (gameMode == IcsPlayingWhite ||
15351 gameMode == MachinePlaysBlack) {
15354 } else { // white clock
15355 if (gameMode == EditPosition || gameMode == IcsExamining) {
15356 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
15357 SetWhiteToPlayEvent();
15358 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
15359 gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
15360 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
15361 } else if (shiftKey) {
15362 AdjustClock(which, -1);
15363 } else if (gameMode == IcsPlayingBlack ||
15364 gameMode == MachinePlaysWhite) {
15373 /* Offer draw or accept pending draw offer from opponent */
15375 if (appData.icsActive) {
15376 /* Note: tournament rules require draw offers to be
15377 made after you make your move but before you punch
15378 your clock. Currently ICS doesn't let you do that;
15379 instead, you immediately punch your clock after making
15380 a move, but you can offer a draw at any time. */
15382 SendToICS(ics_prefix);
15383 SendToICS("draw\n");
15384 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
15385 } else if (cmailMsgLoaded) {
15386 if (currentMove == cmailOldMove &&
15387 commentList[cmailOldMove] != NULL &&
15388 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15389 "Black offers a draw" : "White offers a draw")) {
15390 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15391 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15392 } else if (currentMove == cmailOldMove + 1) {
15393 char *offer = WhiteOnMove(cmailOldMove) ?
15394 "White offers a draw" : "Black offers a draw";
15395 AppendComment(currentMove, offer, TRUE);
15396 DisplayComment(currentMove - 1, offer);
15397 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
15399 DisplayError(_("You must make your move before offering a draw"), 0);
15400 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15402 } else if (first.offeredDraw) {
15403 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
15405 if (first.sendDrawOffers) {
15406 SendToProgram("draw\n", &first);
15407 userOfferedDraw = TRUE;
15415 /* Offer Adjourn or accept pending Adjourn offer from opponent */
15417 if (appData.icsActive) {
15418 SendToICS(ics_prefix);
15419 SendToICS("adjourn\n");
15421 /* Currently GNU Chess doesn't offer or accept Adjourns */
15429 /* Offer Abort or accept pending Abort offer from opponent */
15431 if (appData.icsActive) {
15432 SendToICS(ics_prefix);
15433 SendToICS("abort\n");
15435 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
15442 /* Resign. You can do this even if it's not your turn. */
15444 if (appData.icsActive) {
15445 SendToICS(ics_prefix);
15446 SendToICS("resign\n");
15448 switch (gameMode) {
15449 case MachinePlaysWhite:
15450 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
15452 case MachinePlaysBlack:
15453 GameEnds(BlackWins, "White resigns", GE_PLAYER);
15456 if (cmailMsgLoaded) {
15458 if (WhiteOnMove(cmailOldMove)) {
15459 GameEnds(BlackWins, "White resigns", GE_PLAYER);
15461 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
15463 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
15474 StopObservingEvent ()
15476 /* Stop observing current games */
15477 SendToICS(ics_prefix);
15478 SendToICS("unobserve\n");
15482 StopExaminingEvent ()
15484 /* Stop observing current game */
15485 SendToICS(ics_prefix);
15486 SendToICS("unexamine\n");
15490 ForwardInner (int target)
15492 int limit; int oldSeekGraphUp = seekGraphUp;
15494 if (appData.debugMode)
15495 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
15496 target, currentMove, forwardMostMove);
15498 if (gameMode == EditPosition)
15501 seekGraphUp = FALSE;
15502 MarkTargetSquares(1);
15504 if (gameMode == PlayFromGameFile && !pausing)
15507 if (gameMode == IcsExamining && pausing)
15508 limit = pauseExamForwardMostMove;
15510 limit = forwardMostMove;
15512 if (target > limit) target = limit;
15514 if (target > 0 && moveList[target - 1][0]) {
15515 int fromX, fromY, toX, toY;
15516 toX = moveList[target - 1][2] - AAA;
15517 toY = moveList[target - 1][3] - ONE;
15518 if (moveList[target - 1][1] == '@') {
15519 if (appData.highlightLastMove) {
15520 SetHighlights(-1, -1, toX, toY);
15523 int viaX = moveList[target - 1][5] - AAA;
15524 int viaY = moveList[target - 1][6] - ONE;
15525 fromX = moveList[target - 1][0] - AAA;
15526 fromY = moveList[target - 1][1] - ONE;
15527 if (target == currentMove + 1) {
15528 if(moveList[target - 1][4] == ';') { // multi-leg
15529 ChessSquare piece = boards[currentMove][viaY][viaX];
15530 AnimateMove(boards[currentMove], fromX, fromY, viaX, viaY);
15531 boards[currentMove][viaY][viaX] = boards[currentMove][fromY][fromX];
15532 AnimateMove(boards[currentMove], viaX, viaY, toX, toY);
15533 boards[currentMove][viaY][viaX] = piece;
15535 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
15537 if (appData.highlightLastMove) {
15538 SetHighlights(fromX, fromY, toX, toY);
15542 if (gameMode == EditGame || gameMode == AnalyzeMode ||
15543 gameMode == Training || gameMode == PlayFromGameFile ||
15544 gameMode == AnalyzeFile) {
15545 while (currentMove < target) {
15546 if(second.analyzing) SendMoveToProgram(currentMove, &second);
15547 SendMoveToProgram(currentMove++, &first);
15550 currentMove = target;
15553 if (gameMode == EditGame || gameMode == EndOfGame) {
15554 whiteTimeRemaining = timeRemaining[0][currentMove];
15555 blackTimeRemaining = timeRemaining[1][currentMove];
15557 DisplayBothClocks();
15558 DisplayMove(currentMove - 1);
15559 DrawPosition(oldSeekGraphUp, boards[currentMove]);
15560 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15561 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
15562 DisplayComment(currentMove - 1, commentList[currentMove]);
15564 ClearMap(); // [HGM] exclude: invalidate map
15571 if (gameMode == IcsExamining && !pausing) {
15572 SendToICS(ics_prefix);
15573 SendToICS("forward\n");
15575 ForwardInner(currentMove + 1);
15582 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15583 /* to optimze, we temporarily turn off analysis mode while we feed
15584 * the remaining moves to the engine. Otherwise we get analysis output
15587 if (first.analysisSupport) {
15588 SendToProgram("exit\nforce\n", &first);
15589 first.analyzing = FALSE;
15593 if (gameMode == IcsExamining && !pausing) {
15594 SendToICS(ics_prefix);
15595 SendToICS("forward 999999\n");
15597 ForwardInner(forwardMostMove);
15600 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15601 /* we have fed all the moves, so reactivate analysis mode */
15602 SendToProgram("analyze\n", &first);
15603 first.analyzing = TRUE;
15604 /*first.maybeThinking = TRUE;*/
15605 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15610 BackwardInner (int target)
15612 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
15614 if (appData.debugMode)
15615 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
15616 target, currentMove, forwardMostMove);
15618 if (gameMode == EditPosition) return;
15619 seekGraphUp = FALSE;
15620 MarkTargetSquares(1);
15621 if (currentMove <= backwardMostMove) {
15623 DrawPosition(full_redraw, boards[currentMove]);
15626 if (gameMode == PlayFromGameFile && !pausing)
15629 if (moveList[target][0]) {
15630 int fromX, fromY, toX, toY;
15631 toX = moveList[target][2] - AAA;
15632 toY = moveList[target][3] - ONE;
15633 if (moveList[target][1] == '@') {
15634 if (appData.highlightLastMove) {
15635 SetHighlights(-1, -1, toX, toY);
15638 fromX = moveList[target][0] - AAA;
15639 fromY = moveList[target][1] - ONE;
15640 if (target == currentMove - 1) {
15641 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
15643 if (appData.highlightLastMove) {
15644 SetHighlights(fromX, fromY, toX, toY);
15648 if (gameMode == EditGame || gameMode==AnalyzeMode ||
15649 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
15650 while (currentMove > target) {
15651 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
15652 // null move cannot be undone. Reload program with move history before it.
15654 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
15655 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
15657 SendBoard(&first, i);
15658 if(second.analyzing) SendBoard(&second, i);
15659 for(currentMove=i; currentMove<target; currentMove++) {
15660 SendMoveToProgram(currentMove, &first);
15661 if(second.analyzing) SendMoveToProgram(currentMove, &second);
15665 SendToBoth("undo\n");
15669 currentMove = target;
15672 if (gameMode == EditGame || gameMode == EndOfGame) {
15673 whiteTimeRemaining = timeRemaining[0][currentMove];
15674 blackTimeRemaining = timeRemaining[1][currentMove];
15676 DisplayBothClocks();
15677 DisplayMove(currentMove - 1);
15678 DrawPosition(full_redraw, boards[currentMove]);
15679 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15680 // [HGM] PV info: routine tests if comment empty
15681 DisplayComment(currentMove - 1, commentList[currentMove]);
15682 ClearMap(); // [HGM] exclude: invalidate map
15688 if (gameMode == IcsExamining && !pausing) {
15689 SendToICS(ics_prefix);
15690 SendToICS("backward\n");
15692 BackwardInner(currentMove - 1);
15699 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15700 /* to optimize, we temporarily turn off analysis mode while we undo
15701 * all the moves. Otherwise we get analysis output after each undo.
15703 if (first.analysisSupport) {
15704 SendToProgram("exit\nforce\n", &first);
15705 first.analyzing = FALSE;
15709 if (gameMode == IcsExamining && !pausing) {
15710 SendToICS(ics_prefix);
15711 SendToICS("backward 999999\n");
15713 BackwardInner(backwardMostMove);
15716 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15717 /* we have fed all the moves, so reactivate analysis mode */
15718 SendToProgram("analyze\n", &first);
15719 first.analyzing = TRUE;
15720 /*first.maybeThinking = TRUE;*/
15721 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15728 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
15729 if (to >= forwardMostMove) to = forwardMostMove;
15730 if (to <= backwardMostMove) to = backwardMostMove;
15731 if (to < currentMove) {
15739 RevertEvent (Boolean annotate)
15741 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
15744 if (gameMode != IcsExamining) {
15745 DisplayError(_("You are not examining a game"), 0);
15749 DisplayError(_("You can't revert while pausing"), 0);
15752 SendToICS(ics_prefix);
15753 SendToICS("revert\n");
15757 RetractMoveEvent ()
15759 switch (gameMode) {
15760 case MachinePlaysWhite:
15761 case MachinePlaysBlack:
15762 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15763 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
15766 if (forwardMostMove < 2) return;
15767 currentMove = forwardMostMove = forwardMostMove - 2;
15768 whiteTimeRemaining = timeRemaining[0][currentMove];
15769 blackTimeRemaining = timeRemaining[1][currentMove];
15770 DisplayBothClocks();
15771 DisplayMove(currentMove - 1);
15772 ClearHighlights();/*!! could figure this out*/
15773 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
15774 SendToProgram("remove\n", &first);
15775 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
15778 case BeginningOfGame:
15782 case IcsPlayingWhite:
15783 case IcsPlayingBlack:
15784 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
15785 SendToICS(ics_prefix);
15786 SendToICS("takeback 2\n");
15788 SendToICS(ics_prefix);
15789 SendToICS("takeback 1\n");
15798 ChessProgramState *cps;
15800 switch (gameMode) {
15801 case MachinePlaysWhite:
15802 if (!WhiteOnMove(forwardMostMove)) {
15803 DisplayError(_("It is your turn"), 0);
15808 case MachinePlaysBlack:
15809 if (WhiteOnMove(forwardMostMove)) {
15810 DisplayError(_("It is your turn"), 0);
15815 case TwoMachinesPlay:
15816 if (WhiteOnMove(forwardMostMove) ==
15817 (first.twoMachinesColor[0] == 'w')) {
15823 case BeginningOfGame:
15827 SendToProgram("?\n", cps);
15831 TruncateGameEvent ()
15834 if (gameMode != EditGame) return;
15841 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
15842 if (forwardMostMove > currentMove) {
15843 if (gameInfo.resultDetails != NULL) {
15844 free(gameInfo.resultDetails);
15845 gameInfo.resultDetails = NULL;
15846 gameInfo.result = GameUnfinished;
15848 forwardMostMove = currentMove;
15849 HistorySet(parseList, backwardMostMove, forwardMostMove,
15857 if (appData.noChessProgram) return;
15858 switch (gameMode) {
15859 case MachinePlaysWhite:
15860 if (WhiteOnMove(forwardMostMove)) {
15861 DisplayError(_("Wait until your turn."), 0);
15865 case BeginningOfGame:
15866 case MachinePlaysBlack:
15867 if (!WhiteOnMove(forwardMostMove)) {
15868 DisplayError(_("Wait until your turn."), 0);
15873 DisplayError(_("No hint available"), 0);
15876 SendToProgram("hint\n", &first);
15877 hintRequested = TRUE;
15881 SaveSelected (FILE *g, int dummy, char *dummy2)
15883 ListGame * lg = (ListGame *) gameList.head;
15887 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15888 DisplayError(_("Game list not loaded or empty"), 0);
15892 creatingBook = TRUE; // suppresses stuff during load game
15894 /* Get list size */
15895 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
15896 if(lg->position >= 0) { // selected?
15897 LoadGame(f, nItem, "", TRUE);
15898 SaveGamePGN2(g); // leaves g open
15901 lg = (ListGame *) lg->node.succ;
15905 creatingBook = FALSE;
15913 ListGame * lg = (ListGame *) gameList.head;
15916 static int secondTime = FALSE;
15918 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15919 DisplayError(_("Game list not loaded or empty"), 0);
15923 if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
15926 DisplayNote(_("Book file exists! Try again for overwrite."));
15930 creatingBook = TRUE;
15931 secondTime = FALSE;
15933 /* Get list size */
15934 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
15935 if(lg->position >= 0) {
15936 LoadGame(f, nItem, "", TRUE);
15937 AddGameToBook(TRUE);
15940 lg = (ListGame *) lg->node.succ;
15943 creatingBook = FALSE;
15950 if (appData.noChessProgram) return;
15951 switch (gameMode) {
15952 case MachinePlaysWhite:
15953 if (WhiteOnMove(forwardMostMove)) {
15954 DisplayError(_("Wait until your turn."), 0);
15958 case BeginningOfGame:
15959 case MachinePlaysBlack:
15960 if (!WhiteOnMove(forwardMostMove)) {
15961 DisplayError(_("Wait until your turn."), 0);
15966 EditPositionDone(TRUE);
15968 case TwoMachinesPlay:
15973 SendToProgram("bk\n", &first);
15974 bookOutput[0] = NULLCHAR;
15975 bookRequested = TRUE;
15981 char *tags = PGNTags(&gameInfo);
15982 TagsPopUp(tags, CmailMsg());
15986 /* end button procedures */
15989 PrintPosition (FILE *fp, int move)
15993 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15994 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15995 char c = PieceToChar(boards[move][i][j]);
15996 fputc(c == 'x' ? '.' : c, fp);
15997 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
16000 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
16001 fprintf(fp, "white to play\n");
16003 fprintf(fp, "black to play\n");
16007 PrintOpponents (FILE *fp)
16009 if (gameInfo.white != NULL) {
16010 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
16016 /* Find last component of program's own name, using some heuristics */
16018 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
16021 int local = (strcmp(host, "localhost") == 0);
16022 while (!local && (p = strchr(prog, ';')) != NULL) {
16024 while (*p == ' ') p++;
16027 if (*prog == '"' || *prog == '\'') {
16028 q = strchr(prog + 1, *prog);
16030 q = strchr(prog, ' ');
16032 if (q == NULL) q = prog + strlen(prog);
16034 while (p >= prog && *p != '/' && *p != '\\') p--;
16036 if(p == prog && *p == '"') p++;
16038 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
16039 memcpy(buf, p, q - p);
16040 buf[q - p] = NULLCHAR;
16048 TimeControlTagValue ()
16051 if (!appData.clockMode) {
16052 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
16053 } else if (movesPerSession > 0) {
16054 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
16055 } else if (timeIncrement == 0) {
16056 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
16058 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
16060 return StrSave(buf);
16066 /* This routine is used only for certain modes */
16067 VariantClass v = gameInfo.variant;
16068 ChessMove r = GameUnfinished;
16071 if(keepInfo) return;
16073 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
16074 r = gameInfo.result;
16075 p = gameInfo.resultDetails;
16076 gameInfo.resultDetails = NULL;
16078 ClearGameInfo(&gameInfo);
16079 gameInfo.variant = v;
16081 switch (gameMode) {
16082 case MachinePlaysWhite:
16083 gameInfo.event = StrSave( appData.pgnEventHeader );
16084 gameInfo.site = StrSave(HostName());
16085 gameInfo.date = PGNDate();
16086 gameInfo.round = StrSave("-");
16087 gameInfo.white = StrSave(first.tidy);
16088 gameInfo.black = StrSave(UserName());
16089 gameInfo.timeControl = TimeControlTagValue();
16092 case MachinePlaysBlack:
16093 gameInfo.event = StrSave( appData.pgnEventHeader );
16094 gameInfo.site = StrSave(HostName());
16095 gameInfo.date = PGNDate();
16096 gameInfo.round = StrSave("-");
16097 gameInfo.white = StrSave(UserName());
16098 gameInfo.black = StrSave(first.tidy);
16099 gameInfo.timeControl = TimeControlTagValue();
16102 case TwoMachinesPlay:
16103 gameInfo.event = StrSave( appData.pgnEventHeader );
16104 gameInfo.site = StrSave(HostName());
16105 gameInfo.date = PGNDate();
16108 snprintf(buf, MSG_SIZ, "%d", roundNr);
16109 gameInfo.round = StrSave(buf);
16111 gameInfo.round = StrSave("-");
16113 if (first.twoMachinesColor[0] == 'w') {
16114 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16115 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16117 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16118 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16120 gameInfo.timeControl = TimeControlTagValue();
16124 gameInfo.event = StrSave("Edited game");
16125 gameInfo.site = StrSave(HostName());
16126 gameInfo.date = PGNDate();
16127 gameInfo.round = StrSave("-");
16128 gameInfo.white = StrSave("-");
16129 gameInfo.black = StrSave("-");
16130 gameInfo.result = r;
16131 gameInfo.resultDetails = p;
16135 gameInfo.event = StrSave("Edited position");
16136 gameInfo.site = StrSave(HostName());
16137 gameInfo.date = PGNDate();
16138 gameInfo.round = StrSave("-");
16139 gameInfo.white = StrSave("-");
16140 gameInfo.black = StrSave("-");
16143 case IcsPlayingWhite:
16144 case IcsPlayingBlack:
16149 case PlayFromGameFile:
16150 gameInfo.event = StrSave("Game from non-PGN file");
16151 gameInfo.site = StrSave(HostName());
16152 gameInfo.date = PGNDate();
16153 gameInfo.round = StrSave("-");
16154 gameInfo.white = StrSave("?");
16155 gameInfo.black = StrSave("?");
16164 ReplaceComment (int index, char *text)
16170 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
16171 pvInfoList[index-1].depth == len &&
16172 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
16173 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
16174 while (*text == '\n') text++;
16175 len = strlen(text);
16176 while (len > 0 && text[len - 1] == '\n') len--;
16178 if (commentList[index] != NULL)
16179 free(commentList[index]);
16182 commentList[index] = NULL;
16185 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
16186 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
16187 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
16188 commentList[index] = (char *) malloc(len + 2);
16189 strncpy(commentList[index], text, len);
16190 commentList[index][len] = '\n';
16191 commentList[index][len + 1] = NULLCHAR;
16193 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
16195 commentList[index] = (char *) malloc(len + 7);
16196 safeStrCpy(commentList[index], "{\n", 3);
16197 safeStrCpy(commentList[index]+2, text, len+1);
16198 commentList[index][len+2] = NULLCHAR;
16199 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
16200 strcat(commentList[index], "\n}\n");
16205 CrushCRs (char *text)
16213 if (ch == '\r') continue;
16215 } while (ch != '\0');
16219 AppendComment (int index, char *text, Boolean addBraces)
16220 /* addBraces tells if we should add {} */
16225 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
16226 if(addBraces == 3) addBraces = 0; else // force appending literally
16227 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
16230 while (*text == '\n') text++;
16231 len = strlen(text);
16232 while (len > 0 && text[len - 1] == '\n') len--;
16233 text[len] = NULLCHAR;
16235 if (len == 0) return;
16237 if (commentList[index] != NULL) {
16238 Boolean addClosingBrace = addBraces;
16239 old = commentList[index];
16240 oldlen = strlen(old);
16241 while(commentList[index][oldlen-1] == '\n')
16242 commentList[index][--oldlen] = NULLCHAR;
16243 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
16244 safeStrCpy(commentList[index], old, oldlen + len + 6);
16246 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
16247 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
16248 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
16249 while (*text == '\n') { text++; len--; }
16250 commentList[index][--oldlen] = NULLCHAR;
16252 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
16253 else strcat(commentList[index], "\n");
16254 strcat(commentList[index], text);
16255 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
16256 else strcat(commentList[index], "\n");
16258 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
16260 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
16261 else commentList[index][0] = NULLCHAR;
16262 strcat(commentList[index], text);
16263 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
16264 if(addBraces == TRUE) strcat(commentList[index], "}\n");
16269 FindStr (char * text, char * sub_text)
16271 char * result = strstr( text, sub_text );
16273 if( result != NULL ) {
16274 result += strlen( sub_text );
16280 /* [AS] Try to extract PV info from PGN comment */
16281 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
16283 GetInfoFromComment (int index, char * text)
16285 char * sep = text, *p;
16287 if( text != NULL && index > 0 ) {
16290 int time = -1, sec = 0, deci;
16291 char * s_eval = FindStr( text, "[%eval " );
16292 char * s_emt = FindStr( text, "[%emt " );
16294 if( s_eval != NULL || s_emt != NULL ) {
16296 if(0) { // [HGM] this code is not finished, and could actually be detrimental
16301 if( s_eval != NULL ) {
16302 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
16306 if( delim != ']' ) {
16311 if( s_emt != NULL ) {
16316 /* We expect something like: [+|-]nnn.nn/dd */
16319 if(*text != '{') return text; // [HGM] braces: must be normal comment
16321 sep = strchr( text, '/' );
16322 if( sep == NULL || sep < (text+4) ) {
16327 if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
16328 if(p[1] == '(') { // comment starts with PV
16329 p = strchr(p, ')'); // locate end of PV
16330 if(p == NULL || sep < p+5) return text;
16331 // at this point we have something like "{(.*) +0.23/6 ..."
16332 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
16333 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
16334 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
16336 time = -1; sec = -1; deci = -1;
16337 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
16338 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
16339 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
16340 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
16344 if( score_lo < 0 || score_lo >= 100 ) {
16348 if(sec >= 0) time = 600*time + 10*sec; else
16349 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
16351 score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
16353 /* [HGM] PV time: now locate end of PV info */
16354 while( *++sep >= '0' && *sep <= '9'); // strip depth
16356 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
16358 while( *++sep >= '0' && *sep <= '9'); // strip seconds
16360 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
16361 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
16372 pvInfoList[index-1].depth = depth;
16373 pvInfoList[index-1].score = score;
16374 pvInfoList[index-1].time = 10*time; // centi-sec
16375 if(*sep == '}') *sep = 0; else *--sep = '{';
16376 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
16382 SendToProgram (char *message, ChessProgramState *cps)
16384 int count, outCount, error;
16387 if (cps->pr == NoProc) return;
16390 if (appData.debugMode) {
16393 fprintf(debugFP, "%ld >%-6s: %s",
16394 SubtractTimeMarks(&now, &programStartTime),
16395 cps->which, message);
16397 fprintf(serverFP, "%ld >%-6s: %s",
16398 SubtractTimeMarks(&now, &programStartTime),
16399 cps->which, message), fflush(serverFP);
16402 count = strlen(message);
16403 outCount = OutputToProcess(cps->pr, message, count, &error);
16404 if (outCount < count && !exiting
16405 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
16406 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
16407 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
16408 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
16409 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
16410 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
16411 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
16412 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
16414 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
16415 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
16416 gameInfo.result = res;
16418 gameInfo.resultDetails = StrSave(buf);
16420 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
16421 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
16426 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
16430 ChessProgramState *cps = (ChessProgramState *)closure;
16432 if (isr != cps->isr) return; /* Killed intentionally */
16435 RemoveInputSource(cps->isr);
16436 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
16437 _(cps->which), cps->program);
16438 if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
16439 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
16440 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
16441 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
16442 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
16443 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
16445 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
16446 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
16447 gameInfo.result = res;
16449 gameInfo.resultDetails = StrSave(buf);
16451 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
16452 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
16454 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
16455 _(cps->which), cps->program);
16456 RemoveInputSource(cps->isr);
16458 /* [AS] Program is misbehaving badly... kill it */
16459 if( count == -2 ) {
16460 DestroyChildProcess( cps->pr, 9 );
16464 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
16469 if ((end_str = strchr(message, '\r')) != NULL)
16470 *end_str = NULLCHAR;
16471 if ((end_str = strchr(message, '\n')) != NULL)
16472 *end_str = NULLCHAR;
16474 if (appData.debugMode) {
16475 TimeMark now; int print = 1;
16476 char *quote = ""; char c; int i;
16478 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
16479 char start = message[0];
16480 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
16481 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
16482 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
16483 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
16484 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
16485 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
16486 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
16487 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
16488 sscanf(message, "hint: %c", &c)!=1 &&
16489 sscanf(message, "pong %c", &c)!=1 && start != '#') {
16490 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
16491 print = (appData.engineComments >= 2);
16493 message[0] = start; // restore original message
16497 fprintf(debugFP, "%ld <%-6s: %s%s\n",
16498 SubtractTimeMarks(&now, &programStartTime), cps->which,
16502 fprintf(serverFP, "%ld <%-6s: %s%s\n",
16503 SubtractTimeMarks(&now, &programStartTime), cps->which,
16505 message), fflush(serverFP);
16509 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
16510 if (appData.icsEngineAnalyze) {
16511 if (strstr(message, "whisper") != NULL ||
16512 strstr(message, "kibitz") != NULL ||
16513 strstr(message, "tellics") != NULL) return;
16516 HandleMachineMove(message, cps);
16521 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
16526 if( timeControl_2 > 0 ) {
16527 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
16528 tc = timeControl_2;
16531 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
16532 inc /= cps->timeOdds;
16533 st /= cps->timeOdds;
16535 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
16538 /* Set exact time per move, normally using st command */
16539 if (cps->stKludge) {
16540 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
16542 if (seconds == 0) {
16543 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
16545 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
16548 snprintf(buf, MSG_SIZ, "st %d\n", st);
16551 /* Set conventional or incremental time control, using level command */
16552 if (seconds == 0) {
16553 /* Note old gnuchess bug -- minutes:seconds used to not work.
16554 Fixed in later versions, but still avoid :seconds
16555 when seconds is 0. */
16556 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
16558 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
16559 seconds, inc/1000.);
16562 SendToProgram(buf, cps);
16564 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
16565 /* Orthogonally, limit search to given depth */
16567 if (cps->sdKludge) {
16568 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
16570 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
16572 SendToProgram(buf, cps);
16575 if(cps->nps >= 0) { /* [HGM] nps */
16576 if(cps->supportsNPS == FALSE)
16577 cps->nps = -1; // don't use if engine explicitly says not supported!
16579 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
16580 SendToProgram(buf, cps);
16585 ChessProgramState *
16587 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
16589 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
16590 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
16596 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
16598 char message[MSG_SIZ];
16601 /* Note: this routine must be called when the clocks are stopped
16602 or when they have *just* been set or switched; otherwise
16603 it will be off by the time since the current tick started.
16605 if (machineWhite) {
16606 time = whiteTimeRemaining / 10;
16607 otime = blackTimeRemaining / 10;
16609 time = blackTimeRemaining / 10;
16610 otime = whiteTimeRemaining / 10;
16612 /* [HGM] translate opponent's time by time-odds factor */
16613 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
16615 if (time <= 0) time = 1;
16616 if (otime <= 0) otime = 1;
16618 snprintf(message, MSG_SIZ, "time %ld\n", time);
16619 SendToProgram(message, cps);
16621 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
16622 SendToProgram(message, cps);
16626 EngineDefinedVariant (ChessProgramState *cps, int n)
16627 { // return name of n-th unknown variant that engine supports
16628 static char buf[MSG_SIZ];
16629 char *p, *s = cps->variants;
16630 if(!s) return NULL;
16631 do { // parse string from variants feature
16633 p = strchr(s, ',');
16634 if(p) *p = NULLCHAR;
16635 v = StringToVariant(s);
16636 if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
16637 if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
16638 if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
16639 !strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
16640 !strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
16641 !strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
16642 if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
16645 if(n < 0) return buf;
16651 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
16654 int len = strlen(name);
16657 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
16659 sscanf(*p, "%d", &val);
16661 while (**p && **p != ' ')
16663 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16664 SendToProgram(buf, cps);
16671 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
16674 int len = strlen(name);
16675 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
16677 sscanf(*p, "%d", loc);
16678 while (**p && **p != ' ') (*p)++;
16679 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16680 SendToProgram(buf, cps);
16687 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
16690 int len = strlen(name);
16691 if (strncmp((*p), name, len) == 0
16692 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
16694 ASSIGN(*loc, *p); // kludge alert: assign rest of line just to be sure allocation is large enough so that sscanf below always fits
16695 sscanf(*p, "%[^\"]", *loc);
16696 while (**p && **p != '\"') (*p)++;
16697 if (**p == '\"') (*p)++;
16698 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16699 SendToProgram(buf, cps);
16706 ParseOption (Option *opt, ChessProgramState *cps)
16707 // [HGM] options: process the string that defines an engine option, and determine
16708 // name, type, default value, and allowed value range
16710 char *p, *q, buf[MSG_SIZ];
16711 int n, min = (-1)<<31, max = 1<<31, def;
16713 if(p = strstr(opt->name, " -spin ")) {
16714 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16715 if(max < min) max = min; // enforce consistency
16716 if(def < min) def = min;
16717 if(def > max) def = max;
16722 } else if((p = strstr(opt->name, " -slider "))) {
16723 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
16724 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16725 if(max < min) max = min; // enforce consistency
16726 if(def < min) def = min;
16727 if(def > max) def = max;
16731 opt->type = Spin; // Slider;
16732 } else if((p = strstr(opt->name, " -string "))) {
16733 opt->textValue = p+9;
16734 opt->type = TextBox;
16735 } else if((p = strstr(opt->name, " -file "))) {
16736 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16737 opt->textValue = p+7;
16738 opt->type = FileName; // FileName;
16739 } else if((p = strstr(opt->name, " -path "))) {
16740 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16741 opt->textValue = p+7;
16742 opt->type = PathName; // PathName;
16743 } else if(p = strstr(opt->name, " -check ")) {
16744 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
16745 opt->value = (def != 0);
16746 opt->type = CheckBox;
16747 } else if(p = strstr(opt->name, " -combo ")) {
16748 opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
16749 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
16750 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
16751 opt->value = n = 0;
16752 while(q = StrStr(q, " /// ")) {
16753 n++; *q = 0; // count choices, and null-terminate each of them
16755 if(*q == '*') { // remember default, which is marked with * prefix
16759 cps->comboList[cps->comboCnt++] = q;
16761 cps->comboList[cps->comboCnt++] = NULL;
16763 opt->type = ComboBox;
16764 } else if(p = strstr(opt->name, " -button")) {
16765 opt->type = Button;
16766 } else if(p = strstr(opt->name, " -save")) {
16767 opt->type = SaveButton;
16768 } else return FALSE;
16769 *p = 0; // terminate option name
16770 // now look if the command-line options define a setting for this engine option.
16771 if(cps->optionSettings && cps->optionSettings[0])
16772 p = strstr(cps->optionSettings, opt->name); else p = NULL;
16773 if(p && (p == cps->optionSettings || p[-1] == ',')) {
16774 snprintf(buf, MSG_SIZ, "option %s", p);
16775 if(p = strstr(buf, ",")) *p = 0;
16776 if(q = strchr(buf, '=')) switch(opt->type) {
16778 for(n=0; n<opt->max; n++)
16779 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
16782 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
16786 opt->value = atoi(q+1);
16791 SendToProgram(buf, cps);
16797 FeatureDone (ChessProgramState *cps, int val)
16799 DelayedEventCallback cb = GetDelayedEvent();
16800 if ((cb == InitBackEnd3 && cps == &first) ||
16801 (cb == SettingsMenuIfReady && cps == &second) ||
16802 (cb == LoadEngine) ||
16803 (cb == TwoMachinesEventIfReady)) {
16804 CancelDelayedEvent();
16805 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
16807 cps->initDone = val;
16808 if(val) cps->reload = FALSE;
16811 /* Parse feature command from engine */
16813 ParseFeatures (char *args, ChessProgramState *cps)
16821 while (*p == ' ') p++;
16822 if (*p == NULLCHAR) return;
16824 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
16825 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
16826 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
16827 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
16828 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
16829 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
16830 if (BoolFeature(&p, "reuse", &val, cps)) {
16831 /* Engine can disable reuse, but can't enable it if user said no */
16832 if (!val) cps->reuse = FALSE;
16835 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
16836 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
16837 if (gameMode == TwoMachinesPlay) {
16838 DisplayTwoMachinesTitle();
16844 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
16845 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
16846 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
16847 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
16848 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
16849 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
16850 if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
16851 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
16852 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
16853 if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
16854 if (IntFeature(&p, "done", &val, cps)) {
16855 FeatureDone(cps, val);
16858 /* Added by Tord: */
16859 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
16860 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
16861 /* End of additions by Tord */
16863 /* [HGM] added features: */
16864 if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
16865 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
16866 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
16867 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
16868 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
16869 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
16870 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
16871 if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
16872 if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
16873 FREE(cps->option[cps->nrOptions].name);
16874 cps->option[cps->nrOptions].name = q; q = NULL;
16875 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
16876 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
16877 SendToProgram(buf, cps);
16880 if(cps->nrOptions >= MAX_OPTIONS) {
16882 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
16883 DisplayError(buf, 0);
16887 /* End of additions by HGM */
16889 /* unknown feature: complain and skip */
16891 while (*q && *q != '=') q++;
16892 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
16893 SendToProgram(buf, cps);
16899 while (*p && *p != '\"') p++;
16900 if (*p == '\"') p++;
16902 while (*p && *p != ' ') p++;
16910 PeriodicUpdatesEvent (int newState)
16912 if (newState == appData.periodicUpdates)
16915 appData.periodicUpdates=newState;
16917 /* Display type changes, so update it now */
16918 // DisplayAnalysis();
16920 /* Get the ball rolling again... */
16922 AnalysisPeriodicEvent(1);
16923 StartAnalysisClock();
16928 PonderNextMoveEvent (int newState)
16930 if (newState == appData.ponderNextMove) return;
16931 if (gameMode == EditPosition) EditPositionDone(TRUE);
16933 SendToProgram("hard\n", &first);
16934 if (gameMode == TwoMachinesPlay) {
16935 SendToProgram("hard\n", &second);
16938 SendToProgram("easy\n", &first);
16939 thinkOutput[0] = NULLCHAR;
16940 if (gameMode == TwoMachinesPlay) {
16941 SendToProgram("easy\n", &second);
16944 appData.ponderNextMove = newState;
16948 NewSettingEvent (int option, int *feature, char *command, int value)
16952 if (gameMode == EditPosition) EditPositionDone(TRUE);
16953 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
16954 if(feature == NULL || *feature) SendToProgram(buf, &first);
16955 if (gameMode == TwoMachinesPlay) {
16956 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
16961 ShowThinkingEvent ()
16962 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
16964 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
16965 int newState = appData.showThinking
16966 // [HGM] thinking: other features now need thinking output as well
16967 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
16969 if (oldState == newState) return;
16970 oldState = newState;
16971 if (gameMode == EditPosition) EditPositionDone(TRUE);
16973 SendToProgram("post\n", &first);
16974 if (gameMode == TwoMachinesPlay) {
16975 SendToProgram("post\n", &second);
16978 SendToProgram("nopost\n", &first);
16979 thinkOutput[0] = NULLCHAR;
16980 if (gameMode == TwoMachinesPlay) {
16981 SendToProgram("nopost\n", &second);
16984 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
16988 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
16990 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
16991 if (pr == NoProc) return;
16992 AskQuestion(title, question, replyPrefix, pr);
16996 TypeInEvent (char firstChar)
16998 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
16999 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
17000 gameMode == AnalyzeMode || gameMode == EditGame ||
17001 gameMode == EditPosition || gameMode == IcsExamining ||
17002 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
17003 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
17004 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
17005 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
17006 gameMode == Training) PopUpMoveDialog(firstChar);
17010 TypeInDoneEvent (char *move)
17013 int n, fromX, fromY, toX, toY;
17015 ChessMove moveType;
17018 if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
17019 EditPositionPasteFEN(move);
17022 // [HGM] movenum: allow move number to be typed in any mode
17023 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
17027 // undocumented kludge: allow command-line option to be typed in!
17028 // (potentially fatal, and does not implement the effect of the option.)
17029 // should only be used for options that are values on which future decisions will be made,
17030 // and definitely not on options that would be used during initialization.
17031 if(strstr(move, "!!! -") == move) {
17032 ParseArgsFromString(move+4);
17036 if (gameMode != EditGame && currentMove != forwardMostMove &&
17037 gameMode != Training) {
17038 DisplayMoveError(_("Displayed move is not current"));
17040 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17041 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
17042 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
17043 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17044 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
17045 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
17047 DisplayMoveError(_("Could not parse move"));
17053 DisplayMove (int moveNumber)
17055 char message[MSG_SIZ];
17057 char cpThinkOutput[MSG_SIZ];
17059 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
17061 if (moveNumber == forwardMostMove - 1 ||
17062 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
17064 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
17066 if (strchr(cpThinkOutput, '\n')) {
17067 *strchr(cpThinkOutput, '\n') = NULLCHAR;
17070 *cpThinkOutput = NULLCHAR;
17073 /* [AS] Hide thinking from human user */
17074 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
17075 *cpThinkOutput = NULLCHAR;
17076 if( thinkOutput[0] != NULLCHAR ) {
17079 for( i=0; i<=hiddenThinkOutputState; i++ ) {
17080 cpThinkOutput[i] = '.';
17082 cpThinkOutput[i] = NULLCHAR;
17083 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
17087 if (moveNumber == forwardMostMove - 1 &&
17088 gameInfo.resultDetails != NULL) {
17089 if (gameInfo.resultDetails[0] == NULLCHAR) {
17090 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
17092 snprintf(res, MSG_SIZ, " {%s} %s",
17093 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
17099 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17100 DisplayMessage(res, cpThinkOutput);
17102 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
17103 WhiteOnMove(moveNumber) ? " " : ".. ",
17104 parseList[moveNumber], res);
17105 DisplayMessage(message, cpThinkOutput);
17110 DisplayComment (int moveNumber, char *text)
17112 char title[MSG_SIZ];
17114 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17115 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
17117 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
17118 WhiteOnMove(moveNumber) ? " " : ".. ",
17119 parseList[moveNumber]);
17121 if (text != NULL && (appData.autoDisplayComment || commentUp))
17122 CommentPopUp(title, text);
17125 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
17126 * might be busy thinking or pondering. It can be omitted if your
17127 * gnuchess is configured to stop thinking immediately on any user
17128 * input. However, that gnuchess feature depends on the FIONREAD
17129 * ioctl, which does not work properly on some flavors of Unix.
17132 Attention (ChessProgramState *cps)
17135 if (!cps->useSigint) return;
17136 if (appData.noChessProgram || (cps->pr == NoProc)) return;
17137 switch (gameMode) {
17138 case MachinePlaysWhite:
17139 case MachinePlaysBlack:
17140 case TwoMachinesPlay:
17141 case IcsPlayingWhite:
17142 case IcsPlayingBlack:
17145 /* Skip if we know it isn't thinking */
17146 if (!cps->maybeThinking) return;
17147 if (appData.debugMode)
17148 fprintf(debugFP, "Interrupting %s\n", cps->which);
17149 InterruptChildProcess(cps->pr);
17150 cps->maybeThinking = FALSE;
17155 #endif /*ATTENTION*/
17161 if (whiteTimeRemaining <= 0) {
17164 if (appData.icsActive) {
17165 if (appData.autoCallFlag &&
17166 gameMode == IcsPlayingBlack && !blackFlag) {
17167 SendToICS(ics_prefix);
17168 SendToICS("flag\n");
17172 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17174 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
17175 if (appData.autoCallFlag) {
17176 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
17183 if (blackTimeRemaining <= 0) {
17186 if (appData.icsActive) {
17187 if (appData.autoCallFlag &&
17188 gameMode == IcsPlayingWhite && !whiteFlag) {
17189 SendToICS(ics_prefix);
17190 SendToICS("flag\n");
17194 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17196 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
17197 if (appData.autoCallFlag) {
17198 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
17209 CheckTimeControl ()
17211 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
17212 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
17215 * add time to clocks when time control is achieved ([HGM] now also used for increment)
17217 if ( !WhiteOnMove(forwardMostMove) ) {
17218 /* White made time control */
17219 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
17220 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
17221 /* [HGM] time odds: correct new time quota for time odds! */
17222 / WhitePlayer()->timeOdds;
17223 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
17225 lastBlack -= blackTimeRemaining;
17226 /* Black made time control */
17227 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
17228 / WhitePlayer()->other->timeOdds;
17229 lastWhite = whiteTimeRemaining;
17234 DisplayBothClocks ()
17236 int wom = gameMode == EditPosition ?
17237 !blackPlaysFirst : WhiteOnMove(currentMove);
17238 DisplayWhiteClock(whiteTimeRemaining, wom);
17239 DisplayBlackClock(blackTimeRemaining, !wom);
17243 /* Timekeeping seems to be a portability nightmare. I think everyone
17244 has ftime(), but I'm really not sure, so I'm including some ifdefs
17245 to use other calls if you don't. Clocks will be less accurate if
17246 you have neither ftime nor gettimeofday.
17249 /* VS 2008 requires the #include outside of the function */
17250 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
17251 #include <sys/timeb.h>
17254 /* Get the current time as a TimeMark */
17256 GetTimeMark (TimeMark *tm)
17258 #if HAVE_GETTIMEOFDAY
17260 struct timeval timeVal;
17261 struct timezone timeZone;
17263 gettimeofday(&timeVal, &timeZone);
17264 tm->sec = (long) timeVal.tv_sec;
17265 tm->ms = (int) (timeVal.tv_usec / 1000L);
17267 #else /*!HAVE_GETTIMEOFDAY*/
17270 // include <sys/timeb.h> / moved to just above start of function
17271 struct timeb timeB;
17274 tm->sec = (long) timeB.time;
17275 tm->ms = (int) timeB.millitm;
17277 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
17278 tm->sec = (long) time(NULL);
17284 /* Return the difference in milliseconds between two
17285 time marks. We assume the difference will fit in a long!
17288 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
17290 return 1000L*(tm2->sec - tm1->sec) +
17291 (long) (tm2->ms - tm1->ms);
17296 * Code to manage the game clocks.
17298 * In tournament play, black starts the clock and then white makes a move.
17299 * We give the human user a slight advantage if he is playing white---the
17300 * clocks don't run until he makes his first move, so it takes zero time.
17301 * Also, we don't account for network lag, so we could get out of sync
17302 * with GNU Chess's clock -- but then, referees are always right.
17305 static TimeMark tickStartTM;
17306 static long intendedTickLength;
17309 NextTickLength (long timeRemaining)
17311 long nominalTickLength, nextTickLength;
17313 if (timeRemaining > 0L && timeRemaining <= 10000L)
17314 nominalTickLength = 100L;
17316 nominalTickLength = 1000L;
17317 nextTickLength = timeRemaining % nominalTickLength;
17318 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
17320 return nextTickLength;
17323 /* Adjust clock one minute up or down */
17325 AdjustClock (Boolean which, int dir)
17327 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
17328 if(which) blackTimeRemaining += 60000*dir;
17329 else whiteTimeRemaining += 60000*dir;
17330 DisplayBothClocks();
17331 adjustedClock = TRUE;
17334 /* Stop clocks and reset to a fresh time control */
17338 (void) StopClockTimer();
17339 if (appData.icsActive) {
17340 whiteTimeRemaining = blackTimeRemaining = 0;
17341 } else if (searchTime) {
17342 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
17343 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
17344 } else { /* [HGM] correct new time quote for time odds */
17345 whiteTC = blackTC = fullTimeControlString;
17346 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
17347 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
17349 if (whiteFlag || blackFlag) {
17351 whiteFlag = blackFlag = FALSE;
17353 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
17354 DisplayBothClocks();
17355 adjustedClock = FALSE;
17358 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
17360 /* Decrement running clock by amount of time that has passed */
17364 long timeRemaining;
17365 long lastTickLength, fudge;
17368 if (!appData.clockMode) return;
17369 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
17373 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17375 /* Fudge if we woke up a little too soon */
17376 fudge = intendedTickLength - lastTickLength;
17377 if (fudge < 0 || fudge > FUDGE) fudge = 0;
17379 if (WhiteOnMove(forwardMostMove)) {
17380 if(whiteNPS >= 0) lastTickLength = 0;
17381 timeRemaining = whiteTimeRemaining -= lastTickLength;
17382 if(timeRemaining < 0 && !appData.icsActive) {
17383 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
17384 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
17385 whiteStartMove = forwardMostMove; whiteTC = nextSession;
17386 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
17389 DisplayWhiteClock(whiteTimeRemaining - fudge,
17390 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
17392 if(blackNPS >= 0) lastTickLength = 0;
17393 timeRemaining = blackTimeRemaining -= lastTickLength;
17394 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
17395 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
17397 blackStartMove = forwardMostMove;
17398 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
17401 DisplayBlackClock(blackTimeRemaining - fudge,
17402 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
17404 if (CheckFlags()) return;
17406 if(twoBoards) { // count down secondary board's clocks as well
17407 activePartnerTime -= lastTickLength;
17409 if(activePartner == 'W')
17410 DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
17412 DisplayBlackClock(activePartnerTime, TRUE);
17417 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
17418 StartClockTimer(intendedTickLength);
17420 /* if the time remaining has fallen below the alarm threshold, sound the
17421 * alarm. if the alarm has sounded and (due to a takeback or time control
17422 * with increment) the time remaining has increased to a level above the
17423 * threshold, reset the alarm so it can sound again.
17426 if (appData.icsActive && appData.icsAlarm) {
17428 /* make sure we are dealing with the user's clock */
17429 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
17430 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
17433 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
17434 alarmSounded = FALSE;
17435 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
17437 alarmSounded = TRUE;
17443 /* A player has just moved, so stop the previously running
17444 clock and (if in clock mode) start the other one.
17445 We redisplay both clocks in case we're in ICS mode, because
17446 ICS gives us an update to both clocks after every move.
17447 Note that this routine is called *after* forwardMostMove
17448 is updated, so the last fractional tick must be subtracted
17449 from the color that is *not* on move now.
17452 SwitchClocks (int newMoveNr)
17454 long lastTickLength;
17456 int flagged = FALSE;
17460 if (StopClockTimer() && appData.clockMode) {
17461 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17462 if (!WhiteOnMove(forwardMostMove)) {
17463 if(blackNPS >= 0) lastTickLength = 0;
17464 blackTimeRemaining -= lastTickLength;
17465 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
17466 // if(pvInfoList[forwardMostMove].time == -1)
17467 pvInfoList[forwardMostMove].time = // use GUI time
17468 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
17470 if(whiteNPS >= 0) lastTickLength = 0;
17471 whiteTimeRemaining -= lastTickLength;
17472 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
17473 // if(pvInfoList[forwardMostMove].time == -1)
17474 pvInfoList[forwardMostMove].time =
17475 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
17477 flagged = CheckFlags();
17479 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
17480 CheckTimeControl();
17482 if (flagged || !appData.clockMode) return;
17484 switch (gameMode) {
17485 case MachinePlaysBlack:
17486 case MachinePlaysWhite:
17487 case BeginningOfGame:
17488 if (pausing) return;
17492 case PlayFromGameFile:
17500 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
17501 if(WhiteOnMove(forwardMostMove))
17502 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
17503 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
17507 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
17508 whiteTimeRemaining : blackTimeRemaining);
17509 StartClockTimer(intendedTickLength);
17513 /* Stop both clocks */
17517 long lastTickLength;
17520 if (!StopClockTimer()) return;
17521 if (!appData.clockMode) return;
17525 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17526 if (WhiteOnMove(forwardMostMove)) {
17527 if(whiteNPS >= 0) lastTickLength = 0;
17528 whiteTimeRemaining -= lastTickLength;
17529 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
17531 if(blackNPS >= 0) lastTickLength = 0;
17532 blackTimeRemaining -= lastTickLength;
17533 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
17538 /* Start clock of player on move. Time may have been reset, so
17539 if clock is already running, stop and restart it. */
17543 (void) StopClockTimer(); /* in case it was running already */
17544 DisplayBothClocks();
17545 if (CheckFlags()) return;
17547 if (!appData.clockMode) return;
17548 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
17550 GetTimeMark(&tickStartTM);
17551 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
17552 whiteTimeRemaining : blackTimeRemaining);
17554 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
17555 whiteNPS = blackNPS = -1;
17556 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
17557 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
17558 whiteNPS = first.nps;
17559 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
17560 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
17561 blackNPS = first.nps;
17562 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
17563 whiteNPS = second.nps;
17564 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
17565 blackNPS = second.nps;
17566 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
17568 StartClockTimer(intendedTickLength);
17572 TimeString (long ms)
17574 long second, minute, hour, day;
17576 static char buf[32];
17578 if (ms > 0 && ms <= 9900) {
17579 /* convert milliseconds to tenths, rounding up */
17580 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
17582 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
17586 /* convert milliseconds to seconds, rounding up */
17587 /* use floating point to avoid strangeness of integer division
17588 with negative dividends on many machines */
17589 second = (long) floor(((double) (ms + 999L)) / 1000.0);
17596 day = second / (60 * 60 * 24);
17597 second = second % (60 * 60 * 24);
17598 hour = second / (60 * 60);
17599 second = second % (60 * 60);
17600 minute = second / 60;
17601 second = second % 60;
17604 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
17605 sign, day, hour, minute, second);
17607 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
17609 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
17616 * This is necessary because some C libraries aren't ANSI C compliant yet.
17619 StrStr (char *string, char *match)
17623 length = strlen(match);
17625 for (i = strlen(string) - length; i >= 0; i--, string++)
17626 if (!strncmp(match, string, length))
17633 StrCaseStr (char *string, char *match)
17637 length = strlen(match);
17639 for (i = strlen(string) - length; i >= 0; i--, string++) {
17640 for (j = 0; j < length; j++) {
17641 if (ToLower(match[j]) != ToLower(string[j]))
17644 if (j == length) return string;
17652 StrCaseCmp (char *s1, char *s2)
17657 c1 = ToLower(*s1++);
17658 c2 = ToLower(*s2++);
17659 if (c1 > c2) return 1;
17660 if (c1 < c2) return -1;
17661 if (c1 == NULLCHAR) return 0;
17669 return isupper(c) ? tolower(c) : c;
17676 return islower(c) ? toupper(c) : c;
17678 #endif /* !_amigados */
17685 if ((ret = (char *) malloc(strlen(s) + 1)))
17687 safeStrCpy(ret, s, strlen(s)+1);
17693 StrSavePtr (char *s, char **savePtr)
17698 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
17699 safeStrCpy(*savePtr, s, strlen(s)+1);
17711 clock = time((time_t *)NULL);
17712 tm = localtime(&clock);
17713 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
17714 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
17715 return StrSave(buf);
17720 PositionToFEN (int move, char *overrideCastling, int moveCounts)
17722 int i, j, fromX, fromY, toX, toY;
17729 whiteToPlay = (gameMode == EditPosition) ?
17730 !blackPlaysFirst : (move % 2 == 0);
17733 /* Piece placement data */
17734 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17735 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
17737 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
17738 if (boards[move][i][j] == EmptySquare) {
17740 } else { ChessSquare piece = boards[move][i][j];
17741 if (emptycount > 0) {
17742 if(emptycount<10) /* [HGM] can be >= 10 */
17743 *p++ = '0' + emptycount;
17744 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17747 if(PieceToChar(piece) == '+') {
17748 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
17750 piece = (ChessSquare)(CHUDEMOTED piece);
17752 *p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
17754 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
17755 p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED piece));
17760 if (emptycount > 0) {
17761 if(emptycount<10) /* [HGM] can be >= 10 */
17762 *p++ = '0' + emptycount;
17763 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17770 /* [HGM] print Crazyhouse or Shogi holdings */
17771 if( gameInfo.holdingsWidth ) {
17772 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
17774 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
17775 piece = boards[move][i][BOARD_WIDTH-1];
17776 if( piece != EmptySquare )
17777 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
17778 *p++ = PieceToChar(piece);
17780 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
17781 piece = boards[move][BOARD_HEIGHT-i-1][0];
17782 if( piece != EmptySquare )
17783 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
17784 *p++ = PieceToChar(piece);
17787 if( q == p ) *p++ = '-';
17793 *p++ = whiteToPlay ? 'w' : 'b';
17796 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
17797 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
17799 if(nrCastlingRights) {
17801 if(appData.fischerCastling) {
17802 /* [HGM] write directly from rights */
17803 if(boards[move][CASTLING][2] != NoRights &&
17804 boards[move][CASTLING][0] != NoRights )
17805 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
17806 if(boards[move][CASTLING][2] != NoRights &&
17807 boards[move][CASTLING][1] != NoRights )
17808 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
17809 if(boards[move][CASTLING][5] != NoRights &&
17810 boards[move][CASTLING][3] != NoRights )
17811 *p++ = boards[move][CASTLING][3] + AAA;
17812 if(boards[move][CASTLING][5] != NoRights &&
17813 boards[move][CASTLING][4] != NoRights )
17814 *p++ = boards[move][CASTLING][4] + AAA;
17817 /* [HGM] write true castling rights */
17818 if( nrCastlingRights == 6 ) {
17820 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
17821 boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
17822 q = (boards[move][CASTLING][1] == BOARD_LEFT &&
17823 boards[move][CASTLING][2] != NoRights );
17824 if(gameInfo.variant == VariantSChess) { // for S-Chess, indicate all vrgin backrank pieces
17825 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_RGHT]; // count white held pieces
17826 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17827 if((boards[move][0][i] != WhiteKing || k+q == 0) &&
17828 boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
17832 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
17833 boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
17834 q = (boards[move][CASTLING][4] == BOARD_LEFT &&
17835 boards[move][CASTLING][5] != NoRights );
17836 if(gameInfo.variant == VariantSChess) {
17837 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_LEFT-1]; // count black held pieces
17838 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17839 if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
17840 boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
17845 if (q == p) *p++ = '-'; /* No castling rights */
17849 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
17850 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
17851 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
17852 /* En passant target square */
17853 if (move > backwardMostMove) {
17854 fromX = moveList[move - 1][0] - AAA;
17855 fromY = moveList[move - 1][1] - ONE;
17856 toX = moveList[move - 1][2] - AAA;
17857 toY = moveList[move - 1][3] - ONE;
17858 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
17859 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
17860 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
17862 /* 2-square pawn move just happened */
17864 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17868 } else if(move == backwardMostMove) {
17869 // [HGM] perhaps we should always do it like this, and forget the above?
17870 if((signed char)boards[move][EP_STATUS] >= 0) {
17871 *p++ = boards[move][EP_STATUS] + AAA;
17872 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17884 { int i = 0, j=move;
17886 /* [HGM] find reversible plies */
17887 if (appData.debugMode) { int k;
17888 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
17889 for(k=backwardMostMove; k<=forwardMostMove; k++)
17890 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
17894 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
17895 if( j == backwardMostMove ) i += initialRulePlies;
17896 sprintf(p, "%d ", i);
17897 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
17899 /* Fullmove number */
17900 sprintf(p, "%d", (move / 2) + 1);
17901 } else *--p = NULLCHAR;
17903 return StrSave(buf);
17907 ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
17909 int i, j, k, w=0, subst=0, shuffle=0;
17911 int emptycount, virgin[BOARD_FILES];
17916 /* Piece placement data */
17917 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17920 if (*p == '/' || *p == ' ' || *p == '[' ) {
17922 emptycount = gameInfo.boardWidth - j;
17923 while (emptycount--)
17924 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17925 if (*p == '/') p++;
17926 else if(autoSize) { // we stumbled unexpectedly into end of board
17927 for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
17928 for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
17930 appData.NrRanks = gameInfo.boardHeight - i; i=0;
17933 #if(BOARD_FILES >= 10)*0
17934 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
17935 p++; emptycount=10;
17936 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17937 while (emptycount--)
17938 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17940 } else if (*p == '*') {
17941 board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
17942 } else if (isdigit(*p)) {
17943 emptycount = *p++ - '0';
17944 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
17945 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17946 while (emptycount--)
17947 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17948 } else if (*p == '<') {
17949 if(i == BOARD_HEIGHT-1) shuffle = 1;
17950 else if (i != 0 || !shuffle) return FALSE;
17952 } else if (shuffle && *p == '>') {
17953 p++; // for now ignore closing shuffle range, and assume rank-end
17954 } else if (*p == '?') {
17955 if (j >= gameInfo.boardWidth) return FALSE;
17956 if (i != 0 && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
17957 board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
17958 } else if (*p == '+' || isalpha(*p)) {
17959 if (j >= gameInfo.boardWidth) return FALSE;
17961 piece = CharToPiece(*++p);
17962 if(piece == EmptySquare) return FALSE; /* unknown piece */
17963 piece = (ChessSquare) (CHUPROMOTED piece ); p++;
17964 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
17965 } else piece = CharToPiece(*p++);
17967 if(piece==EmptySquare) return FALSE; /* unknown piece */
17968 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
17969 piece = (ChessSquare) (PROMOTED piece);
17970 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
17973 board[i][(j++)+gameInfo.holdingsWidth] = piece;
17979 while (*p == '/' || *p == ' ') p++;
17981 if(autoSize) appData.NrFiles = w, InitPosition(TRUE);
17983 /* [HGM] by default clear Crazyhouse holdings, if present */
17984 if(gameInfo.holdingsWidth) {
17985 for(i=0; i<BOARD_HEIGHT; i++) {
17986 board[i][0] = EmptySquare; /* black holdings */
17987 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
17988 board[i][1] = (ChessSquare) 0; /* black counts */
17989 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
17993 /* [HGM] look for Crazyhouse holdings here */
17994 while(*p==' ') p++;
17995 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
17996 int swap=0, wcnt=0, bcnt=0;
17998 if(*p == '<') swap++, p++;
17999 if(*p == '-' ) p++; /* empty holdings */ else {
18000 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
18001 /* if we would allow FEN reading to set board size, we would */
18002 /* have to add holdings and shift the board read so far here */
18003 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
18005 if((int) piece >= (int) BlackPawn ) {
18006 i = (int)piece - (int)BlackPawn;
18007 i = PieceToNumber((ChessSquare)i);
18008 if( i >= gameInfo.holdingsSize ) return FALSE;
18009 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
18010 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
18013 i = (int)piece - (int)WhitePawn;
18014 i = PieceToNumber((ChessSquare)i);
18015 if( i >= gameInfo.holdingsSize ) return FALSE;
18016 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
18017 board[i][BOARD_WIDTH-2]++; /* black holdings */
18021 if(subst) { // substitute back-rank question marks by holdings pieces
18022 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
18023 int k, m, n = bcnt + 1;
18024 if(board[0][j] == ClearBoard) {
18025 if(!wcnt) return FALSE;
18027 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
18028 board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
18029 if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
18033 if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
18034 if(!bcnt) return FALSE;
18035 if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
18036 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[BOARD_HEIGHT-1-k][1]) < 0) {
18037 board[BOARD_HEIGHT-1][j] = board[BOARD_HEIGHT-1-k][0]; bcnt--;
18038 if(--board[BOARD_HEIGHT-1-k][1] == 0) board[BOARD_HEIGHT-1-k][0] = EmptySquare;
18049 if(subst) return FALSE; // substitution requested, but no holdings
18051 while(*p == ' ') p++;
18055 if(appData.colorNickNames) {
18056 if( c == appData.colorNickNames[0] ) c = 'w'; else
18057 if( c == appData.colorNickNames[1] ) c = 'b';
18061 *blackPlaysFirst = FALSE;
18064 *blackPlaysFirst = TRUE;
18070 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
18071 /* return the extra info in global variiables */
18073 /* set defaults in case FEN is incomplete */
18074 board[EP_STATUS] = EP_UNKNOWN;
18075 for(i=0; i<nrCastlingRights; i++ ) {
18076 board[CASTLING][i] =
18077 appData.fischerCastling ? NoRights : initialRights[i];
18078 } /* assume possible unless obviously impossible */
18079 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
18080 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
18081 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
18082 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
18083 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
18084 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
18085 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
18086 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
18089 while(*p==' ') p++;
18090 if(nrCastlingRights) {
18092 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
18093 if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
18094 /* castling indicator present, so default becomes no castlings */
18095 for(i=0; i<nrCastlingRights; i++ ) {
18096 board[CASTLING][i] = NoRights;
18099 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
18100 (appData.fischerCastling || gameInfo.variant == VariantSChess) &&
18101 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
18102 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
18103 int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
18105 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
18106 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
18107 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
18109 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
18110 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
18111 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
18112 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
18113 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
18114 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
18117 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
18118 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
18119 board[CASTLING][2] = whiteKingFile;
18120 if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
18121 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18122 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18125 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
18126 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
18127 board[CASTLING][2] = whiteKingFile;
18128 if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
18129 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18130 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18133 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
18134 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
18135 board[CASTLING][5] = blackKingFile;
18136 if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
18137 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18138 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18141 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
18142 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
18143 board[CASTLING][5] = blackKingFile;
18144 if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
18145 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18146 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18149 default: /* FRC castlings */
18150 if(c >= 'a') { /* black rights */
18151 if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
18152 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18153 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
18154 if(i == BOARD_RGHT) break;
18155 board[CASTLING][5] = i;
18157 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
18158 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
18160 board[CASTLING][3] = c;
18162 board[CASTLING][4] = c;
18163 } else { /* white rights */
18164 if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
18165 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18166 if(board[0][i] == WhiteKing) break;
18167 if(i == BOARD_RGHT) break;
18168 board[CASTLING][2] = i;
18169 c -= AAA - 'a' + 'A';
18170 if(board[0][c] >= WhiteKing) break;
18172 board[CASTLING][0] = c;
18174 board[CASTLING][1] = c;
18178 for(i=0; i<nrCastlingRights; i++)
18179 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
18180 if(gameInfo.variant == VariantSChess)
18181 for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
18182 if(fischer && shuffle) appData.fischerCastling = TRUE;
18183 if (appData.debugMode) {
18184 fprintf(debugFP, "FEN castling rights:");
18185 for(i=0; i<nrCastlingRights; i++)
18186 fprintf(debugFP, " %d", board[CASTLING][i]);
18187 fprintf(debugFP, "\n");
18190 while(*p==' ') p++;
18193 if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
18195 /* read e.p. field in games that know e.p. capture */
18196 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
18197 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18198 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18200 p++; board[EP_STATUS] = EP_NONE;
18202 char c = *p++ - AAA;
18204 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
18205 if(*p >= '0' && *p <='9') p++;
18206 board[EP_STATUS] = c;
18211 if(sscanf(p, "%d", &i) == 1) {
18212 FENrulePlies = i; /* 50-move ply counter */
18213 /* (The move number is still ignored) */
18220 EditPositionPasteFEN (char *fen)
18223 Board initial_position;
18225 if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
18226 DisplayError(_("Bad FEN position in clipboard"), 0);
18229 int savedBlackPlaysFirst = blackPlaysFirst;
18230 EditPositionEvent();
18231 blackPlaysFirst = savedBlackPlaysFirst;
18232 CopyBoard(boards[0], initial_position);
18233 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
18234 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
18235 DisplayBothClocks();
18236 DrawPosition(FALSE, boards[currentMove]);
18241 static char cseq[12] = "\\ ";
18244 set_cont_sequence (char *new_seq)
18249 // handle bad attempts to set the sequence
18251 return 0; // acceptable error - no debug
18253 len = strlen(new_seq);
18254 ret = (len > 0) && (len < sizeof(cseq));
18256 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
18257 else if (appData.debugMode)
18258 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
18263 reformat a source message so words don't cross the width boundary. internal
18264 newlines are not removed. returns the wrapped size (no null character unless
18265 included in source message). If dest is NULL, only calculate the size required
18266 for the dest buffer. lp argument indicats line position upon entry, and it's
18267 passed back upon exit.
18270 wrap (char *dest, char *src, int count, int width, int *lp)
18272 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
18274 cseq_len = strlen(cseq);
18275 old_line = line = *lp;
18276 ansi = len = clen = 0;
18278 for (i=0; i < count; i++)
18280 if (src[i] == '\033')
18283 // if we hit the width, back up
18284 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
18286 // store i & len in case the word is too long
18287 old_i = i, old_len = len;
18289 // find the end of the last word
18290 while (i && src[i] != ' ' && src[i] != '\n')
18296 // word too long? restore i & len before splitting it
18297 if ((old_i-i+clen) >= width)
18304 if (i && src[i-1] == ' ')
18307 if (src[i] != ' ' && src[i] != '\n')
18314 // now append the newline and continuation sequence
18319 strncpy(dest+len, cseq, cseq_len);
18327 dest[len] = src[i];
18331 if (src[i] == '\n')
18336 if (dest && appData.debugMode)
18338 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
18339 count, width, line, len, *lp);
18340 show_bytes(debugFP, src, count);
18341 fprintf(debugFP, "\ndest: ");
18342 show_bytes(debugFP, dest, len);
18343 fprintf(debugFP, "\n");
18345 *lp = dest ? line : old_line;
18350 // [HGM] vari: routines for shelving variations
18351 Boolean modeRestore = FALSE;
18354 PushInner (int firstMove, int lastMove)
18356 int i, j, nrMoves = lastMove - firstMove;
18358 // push current tail of game on stack
18359 savedResult[storedGames] = gameInfo.result;
18360 savedDetails[storedGames] = gameInfo.resultDetails;
18361 gameInfo.resultDetails = NULL;
18362 savedFirst[storedGames] = firstMove;
18363 savedLast [storedGames] = lastMove;
18364 savedFramePtr[storedGames] = framePtr;
18365 framePtr -= nrMoves; // reserve space for the boards
18366 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
18367 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
18368 for(j=0; j<MOVE_LEN; j++)
18369 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
18370 for(j=0; j<2*MOVE_LEN; j++)
18371 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
18372 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
18373 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
18374 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
18375 pvInfoList[firstMove+i-1].depth = 0;
18376 commentList[framePtr+i] = commentList[firstMove+i];
18377 commentList[firstMove+i] = NULL;
18381 forwardMostMove = firstMove; // truncate game so we can start variation
18385 PushTail (int firstMove, int lastMove)
18387 if(appData.icsActive) { // only in local mode
18388 forwardMostMove = currentMove; // mimic old ICS behavior
18391 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
18393 PushInner(firstMove, lastMove);
18394 if(storedGames == 1) GreyRevert(FALSE);
18395 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
18399 PopInner (Boolean annotate)
18402 char buf[8000], moveBuf[20];
18404 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
18405 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
18406 nrMoves = savedLast[storedGames] - currentMove;
18409 if(!WhiteOnMove(currentMove))
18410 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
18411 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
18412 for(i=currentMove; i<forwardMostMove; i++) {
18414 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
18415 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
18416 strcat(buf, moveBuf);
18417 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
18418 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
18422 for(i=1; i<=nrMoves; i++) { // copy last variation back
18423 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
18424 for(j=0; j<MOVE_LEN; j++)
18425 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
18426 for(j=0; j<2*MOVE_LEN; j++)
18427 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
18428 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
18429 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
18430 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
18431 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
18432 commentList[currentMove+i] = commentList[framePtr+i];
18433 commentList[framePtr+i] = NULL;
18435 if(annotate) AppendComment(currentMove+1, buf, FALSE);
18436 framePtr = savedFramePtr[storedGames];
18437 gameInfo.result = savedResult[storedGames];
18438 if(gameInfo.resultDetails != NULL) {
18439 free(gameInfo.resultDetails);
18441 gameInfo.resultDetails = savedDetails[storedGames];
18442 forwardMostMove = currentMove + nrMoves;
18446 PopTail (Boolean annotate)
18448 if(appData.icsActive) return FALSE; // only in local mode
18449 if(!storedGames) return FALSE; // sanity
18450 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
18452 PopInner(annotate);
18453 if(currentMove < forwardMostMove) ForwardEvent(); else
18454 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
18456 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
18462 { // remove all shelved variations
18464 for(i=0; i<storedGames; i++) {
18465 if(savedDetails[i])
18466 free(savedDetails[i]);
18467 savedDetails[i] = NULL;
18469 for(i=framePtr; i<MAX_MOVES; i++) {
18470 if(commentList[i]) free(commentList[i]);
18471 commentList[i] = NULL;
18473 framePtr = MAX_MOVES-1;
18478 LoadVariation (int index, char *text)
18479 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
18480 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
18481 int level = 0, move;
18483 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
18484 // first find outermost bracketing variation
18485 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
18486 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
18487 if(*p == '{') wait = '}'; else
18488 if(*p == '[') wait = ']'; else
18489 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
18490 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
18492 if(*p == wait) wait = NULLCHAR; // closing ]} found
18495 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
18496 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
18497 end[1] = NULLCHAR; // clip off comment beyond variation
18498 ToNrEvent(currentMove-1);
18499 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
18500 // kludge: use ParsePV() to append variation to game
18501 move = currentMove;
18502 ParsePV(start, TRUE, TRUE);
18503 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
18504 ClearPremoveHighlights();
18506 ToNrEvent(currentMove+1);
18512 char *p, *q, buf[MSG_SIZ];
18513 if(engineLine && engineLine[0]) { // a theme was selected from the listbox
18514 snprintf(buf, MSG_SIZ, "-theme %s", engineLine);
18515 ParseArgsFromString(buf);
18516 ActivateTheme(TRUE); // also redo colors
18520 if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
18523 q = appData.themeNames;
18524 snprintf(buf, MSG_SIZ, "\"%s\"", nickName);
18525 if(appData.useBitmaps) {
18526 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt true -lbtf \"%s\" -dbtf \"%s\" -lbtm %d -dbtm %d",
18527 appData.liteBackTextureFile, appData.darkBackTextureFile,
18528 appData.liteBackTextureMode,
18529 appData.darkBackTextureMode );
18531 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt false -lsc %s -dsc %s",
18532 Col2Text(2), // lightSquareColor
18533 Col2Text(3) ); // darkSquareColor
18535 if(appData.useBorder) {
18536 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub true -border \"%s\"",
18539 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub false");
18541 if(appData.useFont) {
18542 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
18543 appData.renderPiecesWithFont,
18544 appData.fontToPieceTable,
18545 Col2Text(9), // appData.fontBackColorWhite
18546 Col2Text(10) ); // appData.fontForeColorBlack
18548 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf false -pid \"%s\"",
18549 appData.pieceDirectory);
18550 if(!appData.pieceDirectory[0])
18551 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -wpc %s -bpc %s",
18552 Col2Text(0), // whitePieceColor
18553 Col2Text(1) ); // blackPieceColor
18555 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -hsc %s -phc %s\n",
18556 Col2Text(4), // highlightSquareColor
18557 Col2Text(5) ); // premoveHighlightColor
18558 appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
18559 if(insert != q) insert[-1] = NULLCHAR;
18560 snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
18563 ActivateTheme(FALSE);