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 Free Software Foundation, Inc.
10 * Enhancements Copyright 2005 Alessandro Scotti
12 * The following terms apply to Digital Equipment Corporation's copyright
14 * ------------------------------------------------------------------------
17 * Permission to use, copy, modify, and distribute this software and its
18 * documentation for any purpose and without fee is hereby granted,
19 * provided that the above copyright notice appear in all copies and that
20 * both that copyright notice and this permission notice appear in
21 * supporting documentation, and that the name of Digital not be
22 * used in advertising or publicity pertaining to distribution of the
23 * software without specific, written prior permission.
25 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32 * ------------------------------------------------------------------------
34 * The following terms apply to the enhanced version of XBoard
35 * distributed by the Free Software Foundation:
36 * ------------------------------------------------------------------------
38 * GNU XBoard is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or (at
41 * your option) any later version.
43 * GNU XBoard is distributed in the hope that it will be useful, but
44 * WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see http://www.gnu.org/licenses/. *
51 *------------------------------------------------------------------------
52 ** See the file ChangeLog for a revision history. */
54 /* [AS] Also useful here for debugging */
58 int flock(int f, int code);
75 #include <sys/types.h>
84 #else /* not STDC_HEADERS */
87 # else /* not HAVE_STRING_H */
89 # endif /* not HAVE_STRING_H */
90 #endif /* not STDC_HEADERS */
93 # include <sys/fcntl.h>
94 #else /* not HAVE_SYS_FCNTL_H */
97 # endif /* HAVE_FCNTL_H */
98 #endif /* not HAVE_SYS_FCNTL_H */
100 #if TIME_WITH_SYS_TIME
101 # include <sys/time.h>
105 # include <sys/time.h>
111 #if defined(_amigados) && !defined(__GNUC__)
116 extern int gettimeofday(struct timeval *, struct timezone *);
124 #include "frontend.h"
131 #include "backendz.h"
132 #include "evalgraph.h"
136 # define _(s) gettext (s)
137 # define N_(s) gettext_noop (s)
138 # define T_(s) gettext(s)
151 int establish P((void));
152 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
153 char *buf, int count, int error));
154 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
155 char *buf, int count, int error));
156 void SendToICS P((char *s));
157 void SendToICSDelayed P((char *s, long msdelay));
158 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
159 void HandleMachineMove P((char *message, ChessProgramState *cps));
160 int AutoPlayOneMove P((void));
161 int LoadGameOneMove P((ChessMove readAhead));
162 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
163 int LoadPositionFromFile P((char *filename, int n, char *title));
164 int SavePositionToFile P((char *filename));
165 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
166 void ShowMove P((int fromX, int fromY, int toX, int toY));
167 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
168 /*char*/int promoChar));
169 void BackwardInner P((int target));
170 void ForwardInner P((int target));
171 int Adjudicate P((ChessProgramState *cps));
172 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
173 void EditPositionDone P((Boolean fakeRights));
174 void PrintOpponents P((FILE *fp));
175 void PrintPosition P((FILE *fp, int move));
176 void StartChessProgram P((ChessProgramState *cps));
177 void SendToProgram P((char *message, ChessProgramState *cps));
178 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
179 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
180 char *buf, int count, int error));
181 void SendTimeControl P((ChessProgramState *cps,
182 int mps, long tc, int inc, int sd, int st));
183 char *TimeControlTagValue P((void));
184 void Attention P((ChessProgramState *cps));
185 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
186 int ResurrectChessProgram P((void));
187 void DisplayComment P((int moveNumber, char *text));
188 void DisplayMove P((int moveNumber));
190 void ParseGameHistory P((char *game));
191 void ParseBoard12 P((char *string));
192 void KeepAlive P((void));
193 void StartClocks P((void));
194 void SwitchClocks P((int nr));
195 void StopClocks P((void));
196 void ResetClocks P((void));
197 char *PGNDate P((void));
198 void SetGameInfo P((void));
199 int RegisterMove P((void));
200 void MakeRegisteredMove P((void));
201 void TruncateGame P((void));
202 int looking_at P((char *, int *, char *));
203 void CopyPlayerNameIntoFileName P((char **, char *));
204 char *SavePart P((char *));
205 int SaveGameOldStyle P((FILE *));
206 int SaveGamePGN P((FILE *));
207 int CheckFlags P((void));
208 long NextTickLength P((long));
209 void CheckTimeControl P((void));
210 void show_bytes P((FILE *, char *, int));
211 int string_to_rating P((char *str));
212 void ParseFeatures P((char* args, ChessProgramState *cps));
213 void InitBackEnd3 P((void));
214 void FeatureDone P((ChessProgramState* cps, int val));
215 void InitChessProgram P((ChessProgramState *cps, int setup));
216 void OutputKibitz(int window, char *text);
217 int PerpetualChase(int first, int last);
218 int EngineOutputIsUp();
219 void InitDrawingSizes(int x, int y);
220 void NextMatchGame P((void));
221 int NextTourneyGame P((int nr, int *swap));
222 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
223 FILE *WriteTourneyFile P((char *results, FILE *f));
224 void DisplayTwoMachinesTitle P(());
225 static void ExcludeClick P((int index));
226 void ToggleSecond P((void));
227 void PauseEngine P((ChessProgramState *cps));
228 static int NonStandardBoardSize P((void));
231 extern void ConsoleCreate();
234 ChessProgramState *WhitePlayer();
235 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
236 int VerifyDisplayMode P(());
238 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
239 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
240 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
241 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
242 void ics_update_width P((int new_width));
243 extern char installDir[MSG_SIZ];
244 VariantClass startVariant; /* [HGM] nicks: initial variant */
247 extern int tinyLayout, smallLayout;
248 ChessProgramStats programStats;
249 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
251 static int exiting = 0; /* [HGM] moved to top */
252 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
253 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
254 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
255 int partnerHighlight[2];
256 Boolean partnerBoardValid = 0;
257 char partnerStatus[MSG_SIZ];
259 Boolean originalFlip;
260 Boolean twoBoards = 0;
261 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
262 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
263 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
264 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
265 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
266 int opponentKibitzes;
267 int lastSavedGame; /* [HGM] save: ID of game */
268 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
269 extern int chatCount;
271 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
272 char lastMsg[MSG_SIZ];
273 ChessSquare pieceSweep = EmptySquare;
274 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
275 int promoDefaultAltered;
276 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
278 /* States for ics_getting_history */
280 #define H_REQUESTED 1
281 #define H_GOT_REQ_HEADER 2
282 #define H_GOT_UNREQ_HEADER 3
283 #define H_GETTING_MOVES 4
284 #define H_GOT_UNWANTED_HEADER 5
286 /* whosays values for GameEnds */
295 /* Maximum number of games in a cmail message */
296 #define CMAIL_MAX_GAMES 20
298 /* Different types of move when calling RegisterMove */
300 #define CMAIL_RESIGN 1
302 #define CMAIL_ACCEPT 3
304 /* Different types of result to remember for each game */
305 #define CMAIL_NOT_RESULT 0
306 #define CMAIL_OLD_RESULT 1
307 #define CMAIL_NEW_RESULT 2
309 /* Telnet protocol constants */
320 safeStrCpy (char *dst, const char *src, size_t count)
323 assert( dst != NULL );
324 assert( src != NULL );
327 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
328 if( i == count && dst[count-1] != NULLCHAR)
330 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
331 if(appData.debugMode)
332 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
338 /* Some compiler can't cast u64 to double
339 * This function do the job for us:
341 * We use the highest bit for cast, this only
342 * works if the highest bit is not
343 * in use (This should not happen)
345 * We used this for all compiler
348 u64ToDouble (u64 value)
351 u64 tmp = value & u64Const(0x7fffffffffffffff);
352 r = (double)(s64)tmp;
353 if (value & u64Const(0x8000000000000000))
354 r += 9.2233720368547758080e18; /* 2^63 */
358 /* Fake up flags for now, as we aren't keeping track of castling
359 availability yet. [HGM] Change of logic: the flag now only
360 indicates the type of castlings allowed by the rule of the game.
361 The actual rights themselves are maintained in the array
362 castlingRights, as part of the game history, and are not probed
368 int flags = F_ALL_CASTLE_OK;
369 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
370 switch (gameInfo.variant) {
372 flags &= ~F_ALL_CASTLE_OK;
373 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
374 flags |= F_IGNORE_CHECK;
376 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
379 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
381 case VariantKriegspiel:
382 flags |= F_KRIEGSPIEL_CAPTURE;
384 case VariantCapaRandom:
385 case VariantFischeRandom:
386 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
387 case VariantNoCastle:
388 case VariantShatranj:
392 flags &= ~F_ALL_CASTLE_OK;
400 FILE *gameFileFP, *debugFP, *serverFP;
401 char *currentDebugFile; // [HGM] debug split: to remember name
404 [AS] Note: sometimes, the sscanf() function is used to parse the input
405 into a fixed-size buffer. Because of this, we must be prepared to
406 receive strings as long as the size of the input buffer, which is currently
407 set to 4K for Windows and 8K for the rest.
408 So, we must either allocate sufficiently large buffers here, or
409 reduce the size of the input buffer in the input reading part.
412 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
413 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
414 char thinkOutput1[MSG_SIZ*10];
416 ChessProgramState first, second, pairing;
418 /* premove variables */
421 int premoveFromX = 0;
422 int premoveFromY = 0;
423 int premovePromoChar = 0;
425 Boolean alarmSounded;
426 /* end premove variables */
428 char *ics_prefix = "$";
429 enum ICS_TYPE ics_type = ICS_GENERIC;
431 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
432 int pauseExamForwardMostMove = 0;
433 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
434 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
435 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
436 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
437 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
438 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
439 int whiteFlag = FALSE, blackFlag = FALSE;
440 int userOfferedDraw = FALSE;
441 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
442 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
443 int cmailMoveType[CMAIL_MAX_GAMES];
444 long ics_clock_paused = 0;
445 ProcRef icsPR = NoProc, cmailPR = NoProc;
446 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
447 GameMode gameMode = BeginningOfGame;
448 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
449 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
450 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
451 int hiddenThinkOutputState = 0; /* [AS] */
452 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
453 int adjudicateLossPlies = 6;
454 char white_holding[64], black_holding[64];
455 TimeMark lastNodeCountTime;
456 long lastNodeCount=0;
457 int shiftKey, controlKey; // [HGM] set by mouse handler
459 int have_sent_ICS_logon = 0;
461 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
462 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
463 Boolean adjustedClock;
464 long timeControl_2; /* [AS] Allow separate time controls */
465 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
466 long timeRemaining[2][MAX_MOVES];
467 int matchGame = 0, nextGame = 0, roundNr = 0;
468 Boolean waitingForGame = FALSE, startingEngine = FALSE;
469 TimeMark programStartTime, pauseStart;
470 char ics_handle[MSG_SIZ];
471 int have_set_title = 0;
473 /* animateTraining preserves the state of appData.animate
474 * when Training mode is activated. This allows the
475 * response to be animated when appData.animate == TRUE and
476 * appData.animateDragging == TRUE.
478 Boolean animateTraining;
484 Board boards[MAX_MOVES];
485 /* [HGM] Following 7 needed for accurate legality tests: */
486 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
487 signed char initialRights[BOARD_FILES];
488 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
489 int initialRulePlies, FENrulePlies;
490 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
492 Boolean shuffleOpenings;
493 int mute; // mute all sounds
495 // [HGM] vari: next 12 to save and restore variations
496 #define MAX_VARIATIONS 10
497 int framePtr = MAX_MOVES-1; // points to free stack entry
499 int savedFirst[MAX_VARIATIONS];
500 int savedLast[MAX_VARIATIONS];
501 int savedFramePtr[MAX_VARIATIONS];
502 char *savedDetails[MAX_VARIATIONS];
503 ChessMove savedResult[MAX_VARIATIONS];
505 void PushTail P((int firstMove, int lastMove));
506 Boolean PopTail P((Boolean annotate));
507 void PushInner P((int firstMove, int lastMove));
508 void PopInner P((Boolean annotate));
509 void CleanupTail P((void));
511 ChessSquare FIDEArray[2][BOARD_FILES] = {
512 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
513 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
514 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
515 BlackKing, BlackBishop, BlackKnight, BlackRook }
518 ChessSquare twoKingsArray[2][BOARD_FILES] = {
519 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
520 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
521 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
522 BlackKing, BlackKing, BlackKnight, BlackRook }
525 ChessSquare KnightmateArray[2][BOARD_FILES] = {
526 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
527 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
528 { BlackRook, BlackMan, BlackBishop, BlackQueen,
529 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
532 ChessSquare SpartanArray[2][BOARD_FILES] = {
533 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
534 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
535 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
536 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
539 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
540 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
541 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
542 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
543 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
546 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
547 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
548 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
549 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
550 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
553 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
554 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
555 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
556 { BlackRook, BlackKnight, BlackMan, BlackFerz,
557 BlackKing, BlackMan, BlackKnight, BlackRook }
561 #if (BOARD_FILES>=10)
562 ChessSquare ShogiArray[2][BOARD_FILES] = {
563 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
564 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
565 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
566 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
569 ChessSquare XiangqiArray[2][BOARD_FILES] = {
570 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
571 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
572 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
573 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
576 ChessSquare CapablancaArray[2][BOARD_FILES] = {
577 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
578 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
579 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
580 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
583 ChessSquare GreatArray[2][BOARD_FILES] = {
584 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
585 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
586 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
587 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
590 ChessSquare JanusArray[2][BOARD_FILES] = {
591 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
592 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
593 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
594 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
597 ChessSquare GrandArray[2][BOARD_FILES] = {
598 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
599 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
600 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
601 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
605 ChessSquare GothicArray[2][BOARD_FILES] = {
606 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
607 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
608 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
609 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
612 #define GothicArray CapablancaArray
616 ChessSquare FalconArray[2][BOARD_FILES] = {
617 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
618 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
619 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
620 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
623 #define FalconArray CapablancaArray
626 #else // !(BOARD_FILES>=10)
627 #define XiangqiPosition FIDEArray
628 #define CapablancaArray FIDEArray
629 #define GothicArray FIDEArray
630 #define GreatArray FIDEArray
631 #endif // !(BOARD_FILES>=10)
633 #if (BOARD_FILES>=12)
634 ChessSquare CourierArray[2][BOARD_FILES] = {
635 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
636 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
637 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
638 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
640 #else // !(BOARD_FILES>=12)
641 #define CourierArray CapablancaArray
642 #endif // !(BOARD_FILES>=12)
645 Board initialPosition;
648 /* Convert str to a rating. Checks for special cases of "----",
650 "++++", etc. Also strips ()'s */
652 string_to_rating (char *str)
654 while(*str && !isdigit(*str)) ++str;
656 return 0; /* One of the special "no rating" cases */
664 /* Init programStats */
665 programStats.movelist[0] = 0;
666 programStats.depth = 0;
667 programStats.nr_moves = 0;
668 programStats.moves_left = 0;
669 programStats.nodes = 0;
670 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
671 programStats.score = 0;
672 programStats.got_only_move = 0;
673 programStats.got_fail = 0;
674 programStats.line_is_book = 0;
679 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
680 if (appData.firstPlaysBlack) {
681 first.twoMachinesColor = "black\n";
682 second.twoMachinesColor = "white\n";
684 first.twoMachinesColor = "white\n";
685 second.twoMachinesColor = "black\n";
688 first.other = &second;
689 second.other = &first;
692 if(appData.timeOddsMode) {
693 norm = appData.timeOdds[0];
694 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
696 first.timeOdds = appData.timeOdds[0]/norm;
697 second.timeOdds = appData.timeOdds[1]/norm;
700 if(programVersion) free(programVersion);
701 if (appData.noChessProgram) {
702 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
703 sprintf(programVersion, "%s", PACKAGE_STRING);
705 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
706 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
707 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
712 UnloadEngine (ChessProgramState *cps)
714 /* Kill off first chess program */
715 if (cps->isr != NULL)
716 RemoveInputSource(cps->isr);
719 if (cps->pr != NoProc) {
721 DoSleep( appData.delayBeforeQuit );
722 SendToProgram("quit\n", cps);
723 DoSleep( appData.delayAfterQuit );
724 DestroyChildProcess(cps->pr, cps->useSigterm);
727 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
731 ClearOptions (ChessProgramState *cps)
734 cps->nrOptions = cps->comboCnt = 0;
735 for(i=0; i<MAX_OPTIONS; i++) {
736 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
737 cps->option[i].textValue = 0;
741 char *engineNames[] = {
742 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
743 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
745 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
746 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
751 InitEngine (ChessProgramState *cps, int n)
752 { // [HGM] all engine initialiation put in a function that does one engine
756 cps->which = engineNames[n];
757 cps->maybeThinking = FALSE;
761 cps->sendDrawOffers = 1;
763 cps->program = appData.chessProgram[n];
764 cps->host = appData.host[n];
765 cps->dir = appData.directory[n];
766 cps->initString = appData.engInitString[n];
767 cps->computerString = appData.computerString[n];
768 cps->useSigint = TRUE;
769 cps->useSigterm = TRUE;
770 cps->reuse = appData.reuse[n];
771 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
772 cps->useSetboard = FALSE;
774 cps->usePing = FALSE;
777 cps->usePlayother = FALSE;
778 cps->useColors = TRUE;
779 cps->useUsermove = FALSE;
780 cps->sendICS = FALSE;
781 cps->sendName = appData.icsActive;
782 cps->sdKludge = FALSE;
783 cps->stKludge = FALSE;
784 if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
785 TidyProgramName(cps->program, cps->host, cps->tidy);
787 ASSIGN(cps->variants, appData.variant);
788 cps->analysisSupport = 2; /* detect */
789 cps->analyzing = FALSE;
790 cps->initDone = FALSE;
793 /* New features added by Tord: */
794 cps->useFEN960 = FALSE;
795 cps->useOOCastle = TRUE;
796 /* End of new features added by Tord. */
797 cps->fenOverride = appData.fenOverride[n];
799 /* [HGM] time odds: set factor for each machine */
800 cps->timeOdds = appData.timeOdds[n];
802 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
803 cps->accumulateTC = appData.accumulateTC[n];
804 cps->maxNrOfSessions = 1;
809 cps->supportsNPS = UNKNOWN;
810 cps->memSize = FALSE;
811 cps->maxCores = FALSE;
812 ASSIGN(cps->egtFormats, "");
815 cps->optionSettings = appData.engOptions[n];
817 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
818 cps->isUCI = appData.isUCI[n]; /* [AS] */
819 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
821 if (appData.protocolVersion[n] > PROTOVER
822 || appData.protocolVersion[n] < 1)
827 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
828 appData.protocolVersion[n]);
829 if( (len >= MSG_SIZ) && appData.debugMode )
830 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
832 DisplayFatalError(buf, 0, 2);
836 cps->protocolVersion = appData.protocolVersion[n];
839 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
840 ParseFeatures(appData.featureDefaults, cps);
843 ChessProgramState *savCps;
851 if(WaitForEngine(savCps, LoadEngine)) return;
852 CommonEngineInit(); // recalculate time odds
853 if(gameInfo.variant != StringToVariant(appData.variant)) {
854 // we changed variant when loading the engine; this forces us to reset
855 Reset(TRUE, savCps != &first);
856 oldMode = BeginningOfGame; // to prevent restoring old mode
858 InitChessProgram(savCps, FALSE);
859 if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
860 DisplayMessage("", "");
861 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
862 for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
865 if(oldMode == AnalyzeMode) AnalyzeModeEvent();
869 ReplaceEngine (ChessProgramState *cps, int n)
871 oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
873 if(oldMode != BeginningOfGame) EditGameEvent();
876 appData.noChessProgram = FALSE;
877 appData.clockMode = TRUE;
880 if(n) return; // only startup first engine immediately; second can wait
881 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
885 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
886 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
888 static char resetOptions[] =
889 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
890 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
891 "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 "
892 "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
895 FloatToFront(char **list, char *engineLine)
897 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
899 if(appData.recentEngines <= 0) return;
900 TidyProgramName(engineLine, "localhost", tidy+1);
901 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
902 strncpy(buf+1, *list, MSG_SIZ-50);
903 if(p = strstr(buf, tidy)) { // tidy name appears in list
904 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
905 while(*p++ = *++q); // squeeze out
907 strcat(tidy, buf+1); // put list behind tidy name
908 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
909 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
910 ASSIGN(*list, tidy+1);
913 char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
916 Load (ChessProgramState *cps, int i)
918 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ];
919 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
920 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
921 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
922 ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
923 FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
924 appData.firstProtocolVersion = PROTOVER;
925 ParseArgsFromString(buf);
927 ReplaceEngine(cps, i);
928 FloatToFront(&appData.recentEngineList, engineLine);
932 while(q = strchr(p, SLASH)) p = q+1;
933 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
934 if(engineDir[0] != NULLCHAR) {
935 ASSIGN(appData.directory[i], engineDir); p = engineName;
936 } else if(p != engineName) { // derive directory from engine path, when not given
938 ASSIGN(appData.directory[i], engineName);
940 if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
941 } else { ASSIGN(appData.directory[i], "."); }
943 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
944 snprintf(command, MSG_SIZ, "%s %s", p, params);
947 ASSIGN(appData.chessProgram[i], p);
948 appData.isUCI[i] = isUCI;
949 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
950 appData.hasOwnBookUCI[i] = hasBook;
951 if(!nickName[0]) useNick = FALSE;
952 if(useNick) ASSIGN(appData.pgnName[i], nickName);
956 q = firstChessProgramNames;
957 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
958 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
959 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
960 quote, p, quote, appData.directory[i],
961 useNick ? " -fn \"" : "",
962 useNick ? nickName : "",
964 v1 ? " -firstProtocolVersion 1" : "",
965 hasBook ? "" : " -fNoOwnBookUCI",
966 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
967 storeVariant ? " -variant " : "",
968 storeVariant ? VariantName(gameInfo.variant) : "");
969 if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
970 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
971 if(insert != q) insert[-1] = NULLCHAR;
972 snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
974 FloatToFront(&appData.recentEngineList, buf);
976 ReplaceEngine(cps, i);
982 int matched, min, sec;
984 * Parse timeControl resource
986 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
987 appData.movesPerSession)) {
989 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
990 DisplayFatalError(buf, 0, 2);
994 * Parse searchTime resource
996 if (*appData.searchTime != NULLCHAR) {
997 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
999 searchTime = min * 60;
1000 } else if (matched == 2) {
1001 searchTime = min * 60 + sec;
1004 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1005 DisplayFatalError(buf, 0, 2);
1014 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1015 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1017 GetTimeMark(&programStartTime);
1018 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1019 appData.seedBase = random() + (random()<<15);
1020 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1022 ClearProgramStats();
1023 programStats.ok_to_send = 1;
1024 programStats.seen_stat = 0;
1027 * Initialize game list
1033 * Internet chess server status
1035 if (appData.icsActive) {
1036 appData.matchMode = FALSE;
1037 appData.matchGames = 0;
1039 appData.noChessProgram = !appData.zippyPlay;
1041 appData.zippyPlay = FALSE;
1042 appData.zippyTalk = FALSE;
1043 appData.noChessProgram = TRUE;
1045 if (*appData.icsHelper != NULLCHAR) {
1046 appData.useTelnet = TRUE;
1047 appData.telnetProgram = appData.icsHelper;
1050 appData.zippyTalk = appData.zippyPlay = FALSE;
1053 /* [AS] Initialize pv info list [HGM] and game state */
1057 for( i=0; i<=framePtr; i++ ) {
1058 pvInfoList[i].depth = -1;
1059 boards[i][EP_STATUS] = EP_NONE;
1060 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1066 /* [AS] Adjudication threshold */
1067 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1069 InitEngine(&first, 0);
1070 InitEngine(&second, 1);
1073 pairing.which = "pairing"; // pairing engine
1074 pairing.pr = NoProc;
1076 pairing.program = appData.pairingEngine;
1077 pairing.host = "localhost";
1080 if (appData.icsActive) {
1081 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1082 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1083 appData.clockMode = FALSE;
1084 first.sendTime = second.sendTime = 0;
1088 /* Override some settings from environment variables, for backward
1089 compatibility. Unfortunately it's not feasible to have the env
1090 vars just set defaults, at least in xboard. Ugh.
1092 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1097 if (!appData.icsActive) {
1101 /* Check for variants that are supported only in ICS mode,
1102 or not at all. Some that are accepted here nevertheless
1103 have bugs; see comments below.
1105 VariantClass variant = StringToVariant(appData.variant);
1107 case VariantBughouse: /* need four players and two boards */
1108 case VariantKriegspiel: /* need to hide pieces and move details */
1109 /* case VariantFischeRandom: (Fabien: moved below) */
1110 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1111 if( (len >= MSG_SIZ) && appData.debugMode )
1112 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1114 DisplayFatalError(buf, 0, 2);
1117 case VariantUnknown:
1118 case VariantLoadable:
1128 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1129 if( (len >= MSG_SIZ) && appData.debugMode )
1130 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1132 DisplayFatalError(buf, 0, 2);
1135 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1136 case VariantFairy: /* [HGM] TestLegality definitely off! */
1137 case VariantGothic: /* [HGM] should work */
1138 case VariantCapablanca: /* [HGM] should work */
1139 case VariantCourier: /* [HGM] initial forced moves not implemented */
1140 case VariantShogi: /* [HGM] could still mate with pawn drop */
1141 case VariantKnightmate: /* [HGM] should work */
1142 case VariantCylinder: /* [HGM] untested */
1143 case VariantFalcon: /* [HGM] untested */
1144 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1145 offboard interposition not understood */
1146 case VariantNormal: /* definitely works! */
1147 case VariantWildCastle: /* pieces not automatically shuffled */
1148 case VariantNoCastle: /* pieces not automatically shuffled */
1149 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1150 case VariantLosers: /* should work except for win condition,
1151 and doesn't know captures are mandatory */
1152 case VariantSuicide: /* should work except for win condition,
1153 and doesn't know captures are mandatory */
1154 case VariantGiveaway: /* should work except for win condition,
1155 and doesn't know captures are mandatory */
1156 case VariantTwoKings: /* should work */
1157 case VariantAtomic: /* should work except for win condition */
1158 case Variant3Check: /* should work except for win condition */
1159 case VariantShatranj: /* should work except for all win conditions */
1160 case VariantMakruk: /* should work except for draw countdown */
1161 case VariantBerolina: /* might work if TestLegality is off */
1162 case VariantCapaRandom: /* should work */
1163 case VariantJanus: /* should work */
1164 case VariantSuper: /* experimental */
1165 case VariantGreat: /* experimental, requires legality testing to be off */
1166 case VariantSChess: /* S-Chess, should work */
1167 case VariantGrand: /* should work */
1168 case VariantSpartan: /* should work */
1176 NextIntegerFromString (char ** str, long * value)
1181 while( *s == ' ' || *s == '\t' ) {
1187 if( *s >= '0' && *s <= '9' ) {
1188 while( *s >= '0' && *s <= '9' ) {
1189 *value = *value * 10 + (*s - '0');
1202 NextTimeControlFromString (char ** str, long * value)
1205 int result = NextIntegerFromString( str, &temp );
1208 *value = temp * 60; /* Minutes */
1209 if( **str == ':' ) {
1211 result = NextIntegerFromString( str, &temp );
1212 *value += temp; /* Seconds */
1220 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1221 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1222 int result = -1, type = 0; long temp, temp2;
1224 if(**str != ':') return -1; // old params remain in force!
1226 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1227 if( NextIntegerFromString( str, &temp ) ) return -1;
1228 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1231 /* time only: incremental or sudden-death time control */
1232 if(**str == '+') { /* increment follows; read it */
1234 if(**str == '!') type = *(*str)++; // Bronstein TC
1235 if(result = NextIntegerFromString( str, &temp2)) return -1;
1236 *inc = temp2 * 1000;
1237 if(**str == '.') { // read fraction of increment
1238 char *start = ++(*str);
1239 if(result = NextIntegerFromString( str, &temp2)) return -1;
1241 while(start++ < *str) temp2 /= 10;
1245 *moves = 0; *tc = temp * 1000; *incType = type;
1249 (*str)++; /* classical time control */
1250 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1262 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1263 { /* [HGM] get time to add from the multi-session time-control string */
1264 int incType, moves=1; /* kludge to force reading of first session */
1265 long time, increment;
1268 if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1270 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1271 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1272 if(movenr == -1) return time; /* last move before new session */
1273 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1274 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1275 if(!moves) return increment; /* current session is incremental */
1276 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1277 } while(movenr >= -1); /* try again for next session */
1279 return 0; // no new time quota on this move
1283 ParseTimeControl (char *tc, float ti, int mps)
1287 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1290 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1291 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1292 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1296 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1298 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1301 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1303 snprintf(buf, MSG_SIZ, ":%s", mytc);
1305 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1307 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1312 /* Parse second time control */
1315 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1323 timeControl_2 = tc2 * 1000;
1333 timeControl = tc1 * 1000;
1336 timeIncrement = ti * 1000; /* convert to ms */
1337 movesPerSession = 0;
1340 movesPerSession = mps;
1348 if (appData.debugMode) {
1349 # ifdef __GIT_VERSION
1350 fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1352 fprintf(debugFP, "Version: %s\n", programVersion);
1355 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1357 set_cont_sequence(appData.wrapContSeq);
1358 if (appData.matchGames > 0) {
1359 appData.matchMode = TRUE;
1360 } else if (appData.matchMode) {
1361 appData.matchGames = 1;
1363 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1364 appData.matchGames = appData.sameColorGames;
1365 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1366 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1367 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1370 if (appData.noChessProgram || first.protocolVersion == 1) {
1373 /* kludge: allow timeout for initial "feature" commands */
1375 DisplayMessage("", _("Starting chess program"));
1376 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1381 CalculateIndex (int index, int gameNr)
1382 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1384 if(index > 0) return index; // fixed nmber
1385 if(index == 0) return 1;
1386 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1387 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1392 LoadGameOrPosition (int gameNr)
1393 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1394 if (*appData.loadGameFile != NULLCHAR) {
1395 if (!LoadGameFromFile(appData.loadGameFile,
1396 CalculateIndex(appData.loadGameIndex, gameNr),
1397 appData.loadGameFile, FALSE)) {
1398 DisplayFatalError(_("Bad game file"), 0, 1);
1401 } else if (*appData.loadPositionFile != NULLCHAR) {
1402 if (!LoadPositionFromFile(appData.loadPositionFile,
1403 CalculateIndex(appData.loadPositionIndex, gameNr),
1404 appData.loadPositionFile)) {
1405 DisplayFatalError(_("Bad position file"), 0, 1);
1413 ReserveGame (int gameNr, char resChar)
1415 FILE *tf = fopen(appData.tourneyFile, "r+");
1416 char *p, *q, c, buf[MSG_SIZ];
1417 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1418 safeStrCpy(buf, lastMsg, MSG_SIZ);
1419 DisplayMessage(_("Pick new game"), "");
1420 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1421 ParseArgsFromFile(tf);
1422 p = q = appData.results;
1423 if(appData.debugMode) {
1424 char *r = appData.participants;
1425 fprintf(debugFP, "results = '%s'\n", p);
1426 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1427 fprintf(debugFP, "\n");
1429 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1431 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1432 safeStrCpy(q, p, strlen(p) + 2);
1433 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1434 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1435 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1436 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1439 fseek(tf, -(strlen(p)+4), SEEK_END);
1441 if(c != '"') // depending on DOS or Unix line endings we can be one off
1442 fseek(tf, -(strlen(p)+2), SEEK_END);
1443 else fseek(tf, -(strlen(p)+3), SEEK_END);
1444 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1445 DisplayMessage(buf, "");
1446 free(p); appData.results = q;
1447 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1448 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1449 int round = appData.defaultMatchGames * appData.tourneyType;
1450 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1451 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1452 UnloadEngine(&first); // next game belongs to other pairing;
1453 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1455 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1459 MatchEvent (int mode)
1460 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1462 if(matchMode) { // already in match mode: switch it off
1464 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1467 // if(gameMode != BeginningOfGame) {
1468 // DisplayError(_("You can only start a match from the initial position."), 0);
1472 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1473 /* Set up machine vs. machine match */
1475 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1476 if(appData.tourneyFile[0]) {
1478 if(nextGame > appData.matchGames) {
1480 if(strchr(appData.results, '*') == NULL) {
1482 appData.tourneyCycles++;
1483 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1485 NextTourneyGame(-1, &dummy);
1487 if(nextGame <= appData.matchGames) {
1488 DisplayNote(_("You restarted an already completed tourney\nOne more cycle will now be added to it\nGames commence in 10 sec"));
1490 ScheduleDelayedEvent(NextMatchGame, 10000);
1495 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1496 DisplayError(buf, 0);
1497 appData.tourneyFile[0] = 0;
1501 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1502 DisplayFatalError(_("Can't have a match with no chess programs"),
1507 matchGame = roundNr = 1;
1508 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1512 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1515 InitBackEnd3 P((void))
1517 GameMode initialMode;
1521 InitChessProgram(&first, startedFromSetupPosition);
1523 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1524 free(programVersion);
1525 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1526 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1527 FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1530 if (appData.icsActive) {
1532 /* [DM] Make a console window if needed [HGM] merged ifs */
1538 if (*appData.icsCommPort != NULLCHAR)
1539 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1540 appData.icsCommPort);
1542 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1543 appData.icsHost, appData.icsPort);
1545 if( (len >= MSG_SIZ) && appData.debugMode )
1546 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1548 DisplayFatalError(buf, err, 1);
1553 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1555 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1556 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1557 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1558 } else if (appData.noChessProgram) {
1564 if (*appData.cmailGameName != NULLCHAR) {
1566 OpenLoopback(&cmailPR);
1568 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1572 DisplayMessage("", "");
1573 if (StrCaseCmp(appData.initialMode, "") == 0) {
1574 initialMode = BeginningOfGame;
1575 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1576 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1577 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1578 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1581 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1582 initialMode = TwoMachinesPlay;
1583 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1584 initialMode = AnalyzeFile;
1585 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1586 initialMode = AnalyzeMode;
1587 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1588 initialMode = MachinePlaysWhite;
1589 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1590 initialMode = MachinePlaysBlack;
1591 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1592 initialMode = EditGame;
1593 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1594 initialMode = EditPosition;
1595 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1596 initialMode = Training;
1598 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1599 if( (len >= MSG_SIZ) && appData.debugMode )
1600 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1602 DisplayFatalError(buf, 0, 2);
1606 if (appData.matchMode) {
1607 if(appData.tourneyFile[0]) { // start tourney from command line
1609 if(f = fopen(appData.tourneyFile, "r")) {
1610 ParseArgsFromFile(f); // make sure tourney parmeters re known
1612 appData.clockMode = TRUE;
1614 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1617 } else if (*appData.cmailGameName != NULLCHAR) {
1618 /* Set up cmail mode */
1619 ReloadCmailMsgEvent(TRUE);
1621 /* Set up other modes */
1622 if (initialMode == AnalyzeFile) {
1623 if (*appData.loadGameFile == NULLCHAR) {
1624 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1628 if (*appData.loadGameFile != NULLCHAR) {
1629 (void) LoadGameFromFile(appData.loadGameFile,
1630 appData.loadGameIndex,
1631 appData.loadGameFile, TRUE);
1632 } else if (*appData.loadPositionFile != NULLCHAR) {
1633 (void) LoadPositionFromFile(appData.loadPositionFile,
1634 appData.loadPositionIndex,
1635 appData.loadPositionFile);
1636 /* [HGM] try to make self-starting even after FEN load */
1637 /* to allow automatic setup of fairy variants with wtm */
1638 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1639 gameMode = BeginningOfGame;
1640 setboardSpoiledMachineBlack = 1;
1642 /* [HGM] loadPos: make that every new game uses the setup */
1643 /* from file as long as we do not switch variant */
1644 if(!blackPlaysFirst) {
1645 startedFromPositionFile = TRUE;
1646 CopyBoard(filePosition, boards[0]);
1649 if (initialMode == AnalyzeMode) {
1650 if (appData.noChessProgram) {
1651 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1654 if (appData.icsActive) {
1655 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1659 } else if (initialMode == AnalyzeFile) {
1660 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1661 ShowThinkingEvent();
1663 AnalysisPeriodicEvent(1);
1664 } else if (initialMode == MachinePlaysWhite) {
1665 if (appData.noChessProgram) {
1666 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1670 if (appData.icsActive) {
1671 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1675 MachineWhiteEvent();
1676 } else if (initialMode == MachinePlaysBlack) {
1677 if (appData.noChessProgram) {
1678 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1682 if (appData.icsActive) {
1683 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1687 MachineBlackEvent();
1688 } else if (initialMode == TwoMachinesPlay) {
1689 if (appData.noChessProgram) {
1690 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1694 if (appData.icsActive) {
1695 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1700 } else if (initialMode == EditGame) {
1702 } else if (initialMode == EditPosition) {
1703 EditPositionEvent();
1704 } else if (initialMode == Training) {
1705 if (*appData.loadGameFile == NULLCHAR) {
1706 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1715 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1717 DisplayBook(current+1);
1719 MoveHistorySet( movelist, first, last, current, pvInfoList );
1721 EvalGraphSet( first, last, current, pvInfoList );
1723 MakeEngineOutputTitle();
1727 * Establish will establish a contact to a remote host.port.
1728 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1729 * used to talk to the host.
1730 * Returns 0 if okay, error code if not.
1737 if (*appData.icsCommPort != NULLCHAR) {
1738 /* Talk to the host through a serial comm port */
1739 return OpenCommPort(appData.icsCommPort, &icsPR);
1741 } else if (*appData.gateway != NULLCHAR) {
1742 if (*appData.remoteShell == NULLCHAR) {
1743 /* Use the rcmd protocol to run telnet program on a gateway host */
1744 snprintf(buf, sizeof(buf), "%s %s %s",
1745 appData.telnetProgram, appData.icsHost, appData.icsPort);
1746 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1749 /* Use the rsh program to run telnet program on a gateway host */
1750 if (*appData.remoteUser == NULLCHAR) {
1751 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1752 appData.gateway, appData.telnetProgram,
1753 appData.icsHost, appData.icsPort);
1755 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1756 appData.remoteShell, appData.gateway,
1757 appData.remoteUser, appData.telnetProgram,
1758 appData.icsHost, appData.icsPort);
1760 return StartChildProcess(buf, "", &icsPR);
1763 } else if (appData.useTelnet) {
1764 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1767 /* TCP socket interface differs somewhat between
1768 Unix and NT; handle details in the front end.
1770 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1775 EscapeExpand (char *p, char *q)
1776 { // [HGM] initstring: routine to shape up string arguments
1777 while(*p++ = *q++) if(p[-1] == '\\')
1779 case 'n': p[-1] = '\n'; break;
1780 case 'r': p[-1] = '\r'; break;
1781 case 't': p[-1] = '\t'; break;
1782 case '\\': p[-1] = '\\'; break;
1783 case 0: *p = 0; return;
1784 default: p[-1] = q[-1]; break;
1789 show_bytes (FILE *fp, char *buf, int count)
1792 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1793 fprintf(fp, "\\%03o", *buf & 0xff);
1802 /* Returns an errno value */
1804 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1806 char buf[8192], *p, *q, *buflim;
1807 int left, newcount, outcount;
1809 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1810 *appData.gateway != NULLCHAR) {
1811 if (appData.debugMode) {
1812 fprintf(debugFP, ">ICS: ");
1813 show_bytes(debugFP, message, count);
1814 fprintf(debugFP, "\n");
1816 return OutputToProcess(pr, message, count, outError);
1819 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1826 if (appData.debugMode) {
1827 fprintf(debugFP, ">ICS: ");
1828 show_bytes(debugFP, buf, newcount);
1829 fprintf(debugFP, "\n");
1831 outcount = OutputToProcess(pr, buf, newcount, outError);
1832 if (outcount < newcount) return -1; /* to be sure */
1839 } else if (((unsigned char) *p) == TN_IAC) {
1840 *q++ = (char) TN_IAC;
1847 if (appData.debugMode) {
1848 fprintf(debugFP, ">ICS: ");
1849 show_bytes(debugFP, buf, newcount);
1850 fprintf(debugFP, "\n");
1852 outcount = OutputToProcess(pr, buf, newcount, outError);
1853 if (outcount < newcount) return -1; /* to be sure */
1858 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1860 int outError, outCount;
1861 static int gotEof = 0;
1864 /* Pass data read from player on to ICS */
1867 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1868 if (outCount < count) {
1869 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1871 if(have_sent_ICS_logon == 2) {
1872 if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1873 fprintf(ini, "%s", message);
1874 have_sent_ICS_logon = 3;
1876 have_sent_ICS_logon = 1;
1877 } else if(have_sent_ICS_logon == 3) {
1878 fprintf(ini, "%s", message);
1880 have_sent_ICS_logon = 1;
1882 } else if (count < 0) {
1883 RemoveInputSource(isr);
1884 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1885 } else if (gotEof++ > 0) {
1886 RemoveInputSource(isr);
1887 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1893 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1894 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1895 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1896 SendToICS("date\n");
1897 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1900 /* added routine for printf style output to ics */
1902 ics_printf (char *format, ...)
1904 char buffer[MSG_SIZ];
1907 va_start(args, format);
1908 vsnprintf(buffer, sizeof(buffer), format, args);
1909 buffer[sizeof(buffer)-1] = '\0';
1917 int count, outCount, outError;
1919 if (icsPR == NoProc) return;
1922 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1923 if (outCount < count) {
1924 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1928 /* This is used for sending logon scripts to the ICS. Sending
1929 without a delay causes problems when using timestamp on ICC
1930 (at least on my machine). */
1932 SendToICSDelayed (char *s, long msdelay)
1934 int count, outCount, outError;
1936 if (icsPR == NoProc) return;
1939 if (appData.debugMode) {
1940 fprintf(debugFP, ">ICS: ");
1941 show_bytes(debugFP, s, count);
1942 fprintf(debugFP, "\n");
1944 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1946 if (outCount < count) {
1947 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1952 /* Remove all highlighting escape sequences in s
1953 Also deletes any suffix starting with '('
1956 StripHighlightAndTitle (char *s)
1958 static char retbuf[MSG_SIZ];
1961 while (*s != NULLCHAR) {
1962 while (*s == '\033') {
1963 while (*s != NULLCHAR && !isalpha(*s)) s++;
1964 if (*s != NULLCHAR) s++;
1966 while (*s != NULLCHAR && *s != '\033') {
1967 if (*s == '(' || *s == '[') {
1978 /* Remove all highlighting escape sequences in s */
1980 StripHighlight (char *s)
1982 static char retbuf[MSG_SIZ];
1985 while (*s != NULLCHAR) {
1986 while (*s == '\033') {
1987 while (*s != NULLCHAR && !isalpha(*s)) s++;
1988 if (*s != NULLCHAR) s++;
1990 while (*s != NULLCHAR && *s != '\033') {
1998 char *variantNames[] = VARIANT_NAMES;
2000 VariantName (VariantClass v)
2002 return variantNames[v];
2006 /* Identify a variant from the strings the chess servers use or the
2007 PGN Variant tag names we use. */
2009 StringToVariant (char *e)
2013 VariantClass v = VariantNormal;
2014 int i, found = FALSE;
2020 /* [HGM] skip over optional board-size prefixes */
2021 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
2022 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
2023 while( *e++ != '_');
2026 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2030 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2031 if (StrCaseStr(e, variantNames[i])) {
2032 v = (VariantClass) i;
2039 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2040 || StrCaseStr(e, "wild/fr")
2041 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2042 v = VariantFischeRandom;
2043 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2044 (i = 1, p = StrCaseStr(e, "w"))) {
2046 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2053 case 0: /* FICS only, actually */
2055 /* Castling legal even if K starts on d-file */
2056 v = VariantWildCastle;
2061 /* Castling illegal even if K & R happen to start in
2062 normal positions. */
2063 v = VariantNoCastle;
2076 /* Castling legal iff K & R start in normal positions */
2082 /* Special wilds for position setup; unclear what to do here */
2083 v = VariantLoadable;
2086 /* Bizarre ICC game */
2087 v = VariantTwoKings;
2090 v = VariantKriegspiel;
2096 v = VariantFischeRandom;
2099 v = VariantCrazyhouse;
2102 v = VariantBughouse;
2108 /* Not quite the same as FICS suicide! */
2109 v = VariantGiveaway;
2115 v = VariantShatranj;
2118 /* Temporary names for future ICC types. The name *will* change in
2119 the next xboard/WinBoard release after ICC defines it. */
2157 v = VariantCapablanca;
2160 v = VariantKnightmate;
2166 v = VariantCylinder;
2172 v = VariantCapaRandom;
2175 v = VariantBerolina;
2187 /* Found "wild" or "w" in the string but no number;
2188 must assume it's normal chess. */
2192 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2193 if( (len >= MSG_SIZ) && appData.debugMode )
2194 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2196 DisplayError(buf, 0);
2202 if (appData.debugMode) {
2203 fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2204 e, wnum, VariantName(v));
2209 static int leftover_start = 0, leftover_len = 0;
2210 char star_match[STAR_MATCH_N][MSG_SIZ];
2212 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2213 advance *index beyond it, and set leftover_start to the new value of
2214 *index; else return FALSE. If pattern contains the character '*', it
2215 matches any sequence of characters not containing '\r', '\n', or the
2216 character following the '*' (if any), and the matched sequence(s) are
2217 copied into star_match.
2220 looking_at ( char *buf, int *index, char *pattern)
2222 char *bufp = &buf[*index], *patternp = pattern;
2224 char *matchp = star_match[0];
2227 if (*patternp == NULLCHAR) {
2228 *index = leftover_start = bufp - buf;
2232 if (*bufp == NULLCHAR) return FALSE;
2233 if (*patternp == '*') {
2234 if (*bufp == *(patternp + 1)) {
2236 matchp = star_match[++star_count];
2240 } else if (*bufp == '\n' || *bufp == '\r') {
2242 if (*patternp == NULLCHAR)
2247 *matchp++ = *bufp++;
2251 if (*patternp != *bufp) return FALSE;
2258 SendToPlayer (char *data, int length)
2260 int error, outCount;
2261 outCount = OutputToProcess(NoProc, data, length, &error);
2262 if (outCount < length) {
2263 DisplayFatalError(_("Error writing to display"), error, 1);
2268 PackHolding (char packed[], char *holding)
2278 switch (runlength) {
2289 sprintf(q, "%d", runlength);
2301 /* Telnet protocol requests from the front end */
2303 TelnetRequest (unsigned char ddww, unsigned char option)
2305 unsigned char msg[3];
2306 int outCount, outError;
2308 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2310 if (appData.debugMode) {
2311 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2327 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2336 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2339 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2344 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2346 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2353 if (!appData.icsActive) return;
2354 TelnetRequest(TN_DO, TN_ECHO);
2360 if (!appData.icsActive) return;
2361 TelnetRequest(TN_DONT, TN_ECHO);
2365 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2367 /* put the holdings sent to us by the server on the board holdings area */
2368 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2372 if(gameInfo.holdingsWidth < 2) return;
2373 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2374 return; // prevent overwriting by pre-board holdings
2376 if( (int)lowestPiece >= BlackPawn ) {
2379 holdingsStartRow = BOARD_HEIGHT-1;
2382 holdingsColumn = BOARD_WIDTH-1;
2383 countsColumn = BOARD_WIDTH-2;
2384 holdingsStartRow = 0;
2388 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2389 board[i][holdingsColumn] = EmptySquare;
2390 board[i][countsColumn] = (ChessSquare) 0;
2392 while( (p=*holdings++) != NULLCHAR ) {
2393 piece = CharToPiece( ToUpper(p) );
2394 if(piece == EmptySquare) continue;
2395 /*j = (int) piece - (int) WhitePawn;*/
2396 j = PieceToNumber(piece);
2397 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2398 if(j < 0) continue; /* should not happen */
2399 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2400 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2401 board[holdingsStartRow+j*direction][countsColumn]++;
2407 VariantSwitch (Board board, VariantClass newVariant)
2409 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2410 static Board oldBoard;
2412 startedFromPositionFile = FALSE;
2413 if(gameInfo.variant == newVariant) return;
2415 /* [HGM] This routine is called each time an assignment is made to
2416 * gameInfo.variant during a game, to make sure the board sizes
2417 * are set to match the new variant. If that means adding or deleting
2418 * holdings, we shift the playing board accordingly
2419 * This kludge is needed because in ICS observe mode, we get boards
2420 * of an ongoing game without knowing the variant, and learn about the
2421 * latter only later. This can be because of the move list we requested,
2422 * in which case the game history is refilled from the beginning anyway,
2423 * but also when receiving holdings of a crazyhouse game. In the latter
2424 * case we want to add those holdings to the already received position.
2428 if (appData.debugMode) {
2429 fprintf(debugFP, "Switch board from %s to %s\n",
2430 VariantName(gameInfo.variant), VariantName(newVariant));
2431 setbuf(debugFP, NULL);
2433 shuffleOpenings = 0; /* [HGM] shuffle */
2434 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2438 newWidth = 9; newHeight = 9;
2439 gameInfo.holdingsSize = 7;
2440 case VariantBughouse:
2441 case VariantCrazyhouse:
2442 newHoldingsWidth = 2; break;
2446 newHoldingsWidth = 2;
2447 gameInfo.holdingsSize = 8;
2450 case VariantCapablanca:
2451 case VariantCapaRandom:
2454 newHoldingsWidth = gameInfo.holdingsSize = 0;
2457 if(newWidth != gameInfo.boardWidth ||
2458 newHeight != gameInfo.boardHeight ||
2459 newHoldingsWidth != gameInfo.holdingsWidth ) {
2461 /* shift position to new playing area, if needed */
2462 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2463 for(i=0; i<BOARD_HEIGHT; i++)
2464 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2465 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2467 for(i=0; i<newHeight; i++) {
2468 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2469 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2471 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2472 for(i=0; i<BOARD_HEIGHT; i++)
2473 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2474 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2477 board[HOLDINGS_SET] = 0;
2478 gameInfo.boardWidth = newWidth;
2479 gameInfo.boardHeight = newHeight;
2480 gameInfo.holdingsWidth = newHoldingsWidth;
2481 gameInfo.variant = newVariant;
2482 InitDrawingSizes(-2, 0);
2483 } else gameInfo.variant = newVariant;
2484 CopyBoard(oldBoard, board); // remember correctly formatted board
2485 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2486 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2489 static int loggedOn = FALSE;
2491 /*-- Game start info cache: --*/
2493 char gs_kind[MSG_SIZ];
2494 static char player1Name[128] = "";
2495 static char player2Name[128] = "";
2496 static char cont_seq[] = "\n\\ ";
2497 static int player1Rating = -1;
2498 static int player2Rating = -1;
2499 /*----------------------------*/
2501 ColorClass curColor = ColorNormal;
2502 int suppressKibitz = 0;
2505 Boolean soughtPending = FALSE;
2506 Boolean seekGraphUp;
2507 #define MAX_SEEK_ADS 200
2509 char *seekAdList[MAX_SEEK_ADS];
2510 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2511 float tcList[MAX_SEEK_ADS];
2512 char colorList[MAX_SEEK_ADS];
2513 int nrOfSeekAds = 0;
2514 int minRating = 1010, maxRating = 2800;
2515 int hMargin = 10, vMargin = 20, h, w;
2516 extern int squareSize, lineGap;
2521 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2522 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2523 if(r < minRating+100 && r >=0 ) r = minRating+100;
2524 if(r > maxRating) r = maxRating;
2525 if(tc < 1.f) tc = 1.f;
2526 if(tc > 95.f) tc = 95.f;
2527 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2528 y = ((double)r - minRating)/(maxRating - minRating)
2529 * (h-vMargin-squareSize/8-1) + vMargin;
2530 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2531 if(strstr(seekAdList[i], " u ")) color = 1;
2532 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2533 !strstr(seekAdList[i], "bullet") &&
2534 !strstr(seekAdList[i], "blitz") &&
2535 !strstr(seekAdList[i], "standard") ) color = 2;
2536 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2537 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2541 PlotSingleSeekAd (int i)
2547 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2549 char buf[MSG_SIZ], *ext = "";
2550 VariantClass v = StringToVariant(type);
2551 if(strstr(type, "wild")) {
2552 ext = type + 4; // append wild number
2553 if(v == VariantFischeRandom) type = "chess960"; else
2554 if(v == VariantLoadable) type = "setup"; else
2555 type = VariantName(v);
2557 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2558 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2559 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2560 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2561 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2562 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2563 seekNrList[nrOfSeekAds] = nr;
2564 zList[nrOfSeekAds] = 0;
2565 seekAdList[nrOfSeekAds++] = StrSave(buf);
2566 if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2571 EraseSeekDot (int i)
2573 int x = xList[i], y = yList[i], d=squareSize/4, k;
2574 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2575 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2576 // now replot every dot that overlapped
2577 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2578 int xx = xList[k], yy = yList[k];
2579 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2580 DrawSeekDot(xx, yy, colorList[k]);
2585 RemoveSeekAd (int nr)
2588 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2590 if(seekAdList[i]) free(seekAdList[i]);
2591 seekAdList[i] = seekAdList[--nrOfSeekAds];
2592 seekNrList[i] = seekNrList[nrOfSeekAds];
2593 ratingList[i] = ratingList[nrOfSeekAds];
2594 colorList[i] = colorList[nrOfSeekAds];
2595 tcList[i] = tcList[nrOfSeekAds];
2596 xList[i] = xList[nrOfSeekAds];
2597 yList[i] = yList[nrOfSeekAds];
2598 zList[i] = zList[nrOfSeekAds];
2599 seekAdList[nrOfSeekAds] = NULL;
2605 MatchSoughtLine (char *line)
2607 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2608 int nr, base, inc, u=0; char dummy;
2610 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2611 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2613 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2614 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2615 // match: compact and save the line
2616 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2626 if(!seekGraphUp) return FALSE;
2627 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2628 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2630 DrawSeekBackground(0, 0, w, h);
2631 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2632 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2633 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2634 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2636 DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2639 snprintf(buf, MSG_SIZ, "%d", i);
2640 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2643 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2644 for(i=1; i<100; i+=(i<10?1:5)) {
2645 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2646 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2647 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2649 snprintf(buf, MSG_SIZ, "%d", i);
2650 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2653 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2658 SeekGraphClick (ClickType click, int x, int y, int moving)
2660 static int lastDown = 0, displayed = 0, lastSecond;
2661 if(y < 0) return FALSE;
2662 if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2663 (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2664 if(!seekGraphUp) return FALSE;
2665 seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2666 DrawPosition(TRUE, NULL);
2669 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2670 if(click == Release || moving) return FALSE;
2672 soughtPending = TRUE;
2673 SendToICS(ics_prefix);
2674 SendToICS("sought\n"); // should this be "sought all"?
2675 } else { // issue challenge based on clicked ad
2676 int dist = 10000; int i, closest = 0, second = 0;
2677 for(i=0; i<nrOfSeekAds; i++) {
2678 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2679 if(d < dist) { dist = d; closest = i; }
2680 second += (d - zList[i] < 120); // count in-range ads
2681 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2685 second = (second > 1);
2686 if(displayed != closest || second != lastSecond) {
2687 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2688 lastSecond = second; displayed = closest;
2690 if(click == Press) {
2691 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2694 } // on press 'hit', only show info
2695 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2696 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2697 SendToICS(ics_prefix);
2699 return TRUE; // let incoming board of started game pop down the graph
2700 } else if(click == Release) { // release 'miss' is ignored
2701 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2702 if(moving == 2) { // right up-click
2703 nrOfSeekAds = 0; // refresh graph
2704 soughtPending = TRUE;
2705 SendToICS(ics_prefix);
2706 SendToICS("sought\n"); // should this be "sought all"?
2709 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2710 // press miss or release hit 'pop down' seek graph
2711 seekGraphUp = FALSE;
2712 DrawPosition(TRUE, NULL);
2718 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2720 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2721 #define STARTED_NONE 0
2722 #define STARTED_MOVES 1
2723 #define STARTED_BOARD 2
2724 #define STARTED_OBSERVE 3
2725 #define STARTED_HOLDINGS 4
2726 #define STARTED_CHATTER 5
2727 #define STARTED_COMMENT 6
2728 #define STARTED_MOVES_NOHIDE 7
2730 static int started = STARTED_NONE;
2731 static char parse[20000];
2732 static int parse_pos = 0;
2733 static char buf[BUF_SIZE + 1];
2734 static int firstTime = TRUE, intfSet = FALSE;
2735 static ColorClass prevColor = ColorNormal;
2736 static int savingComment = FALSE;
2737 static int cmatch = 0; // continuation sequence match
2744 int backup; /* [DM] For zippy color lines */
2746 char talker[MSG_SIZ]; // [HGM] chat
2749 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2751 if (appData.debugMode) {
2753 fprintf(debugFP, "<ICS: ");
2754 show_bytes(debugFP, data, count);
2755 fprintf(debugFP, "\n");
2759 if (appData.debugMode) { int f = forwardMostMove;
2760 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2761 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2762 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2765 /* If last read ended with a partial line that we couldn't parse,
2766 prepend it to the new read and try again. */
2767 if (leftover_len > 0) {
2768 for (i=0; i<leftover_len; i++)
2769 buf[i] = buf[leftover_start + i];
2772 /* copy new characters into the buffer */
2773 bp = buf + leftover_len;
2774 buf_len=leftover_len;
2775 for (i=0; i<count; i++)
2778 if (data[i] == '\r')
2781 // join lines split by ICS?
2782 if (!appData.noJoin)
2785 Joining just consists of finding matches against the
2786 continuation sequence, and discarding that sequence
2787 if found instead of copying it. So, until a match
2788 fails, there's nothing to do since it might be the
2789 complete sequence, and thus, something we don't want
2792 if (data[i] == cont_seq[cmatch])
2795 if (cmatch == strlen(cont_seq))
2797 cmatch = 0; // complete match. just reset the counter
2800 it's possible for the ICS to not include the space
2801 at the end of the last word, making our [correct]
2802 join operation fuse two separate words. the server
2803 does this when the space occurs at the width setting.
2805 if (!buf_len || buf[buf_len-1] != ' ')
2816 match failed, so we have to copy what matched before
2817 falling through and copying this character. In reality,
2818 this will only ever be just the newline character, but
2819 it doesn't hurt to be precise.
2821 strncpy(bp, cont_seq, cmatch);
2833 buf[buf_len] = NULLCHAR;
2834 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2839 while (i < buf_len) {
2840 /* Deal with part of the TELNET option negotiation
2841 protocol. We refuse to do anything beyond the
2842 defaults, except that we allow the WILL ECHO option,
2843 which ICS uses to turn off password echoing when we are
2844 directly connected to it. We reject this option
2845 if localLineEditing mode is on (always on in xboard)
2846 and we are talking to port 23, which might be a real
2847 telnet server that will try to keep WILL ECHO on permanently.
2849 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2850 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2851 unsigned char option;
2853 switch ((unsigned char) buf[++i]) {
2855 if (appData.debugMode)
2856 fprintf(debugFP, "\n<WILL ");
2857 switch (option = (unsigned char) buf[++i]) {
2859 if (appData.debugMode)
2860 fprintf(debugFP, "ECHO ");
2861 /* Reply only if this is a change, according
2862 to the protocol rules. */
2863 if (remoteEchoOption) break;
2864 if (appData.localLineEditing &&
2865 atoi(appData.icsPort) == TN_PORT) {
2866 TelnetRequest(TN_DONT, TN_ECHO);
2869 TelnetRequest(TN_DO, TN_ECHO);
2870 remoteEchoOption = TRUE;
2874 if (appData.debugMode)
2875 fprintf(debugFP, "%d ", option);
2876 /* Whatever this is, we don't want it. */
2877 TelnetRequest(TN_DONT, option);
2882 if (appData.debugMode)
2883 fprintf(debugFP, "\n<WONT ");
2884 switch (option = (unsigned char) buf[++i]) {
2886 if (appData.debugMode)
2887 fprintf(debugFP, "ECHO ");
2888 /* Reply only if this is a change, according
2889 to the protocol rules. */
2890 if (!remoteEchoOption) break;
2892 TelnetRequest(TN_DONT, TN_ECHO);
2893 remoteEchoOption = FALSE;
2896 if (appData.debugMode)
2897 fprintf(debugFP, "%d ", (unsigned char) option);
2898 /* Whatever this is, it must already be turned
2899 off, because we never agree to turn on
2900 anything non-default, so according to the
2901 protocol rules, we don't reply. */
2906 if (appData.debugMode)
2907 fprintf(debugFP, "\n<DO ");
2908 switch (option = (unsigned char) buf[++i]) {
2910 /* Whatever this is, we refuse to do it. */
2911 if (appData.debugMode)
2912 fprintf(debugFP, "%d ", option);
2913 TelnetRequest(TN_WONT, option);
2918 if (appData.debugMode)
2919 fprintf(debugFP, "\n<DONT ");
2920 switch (option = (unsigned char) buf[++i]) {
2922 if (appData.debugMode)
2923 fprintf(debugFP, "%d ", option);
2924 /* Whatever this is, we are already not doing
2925 it, because we never agree to do anything
2926 non-default, so according to the protocol
2927 rules, we don't reply. */
2932 if (appData.debugMode)
2933 fprintf(debugFP, "\n<IAC ");
2934 /* Doubled IAC; pass it through */
2938 if (appData.debugMode)
2939 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2940 /* Drop all other telnet commands on the floor */
2943 if (oldi > next_out)
2944 SendToPlayer(&buf[next_out], oldi - next_out);
2950 /* OK, this at least will *usually* work */
2951 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2955 if (loggedOn && !intfSet) {
2956 if (ics_type == ICS_ICC) {
2957 snprintf(str, MSG_SIZ,
2958 "/set-quietly interface %s\n/set-quietly style 12\n",
2960 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2961 strcat(str, "/set-2 51 1\n/set seek 1\n");
2962 } else if (ics_type == ICS_CHESSNET) {
2963 snprintf(str, MSG_SIZ, "/style 12\n");
2965 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2966 strcat(str, programVersion);
2967 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2968 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2969 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2971 strcat(str, "$iset nohighlight 1\n");
2973 strcat(str, "$iset lock 1\n$style 12\n");
2976 NotifyFrontendLogin();
2980 if (started == STARTED_COMMENT) {
2981 /* Accumulate characters in comment */
2982 parse[parse_pos++] = buf[i];
2983 if (buf[i] == '\n') {
2984 parse[parse_pos] = NULLCHAR;
2985 if(chattingPartner>=0) {
2987 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2988 OutputChatMessage(chattingPartner, mess);
2989 chattingPartner = -1;
2990 next_out = i+1; // [HGM] suppress printing in ICS window
2992 if(!suppressKibitz) // [HGM] kibitz
2993 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2994 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2995 int nrDigit = 0, nrAlph = 0, j;
2996 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2997 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2998 parse[parse_pos] = NULLCHAR;
2999 // try to be smart: if it does not look like search info, it should go to
3000 // ICS interaction window after all, not to engine-output window.
3001 for(j=0; j<parse_pos; j++) { // count letters and digits
3002 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3003 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
3004 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
3006 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3007 int depth=0; float score;
3008 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3009 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3010 pvInfoList[forwardMostMove-1].depth = depth;
3011 pvInfoList[forwardMostMove-1].score = 100*score;
3013 OutputKibitz(suppressKibitz, parse);
3016 if(gameMode == IcsObserving) // restore original ICS messages
3017 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3019 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3020 SendToPlayer(tmp, strlen(tmp));
3022 next_out = i+1; // [HGM] suppress printing in ICS window
3024 started = STARTED_NONE;
3026 /* Don't match patterns against characters in comment */
3031 if (started == STARTED_CHATTER) {
3032 if (buf[i] != '\n') {
3033 /* Don't match patterns against characters in chatter */
3037 started = STARTED_NONE;
3038 if(suppressKibitz) next_out = i+1;
3041 /* Kludge to deal with rcmd protocol */
3042 if (firstTime && looking_at(buf, &i, "\001*")) {
3043 DisplayFatalError(&buf[1], 0, 1);
3049 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3052 if (appData.debugMode)
3053 fprintf(debugFP, "ics_type %d\n", ics_type);
3056 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3057 ics_type = ICS_FICS;
3059 if (appData.debugMode)
3060 fprintf(debugFP, "ics_type %d\n", ics_type);
3063 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3064 ics_type = ICS_CHESSNET;
3066 if (appData.debugMode)
3067 fprintf(debugFP, "ics_type %d\n", ics_type);
3072 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3073 looking_at(buf, &i, "Logging you in as \"*\"") ||
3074 looking_at(buf, &i, "will be \"*\""))) {
3075 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3079 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3081 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3082 DisplayIcsInteractionTitle(buf);
3083 have_set_title = TRUE;
3086 /* skip finger notes */
3087 if (started == STARTED_NONE &&
3088 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3089 (buf[i] == '1' && buf[i+1] == '0')) &&
3090 buf[i+2] == ':' && buf[i+3] == ' ') {
3091 started = STARTED_CHATTER;
3097 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3098 if(appData.seekGraph) {
3099 if(soughtPending && MatchSoughtLine(buf+i)) {
3100 i = strstr(buf+i, "rated") - buf;
3101 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3102 next_out = leftover_start = i;
3103 started = STARTED_CHATTER;
3104 suppressKibitz = TRUE;
3107 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3108 && looking_at(buf, &i, "* ads displayed")) {
3109 soughtPending = FALSE;
3114 if(appData.autoRefresh) {
3115 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3116 int s = (ics_type == ICS_ICC); // ICC format differs
3118 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3119 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3120 looking_at(buf, &i, "*% "); // eat prompt
3121 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3122 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3123 next_out = i; // suppress
3126 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3127 char *p = star_match[0];
3129 if(seekGraphUp) RemoveSeekAd(atoi(p));
3130 while(*p && *p++ != ' '); // next
3132 looking_at(buf, &i, "*% "); // eat prompt
3133 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3140 /* skip formula vars */
3141 if (started == STARTED_NONE &&
3142 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3143 started = STARTED_CHATTER;
3148 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3149 if (appData.autoKibitz && started == STARTED_NONE &&
3150 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3151 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3152 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3153 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3154 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3155 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3156 suppressKibitz = TRUE;
3157 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3159 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3160 && (gameMode == IcsPlayingWhite)) ||
3161 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3162 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3163 started = STARTED_CHATTER; // own kibitz we simply discard
3165 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3166 parse_pos = 0; parse[0] = NULLCHAR;
3167 savingComment = TRUE;
3168 suppressKibitz = gameMode != IcsObserving ? 2 :
3169 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3173 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3174 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3175 && atoi(star_match[0])) {
3176 // suppress the acknowledgements of our own autoKibitz
3178 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3179 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3180 SendToPlayer(star_match[0], strlen(star_match[0]));
3181 if(looking_at(buf, &i, "*% ")) // eat prompt
3182 suppressKibitz = FALSE;
3186 } // [HGM] kibitz: end of patch
3188 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3190 // [HGM] chat: intercept tells by users for which we have an open chat window
3192 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3193 looking_at(buf, &i, "* whispers:") ||
3194 looking_at(buf, &i, "* kibitzes:") ||
3195 looking_at(buf, &i, "* shouts:") ||
3196 looking_at(buf, &i, "* c-shouts:") ||
3197 looking_at(buf, &i, "--> * ") ||
3198 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3199 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3200 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3201 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3203 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3204 chattingPartner = -1;
3206 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3207 for(p=0; p<MAX_CHAT; p++) {
3208 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3209 talker[0] = '['; strcat(talker, "] ");
3210 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
3211 chattingPartner = p; break;
3214 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3215 for(p=0; p<MAX_CHAT; p++) {
3216 if(!strcmp("kibitzes", chatPartner[p])) {
3217 talker[0] = '['; strcat(talker, "] ");
3218 chattingPartner = p; break;
3221 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3222 for(p=0; p<MAX_CHAT; p++) {
3223 if(!strcmp("whispers", chatPartner[p])) {
3224 talker[0] = '['; strcat(talker, "] ");
3225 chattingPartner = p; break;
3228 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3229 if(buf[i-8] == '-' && buf[i-3] == 't')
3230 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3231 if(!strcmp("c-shouts", chatPartner[p])) {
3232 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3233 chattingPartner = p; break;
3236 if(chattingPartner < 0)
3237 for(p=0; p<MAX_CHAT; p++) {
3238 if(!strcmp("shouts", chatPartner[p])) {
3239 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3240 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3241 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3242 chattingPartner = p; break;
3246 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3247 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3248 talker[0] = 0; Colorize(ColorTell, FALSE);
3249 chattingPartner = p; break;
3251 if(chattingPartner<0) i = oldi; else {
3252 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3253 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3254 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3255 started = STARTED_COMMENT;
3256 parse_pos = 0; parse[0] = NULLCHAR;
3257 savingComment = 3 + chattingPartner; // counts as TRUE
3258 suppressKibitz = TRUE;
3261 } // [HGM] chat: end of patch
3264 if (appData.zippyTalk || appData.zippyPlay) {
3265 /* [DM] Backup address for color zippy lines */
3267 if (loggedOn == TRUE)
3268 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3269 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3271 } // [DM] 'else { ' deleted
3273 /* Regular tells and says */
3274 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3275 looking_at(buf, &i, "* (your partner) tells you: ") ||
3276 looking_at(buf, &i, "* says: ") ||
3277 /* Don't color "message" or "messages" output */
3278 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3279 looking_at(buf, &i, "*. * at *:*: ") ||
3280 looking_at(buf, &i, "--* (*:*): ") ||
3281 /* Message notifications (same color as tells) */
3282 looking_at(buf, &i, "* has left a message ") ||
3283 looking_at(buf, &i, "* just sent you a message:\n") ||
3284 /* Whispers and kibitzes */
3285 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3286 looking_at(buf, &i, "* kibitzes: ") ||
3288 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3290 if (tkind == 1 && strchr(star_match[0], ':')) {
3291 /* Avoid "tells you:" spoofs in channels */
3294 if (star_match[0][0] == NULLCHAR ||
3295 strchr(star_match[0], ' ') ||
3296 (tkind == 3 && strchr(star_match[1], ' '))) {
3297 /* Reject bogus matches */
3300 if (appData.colorize) {
3301 if (oldi > next_out) {
3302 SendToPlayer(&buf[next_out], oldi - next_out);
3307 Colorize(ColorTell, FALSE);
3308 curColor = ColorTell;
3311 Colorize(ColorKibitz, FALSE);
3312 curColor = ColorKibitz;
3315 p = strrchr(star_match[1], '(');
3322 Colorize(ColorChannel1, FALSE);
3323 curColor = ColorChannel1;
3325 Colorize(ColorChannel, FALSE);
3326 curColor = ColorChannel;
3330 curColor = ColorNormal;
3334 if (started == STARTED_NONE && appData.autoComment &&
3335 (gameMode == IcsObserving ||
3336 gameMode == IcsPlayingWhite ||
3337 gameMode == IcsPlayingBlack)) {
3338 parse_pos = i - oldi;
3339 memcpy(parse, &buf[oldi], parse_pos);
3340 parse[parse_pos] = NULLCHAR;
3341 started = STARTED_COMMENT;
3342 savingComment = TRUE;
3344 started = STARTED_CHATTER;
3345 savingComment = FALSE;
3352 if (looking_at(buf, &i, "* s-shouts: ") ||
3353 looking_at(buf, &i, "* c-shouts: ")) {
3354 if (appData.colorize) {
3355 if (oldi > next_out) {
3356 SendToPlayer(&buf[next_out], oldi - next_out);
3359 Colorize(ColorSShout, FALSE);
3360 curColor = ColorSShout;
3363 started = STARTED_CHATTER;
3367 if (looking_at(buf, &i, "--->")) {
3372 if (looking_at(buf, &i, "* shouts: ") ||
3373 looking_at(buf, &i, "--> ")) {
3374 if (appData.colorize) {
3375 if (oldi > next_out) {
3376 SendToPlayer(&buf[next_out], oldi - next_out);
3379 Colorize(ColorShout, FALSE);
3380 curColor = ColorShout;
3383 started = STARTED_CHATTER;
3387 if (looking_at( buf, &i, "Challenge:")) {
3388 if (appData.colorize) {
3389 if (oldi > next_out) {
3390 SendToPlayer(&buf[next_out], oldi - next_out);
3393 Colorize(ColorChallenge, FALSE);
3394 curColor = ColorChallenge;
3400 if (looking_at(buf, &i, "* offers you") ||
3401 looking_at(buf, &i, "* offers to be") ||
3402 looking_at(buf, &i, "* would like to") ||
3403 looking_at(buf, &i, "* requests to") ||
3404 looking_at(buf, &i, "Your opponent offers") ||
3405 looking_at(buf, &i, "Your opponent requests")) {
3407 if (appData.colorize) {
3408 if (oldi > next_out) {
3409 SendToPlayer(&buf[next_out], oldi - next_out);
3412 Colorize(ColorRequest, FALSE);
3413 curColor = ColorRequest;
3418 if (looking_at(buf, &i, "* (*) seeking")) {
3419 if (appData.colorize) {
3420 if (oldi > next_out) {
3421 SendToPlayer(&buf[next_out], oldi - next_out);
3424 Colorize(ColorSeek, FALSE);
3425 curColor = ColorSeek;
3430 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3432 if (looking_at(buf, &i, "\\ ")) {
3433 if (prevColor != ColorNormal) {
3434 if (oldi > next_out) {
3435 SendToPlayer(&buf[next_out], oldi - next_out);
3438 Colorize(prevColor, TRUE);
3439 curColor = prevColor;
3441 if (savingComment) {
3442 parse_pos = i - oldi;
3443 memcpy(parse, &buf[oldi], parse_pos);
3444 parse[parse_pos] = NULLCHAR;
3445 started = STARTED_COMMENT;
3446 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3447 chattingPartner = savingComment - 3; // kludge to remember the box
3449 started = STARTED_CHATTER;
3454 if (looking_at(buf, &i, "Black Strength :") ||
3455 looking_at(buf, &i, "<<< style 10 board >>>") ||
3456 looking_at(buf, &i, "<10>") ||
3457 looking_at(buf, &i, "#@#")) {
3458 /* Wrong board style */
3460 SendToICS(ics_prefix);
3461 SendToICS("set style 12\n");
3462 SendToICS(ics_prefix);
3463 SendToICS("refresh\n");
3467 if (looking_at(buf, &i, "login:")) {
3468 if (!have_sent_ICS_logon) {
3470 have_sent_ICS_logon = 1;
3471 else // no init script was found
3472 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3473 } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3474 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3479 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3480 (looking_at(buf, &i, "\n<12> ") ||
3481 looking_at(buf, &i, "<12> "))) {
3483 if (oldi > next_out) {
3484 SendToPlayer(&buf[next_out], oldi - next_out);
3487 started = STARTED_BOARD;
3492 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3493 looking_at(buf, &i, "<b1> ")) {
3494 if (oldi > next_out) {
3495 SendToPlayer(&buf[next_out], oldi - next_out);
3498 started = STARTED_HOLDINGS;
3503 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3505 /* Header for a move list -- first line */
3507 switch (ics_getting_history) {
3511 case BeginningOfGame:
3512 /* User typed "moves" or "oldmoves" while we
3513 were idle. Pretend we asked for these
3514 moves and soak them up so user can step
3515 through them and/or save them.
3518 gameMode = IcsObserving;
3521 ics_getting_history = H_GOT_UNREQ_HEADER;
3523 case EditGame: /*?*/
3524 case EditPosition: /*?*/
3525 /* Should above feature work in these modes too? */
3526 /* For now it doesn't */
3527 ics_getting_history = H_GOT_UNWANTED_HEADER;
3530 ics_getting_history = H_GOT_UNWANTED_HEADER;
3535 /* Is this the right one? */
3536 if (gameInfo.white && gameInfo.black &&
3537 strcmp(gameInfo.white, star_match[0]) == 0 &&
3538 strcmp(gameInfo.black, star_match[2]) == 0) {
3540 ics_getting_history = H_GOT_REQ_HEADER;
3543 case H_GOT_REQ_HEADER:
3544 case H_GOT_UNREQ_HEADER:
3545 case H_GOT_UNWANTED_HEADER:
3546 case H_GETTING_MOVES:
3547 /* Should not happen */
3548 DisplayError(_("Error gathering move list: two headers"), 0);
3549 ics_getting_history = H_FALSE;
3553 /* Save player ratings into gameInfo if needed */
3554 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3555 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3556 (gameInfo.whiteRating == -1 ||
3557 gameInfo.blackRating == -1)) {
3559 gameInfo.whiteRating = string_to_rating(star_match[1]);
3560 gameInfo.blackRating = string_to_rating(star_match[3]);
3561 if (appData.debugMode)
3562 fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3563 gameInfo.whiteRating, gameInfo.blackRating);
3568 if (looking_at(buf, &i,
3569 "* * match, initial time: * minute*, increment: * second")) {
3570 /* Header for a move list -- second line */
3571 /* Initial board will follow if this is a wild game */
3572 if (gameInfo.event != NULL) free(gameInfo.event);
3573 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3574 gameInfo.event = StrSave(str);
3575 /* [HGM] we switched variant. Translate boards if needed. */
3576 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3580 if (looking_at(buf, &i, "Move ")) {
3581 /* Beginning of a move list */
3582 switch (ics_getting_history) {
3584 /* Normally should not happen */
3585 /* Maybe user hit reset while we were parsing */
3588 /* Happens if we are ignoring a move list that is not
3589 * the one we just requested. Common if the user
3590 * tries to observe two games without turning off
3593 case H_GETTING_MOVES:
3594 /* Should not happen */
3595 DisplayError(_("Error gathering move list: nested"), 0);
3596 ics_getting_history = H_FALSE;
3598 case H_GOT_REQ_HEADER:
3599 ics_getting_history = H_GETTING_MOVES;
3600 started = STARTED_MOVES;
3602 if (oldi > next_out) {
3603 SendToPlayer(&buf[next_out], oldi - next_out);
3606 case H_GOT_UNREQ_HEADER:
3607 ics_getting_history = H_GETTING_MOVES;
3608 started = STARTED_MOVES_NOHIDE;
3611 case H_GOT_UNWANTED_HEADER:
3612 ics_getting_history = H_FALSE;
3618 if (looking_at(buf, &i, "% ") ||
3619 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3620 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3621 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3622 soughtPending = FALSE;
3626 if(suppressKibitz) next_out = i;
3627 savingComment = FALSE;
3631 case STARTED_MOVES_NOHIDE:
3632 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3633 parse[parse_pos + i - oldi] = NULLCHAR;
3634 ParseGameHistory(parse);
3636 if (appData.zippyPlay && first.initDone) {
3637 FeedMovesToProgram(&first, forwardMostMove);
3638 if (gameMode == IcsPlayingWhite) {
3639 if (WhiteOnMove(forwardMostMove)) {
3640 if (first.sendTime) {
3641 if (first.useColors) {
3642 SendToProgram("black\n", &first);
3644 SendTimeRemaining(&first, TRUE);
3646 if (first.useColors) {
3647 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3649 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3650 first.maybeThinking = TRUE;
3652 if (first.usePlayother) {
3653 if (first.sendTime) {
3654 SendTimeRemaining(&first, TRUE);
3656 SendToProgram("playother\n", &first);
3662 } else if (gameMode == IcsPlayingBlack) {
3663 if (!WhiteOnMove(forwardMostMove)) {
3664 if (first.sendTime) {
3665 if (first.useColors) {
3666 SendToProgram("white\n", &first);
3668 SendTimeRemaining(&first, FALSE);
3670 if (first.useColors) {
3671 SendToProgram("black\n", &first);
3673 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3674 first.maybeThinking = TRUE;
3676 if (first.usePlayother) {
3677 if (first.sendTime) {
3678 SendTimeRemaining(&first, FALSE);
3680 SendToProgram("playother\n", &first);
3689 if (gameMode == IcsObserving && ics_gamenum == -1) {
3690 /* Moves came from oldmoves or moves command
3691 while we weren't doing anything else.
3693 currentMove = forwardMostMove;
3694 ClearHighlights();/*!!could figure this out*/
3695 flipView = appData.flipView;
3696 DrawPosition(TRUE, boards[currentMove]);
3697 DisplayBothClocks();
3698 snprintf(str, MSG_SIZ, "%s %s %s",
3699 gameInfo.white, _("vs."), gameInfo.black);
3703 /* Moves were history of an active game */
3704 if (gameInfo.resultDetails != NULL) {
3705 free(gameInfo.resultDetails);
3706 gameInfo.resultDetails = NULL;
3709 HistorySet(parseList, backwardMostMove,
3710 forwardMostMove, currentMove-1);
3711 DisplayMove(currentMove - 1);
3712 if (started == STARTED_MOVES) next_out = i;
3713 started = STARTED_NONE;
3714 ics_getting_history = H_FALSE;
3717 case STARTED_OBSERVE:
3718 started = STARTED_NONE;
3719 SendToICS(ics_prefix);
3720 SendToICS("refresh\n");
3726 if(bookHit) { // [HGM] book: simulate book reply
3727 static char bookMove[MSG_SIZ]; // a bit generous?
3729 programStats.nodes = programStats.depth = programStats.time =
3730 programStats.score = programStats.got_only_move = 0;
3731 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3733 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3734 strcat(bookMove, bookHit);
3735 HandleMachineMove(bookMove, &first);
3740 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3741 started == STARTED_HOLDINGS ||
3742 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3743 /* Accumulate characters in move list or board */
3744 parse[parse_pos++] = buf[i];
3747 /* Start of game messages. Mostly we detect start of game
3748 when the first board image arrives. On some versions
3749 of the ICS, though, we need to do a "refresh" after starting
3750 to observe in order to get the current board right away. */
3751 if (looking_at(buf, &i, "Adding game * to observation list")) {
3752 started = STARTED_OBSERVE;
3756 /* Handle auto-observe */
3757 if (appData.autoObserve &&
3758 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3759 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3761 /* Choose the player that was highlighted, if any. */
3762 if (star_match[0][0] == '\033' ||
3763 star_match[1][0] != '\033') {
3764 player = star_match[0];
3766 player = star_match[2];
3768 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3769 ics_prefix, StripHighlightAndTitle(player));
3772 /* Save ratings from notify string */
3773 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3774 player1Rating = string_to_rating(star_match[1]);
3775 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3776 player2Rating = string_to_rating(star_match[3]);
3778 if (appData.debugMode)
3780 "Ratings from 'Game notification:' %s %d, %s %d\n",
3781 player1Name, player1Rating,
3782 player2Name, player2Rating);
3787 /* Deal with automatic examine mode after a game,
3788 and with IcsObserving -> IcsExamining transition */
3789 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3790 looking_at(buf, &i, "has made you an examiner of game *")) {
3792 int gamenum = atoi(star_match[0]);
3793 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3794 gamenum == ics_gamenum) {
3795 /* We were already playing or observing this game;
3796 no need to refetch history */
3797 gameMode = IcsExamining;
3799 pauseExamForwardMostMove = forwardMostMove;
3800 } else if (currentMove < forwardMostMove) {
3801 ForwardInner(forwardMostMove);
3804 /* I don't think this case really can happen */
3805 SendToICS(ics_prefix);
3806 SendToICS("refresh\n");
3811 /* Error messages */
3812 // if (ics_user_moved) {
3813 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3814 if (looking_at(buf, &i, "Illegal move") ||
3815 looking_at(buf, &i, "Not a legal move") ||
3816 looking_at(buf, &i, "Your king is in check") ||
3817 looking_at(buf, &i, "It isn't your turn") ||
3818 looking_at(buf, &i, "It is not your move")) {
3820 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3821 currentMove = forwardMostMove-1;
3822 DisplayMove(currentMove - 1); /* before DMError */
3823 DrawPosition(FALSE, boards[currentMove]);
3824 SwitchClocks(forwardMostMove-1); // [HGM] race
3825 DisplayBothClocks();
3827 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3833 if (looking_at(buf, &i, "still have time") ||
3834 looking_at(buf, &i, "not out of time") ||
3835 looking_at(buf, &i, "either player is out of time") ||
3836 looking_at(buf, &i, "has timeseal; checking")) {
3837 /* We must have called his flag a little too soon */
3838 whiteFlag = blackFlag = FALSE;
3842 if (looking_at(buf, &i, "added * seconds to") ||
3843 looking_at(buf, &i, "seconds were added to")) {
3844 /* Update the clocks */
3845 SendToICS(ics_prefix);
3846 SendToICS("refresh\n");
3850 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3851 ics_clock_paused = TRUE;
3856 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3857 ics_clock_paused = FALSE;
3862 /* Grab player ratings from the Creating: message.
3863 Note we have to check for the special case when
3864 the ICS inserts things like [white] or [black]. */
3865 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3866 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3868 0 player 1 name (not necessarily white)
3870 2 empty, white, or black (IGNORED)
3871 3 player 2 name (not necessarily black)
3874 The names/ratings are sorted out when the game
3875 actually starts (below).
3877 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3878 player1Rating = string_to_rating(star_match[1]);
3879 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3880 player2Rating = string_to_rating(star_match[4]);
3882 if (appData.debugMode)
3884 "Ratings from 'Creating:' %s %d, %s %d\n",
3885 player1Name, player1Rating,
3886 player2Name, player2Rating);
3891 /* Improved generic start/end-of-game messages */
3892 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3893 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3894 /* If tkind == 0: */
3895 /* star_match[0] is the game number */
3896 /* [1] is the white player's name */
3897 /* [2] is the black player's name */
3898 /* For end-of-game: */
3899 /* [3] is the reason for the game end */
3900 /* [4] is a PGN end game-token, preceded by " " */
3901 /* For start-of-game: */
3902 /* [3] begins with "Creating" or "Continuing" */
3903 /* [4] is " *" or empty (don't care). */
3904 int gamenum = atoi(star_match[0]);
3905 char *whitename, *blackname, *why, *endtoken;
3906 ChessMove endtype = EndOfFile;
3909 whitename = star_match[1];
3910 blackname = star_match[2];
3911 why = star_match[3];
3912 endtoken = star_match[4];
3914 whitename = star_match[1];
3915 blackname = star_match[3];
3916 why = star_match[5];
3917 endtoken = star_match[6];
3920 /* Game start messages */
3921 if (strncmp(why, "Creating ", 9) == 0 ||
3922 strncmp(why, "Continuing ", 11) == 0) {
3923 gs_gamenum = gamenum;
3924 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3925 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
3926 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3928 if (appData.zippyPlay) {
3929 ZippyGameStart(whitename, blackname);
3932 partnerBoardValid = FALSE; // [HGM] bughouse
3936 /* Game end messages */
3937 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3938 ics_gamenum != gamenum) {
3941 while (endtoken[0] == ' ') endtoken++;
3942 switch (endtoken[0]) {
3945 endtype = GameUnfinished;
3948 endtype = BlackWins;
3951 if (endtoken[1] == '/')
3952 endtype = GameIsDrawn;
3954 endtype = WhiteWins;
3957 GameEnds(endtype, why, GE_ICS);
3959 if (appData.zippyPlay && first.initDone) {
3960 ZippyGameEnd(endtype, why);
3961 if (first.pr == NoProc) {
3962 /* Start the next process early so that we'll
3963 be ready for the next challenge */
3964 StartChessProgram(&first);
3966 /* Send "new" early, in case this command takes
3967 a long time to finish, so that we'll be ready
3968 for the next challenge. */
3969 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3973 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3977 if (looking_at(buf, &i, "Removing game * from observation") ||
3978 looking_at(buf, &i, "no longer observing game *") ||
3979 looking_at(buf, &i, "Game * (*) has no examiners")) {
3980 if (gameMode == IcsObserving &&
3981 atoi(star_match[0]) == ics_gamenum)
3983 /* icsEngineAnalyze */
3984 if (appData.icsEngineAnalyze) {
3991 ics_user_moved = FALSE;
3996 if (looking_at(buf, &i, "no longer examining game *")) {
3997 if (gameMode == IcsExamining &&
3998 atoi(star_match[0]) == ics_gamenum)
4002 ics_user_moved = FALSE;
4007 /* Advance leftover_start past any newlines we find,
4008 so only partial lines can get reparsed */
4009 if (looking_at(buf, &i, "\n")) {
4010 prevColor = curColor;
4011 if (curColor != ColorNormal) {
4012 if (oldi > next_out) {
4013 SendToPlayer(&buf[next_out], oldi - next_out);
4016 Colorize(ColorNormal, FALSE);
4017 curColor = ColorNormal;
4019 if (started == STARTED_BOARD) {
4020 started = STARTED_NONE;
4021 parse[parse_pos] = NULLCHAR;
4022 ParseBoard12(parse);
4025 /* Send premove here */
4026 if (appData.premove) {
4028 if (currentMove == 0 &&
4029 gameMode == IcsPlayingWhite &&
4030 appData.premoveWhite) {
4031 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4032 if (appData.debugMode)
4033 fprintf(debugFP, "Sending premove:\n");
4035 } else if (currentMove == 1 &&
4036 gameMode == IcsPlayingBlack &&
4037 appData.premoveBlack) {
4038 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4039 if (appData.debugMode)
4040 fprintf(debugFP, "Sending premove:\n");
4042 } else if (gotPremove) {
4044 ClearPremoveHighlights();
4045 if (appData.debugMode)
4046 fprintf(debugFP, "Sending premove:\n");
4047 UserMoveEvent(premoveFromX, premoveFromY,
4048 premoveToX, premoveToY,
4053 /* Usually suppress following prompt */
4054 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4055 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4056 if (looking_at(buf, &i, "*% ")) {
4057 savingComment = FALSE;
4062 } else if (started == STARTED_HOLDINGS) {
4064 char new_piece[MSG_SIZ];
4065 started = STARTED_NONE;
4066 parse[parse_pos] = NULLCHAR;
4067 if (appData.debugMode)
4068 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4069 parse, currentMove);
4070 if (sscanf(parse, " game %d", &gamenum) == 1) {
4071 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4072 if (gameInfo.variant == VariantNormal) {
4073 /* [HGM] We seem to switch variant during a game!
4074 * Presumably no holdings were displayed, so we have
4075 * to move the position two files to the right to
4076 * create room for them!
4078 VariantClass newVariant;
4079 switch(gameInfo.boardWidth) { // base guess on board width
4080 case 9: newVariant = VariantShogi; break;
4081 case 10: newVariant = VariantGreat; break;
4082 default: newVariant = VariantCrazyhouse; break;
4084 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4085 /* Get a move list just to see the header, which
4086 will tell us whether this is really bug or zh */
4087 if (ics_getting_history == H_FALSE) {
4088 ics_getting_history = H_REQUESTED;
4089 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4093 new_piece[0] = NULLCHAR;
4094 sscanf(parse, "game %d white [%s black [%s <- %s",
4095 &gamenum, white_holding, black_holding,
4097 white_holding[strlen(white_holding)-1] = NULLCHAR;
4098 black_holding[strlen(black_holding)-1] = NULLCHAR;
4099 /* [HGM] copy holdings to board holdings area */
4100 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4101 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4102 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4104 if (appData.zippyPlay && first.initDone) {
4105 ZippyHoldings(white_holding, black_holding,
4109 if (tinyLayout || smallLayout) {
4110 char wh[16], bh[16];
4111 PackHolding(wh, white_holding);
4112 PackHolding(bh, black_holding);
4113 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4114 gameInfo.white, gameInfo.black);
4116 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4117 gameInfo.white, white_holding, _("vs."),
4118 gameInfo.black, black_holding);
4120 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4121 DrawPosition(FALSE, boards[currentMove]);
4123 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4124 sscanf(parse, "game %d white [%s black [%s <- %s",
4125 &gamenum, white_holding, black_holding,
4127 white_holding[strlen(white_holding)-1] = NULLCHAR;
4128 black_holding[strlen(black_holding)-1] = NULLCHAR;
4129 /* [HGM] copy holdings to partner-board holdings area */
4130 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4131 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4132 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4133 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4134 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4137 /* Suppress following prompt */
4138 if (looking_at(buf, &i, "*% ")) {
4139 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4140 savingComment = FALSE;
4148 i++; /* skip unparsed character and loop back */
4151 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4152 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4153 // SendToPlayer(&buf[next_out], i - next_out);
4154 started != STARTED_HOLDINGS && leftover_start > next_out) {
4155 SendToPlayer(&buf[next_out], leftover_start - next_out);
4159 leftover_len = buf_len - leftover_start;
4160 /* if buffer ends with something we couldn't parse,
4161 reparse it after appending the next read */
4163 } else if (count == 0) {
4164 RemoveInputSource(isr);
4165 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4167 DisplayFatalError(_("Error reading from ICS"), error, 1);
4172 /* Board style 12 looks like this:
4174 <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
4176 * The "<12> " is stripped before it gets to this routine. The two
4177 * trailing 0's (flip state and clock ticking) are later addition, and
4178 * some chess servers may not have them, or may have only the first.
4179 * Additional trailing fields may be added in the future.
4182 #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"
4184 #define RELATION_OBSERVING_PLAYED 0
4185 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4186 #define RELATION_PLAYING_MYMOVE 1
4187 #define RELATION_PLAYING_NOTMYMOVE -1
4188 #define RELATION_EXAMINING 2
4189 #define RELATION_ISOLATED_BOARD -3
4190 #define RELATION_STARTING_POSITION -4 /* FICS only */
4193 ParseBoard12 (char *string)
4197 char *bookHit = NULL; // [HGM] book
4199 GameMode newGameMode;
4200 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4201 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4202 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4203 char to_play, board_chars[200];
4204 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4205 char black[32], white[32];
4207 int prevMove = currentMove;
4210 int fromX, fromY, toX, toY;
4212 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4213 Boolean weird = FALSE, reqFlag = FALSE;
4215 fromX = fromY = toX = toY = -1;
4219 if (appData.debugMode)
4220 fprintf(debugFP, "Parsing board: %s\n", string);
4222 move_str[0] = NULLCHAR;
4223 elapsed_time[0] = NULLCHAR;
4224 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4226 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4227 if(string[i] == ' ') { ranks++; files = 0; }
4229 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4232 for(j = 0; j <i; j++) board_chars[j] = string[j];
4233 board_chars[i] = '\0';
4236 n = sscanf(string, PATTERN, &to_play, &double_push,
4237 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4238 &gamenum, white, black, &relation, &basetime, &increment,
4239 &white_stren, &black_stren, &white_time, &black_time,
4240 &moveNum, str, elapsed_time, move_str, &ics_flip,
4244 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4245 DisplayError(str, 0);
4249 /* Convert the move number to internal form */
4250 moveNum = (moveNum - 1) * 2;
4251 if (to_play == 'B') moveNum++;
4252 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4253 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4259 case RELATION_OBSERVING_PLAYED:
4260 case RELATION_OBSERVING_STATIC:
4261 if (gamenum == -1) {
4262 /* Old ICC buglet */
4263 relation = RELATION_OBSERVING_STATIC;
4265 newGameMode = IcsObserving;
4267 case RELATION_PLAYING_MYMOVE:
4268 case RELATION_PLAYING_NOTMYMOVE:
4270 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4271 IcsPlayingWhite : IcsPlayingBlack;
4272 soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4274 case RELATION_EXAMINING:
4275 newGameMode = IcsExamining;
4277 case RELATION_ISOLATED_BOARD:
4279 /* Just display this board. If user was doing something else,
4280 we will forget about it until the next board comes. */
4281 newGameMode = IcsIdle;
4283 case RELATION_STARTING_POSITION:
4284 newGameMode = gameMode;
4288 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4289 gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4290 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4291 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4292 int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4293 static int lastBgGame = -1;
4295 for (k = 0; k < ranks; k++) {
4296 for (j = 0; j < files; j++)
4297 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4298 if(gameInfo.holdingsWidth > 1) {
4299 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4300 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4303 CopyBoard(partnerBoard, board);
4304 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4305 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4306 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4307 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4308 if(toSqr = strchr(str, '-')) {
4309 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4310 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4311 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4312 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4313 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4314 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4316 DisplayWhiteClock(white_time*fac, to_play == 'W');
4317 DisplayBlackClock(black_time*fac, to_play != 'W');
4318 activePartner = to_play;
4319 if(gamenum != lastBgGame) {
4321 snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4324 lastBgGame = gamenum;
4325 activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4326 partnerUp = 0; flipView = !flipView; } // [HGM] dual
4327 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4328 (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4329 if(!twoBoards) DisplayMessage(partnerStatus, "");
4330 partnerBoardValid = TRUE;
4334 if(appData.dualBoard && appData.bgObserve) {
4335 if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4336 SendToICS(ics_prefix), SendToICS("pobserve\n");
4337 else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4339 snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4344 /* Modify behavior for initial board display on move listing
4347 switch (ics_getting_history) {
4351 case H_GOT_REQ_HEADER:
4352 case H_GOT_UNREQ_HEADER:
4353 /* This is the initial position of the current game */
4354 gamenum = ics_gamenum;
4355 moveNum = 0; /* old ICS bug workaround */
4356 if (to_play == 'B') {
4357 startedFromSetupPosition = TRUE;
4358 blackPlaysFirst = TRUE;
4360 if (forwardMostMove == 0) forwardMostMove = 1;
4361 if (backwardMostMove == 0) backwardMostMove = 1;
4362 if (currentMove == 0) currentMove = 1;
4364 newGameMode = gameMode;
4365 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4367 case H_GOT_UNWANTED_HEADER:
4368 /* This is an initial board that we don't want */
4370 case H_GETTING_MOVES:
4371 /* Should not happen */
4372 DisplayError(_("Error gathering move list: extra board"), 0);
4373 ics_getting_history = H_FALSE;
4377 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4378 move_str[1] == '@' && !gameInfo.holdingsWidth ||
4379 weird && (int)gameInfo.variant < (int)VariantShogi) {
4380 /* [HGM] We seem to have switched variant unexpectedly
4381 * Try to guess new variant from board size
4383 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4384 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4385 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4386 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4387 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4388 if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4389 if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4390 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4391 /* Get a move list just to see the header, which
4392 will tell us whether this is really bug or zh */
4393 if (ics_getting_history == H_FALSE) {
4394 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4395 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4400 /* Take action if this is the first board of a new game, or of a
4401 different game than is currently being displayed. */
4402 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4403 relation == RELATION_ISOLATED_BOARD) {
4405 /* Forget the old game and get the history (if any) of the new one */
4406 if (gameMode != BeginningOfGame) {
4410 if (appData.autoRaiseBoard) BoardToTop();
4412 if (gamenum == -1) {
4413 newGameMode = IcsIdle;
4414 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4415 appData.getMoveList && !reqFlag) {
4416 /* Need to get game history */
4417 ics_getting_history = H_REQUESTED;
4418 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4422 /* Initially flip the board to have black on the bottom if playing
4423 black or if the ICS flip flag is set, but let the user change
4424 it with the Flip View button. */
4425 flipView = appData.autoFlipView ?
4426 (newGameMode == IcsPlayingBlack) || ics_flip :
4429 /* Done with values from previous mode; copy in new ones */
4430 gameMode = newGameMode;
4432 ics_gamenum = gamenum;
4433 if (gamenum == gs_gamenum) {
4434 int klen = strlen(gs_kind);
4435 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4436 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4437 gameInfo.event = StrSave(str);
4439 gameInfo.event = StrSave("ICS game");
4441 gameInfo.site = StrSave(appData.icsHost);
4442 gameInfo.date = PGNDate();
4443 gameInfo.round = StrSave("-");
4444 gameInfo.white = StrSave(white);
4445 gameInfo.black = StrSave(black);
4446 timeControl = basetime * 60 * 1000;
4448 timeIncrement = increment * 1000;
4449 movesPerSession = 0;
4450 gameInfo.timeControl = TimeControlTagValue();
4451 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4452 if (appData.debugMode) {
4453 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4454 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4455 setbuf(debugFP, NULL);
4458 gameInfo.outOfBook = NULL;
4460 /* Do we have the ratings? */
4461 if (strcmp(player1Name, white) == 0 &&
4462 strcmp(player2Name, black) == 0) {
4463 if (appData.debugMode)
4464 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4465 player1Rating, player2Rating);
4466 gameInfo.whiteRating = player1Rating;
4467 gameInfo.blackRating = player2Rating;
4468 } else if (strcmp(player2Name, white) == 0 &&
4469 strcmp(player1Name, black) == 0) {
4470 if (appData.debugMode)
4471 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4472 player2Rating, player1Rating);
4473 gameInfo.whiteRating = player2Rating;
4474 gameInfo.blackRating = player1Rating;
4476 player1Name[0] = player2Name[0] = NULLCHAR;
4478 /* Silence shouts if requested */
4479 if (appData.quietPlay &&
4480 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4481 SendToICS(ics_prefix);
4482 SendToICS("set shout 0\n");
4486 /* Deal with midgame name changes */
4488 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4489 if (gameInfo.white) free(gameInfo.white);
4490 gameInfo.white = StrSave(white);
4492 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4493 if (gameInfo.black) free(gameInfo.black);
4494 gameInfo.black = StrSave(black);
4498 /* Throw away game result if anything actually changes in examine mode */
4499 if (gameMode == IcsExamining && !newGame) {
4500 gameInfo.result = GameUnfinished;
4501 if (gameInfo.resultDetails != NULL) {
4502 free(gameInfo.resultDetails);
4503 gameInfo.resultDetails = NULL;
4507 /* In pausing && IcsExamining mode, we ignore boards coming
4508 in if they are in a different variation than we are. */
4509 if (pauseExamInvalid) return;
4510 if (pausing && gameMode == IcsExamining) {
4511 if (moveNum <= pauseExamForwardMostMove) {
4512 pauseExamInvalid = TRUE;
4513 forwardMostMove = pauseExamForwardMostMove;
4518 if (appData.debugMode) {
4519 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4521 /* Parse the board */
4522 for (k = 0; k < ranks; k++) {
4523 for (j = 0; j < files; j++)
4524 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4525 if(gameInfo.holdingsWidth > 1) {
4526 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4527 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4530 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4531 board[5][BOARD_RGHT+1] = WhiteAngel;
4532 board[6][BOARD_RGHT+1] = WhiteMarshall;
4533 board[1][0] = BlackMarshall;
4534 board[2][0] = BlackAngel;
4535 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4537 CopyBoard(boards[moveNum], board);
4538 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4540 startedFromSetupPosition =
4541 !CompareBoards(board, initialPosition);
4542 if(startedFromSetupPosition)
4543 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4546 /* [HGM] Set castling rights. Take the outermost Rooks,
4547 to make it also work for FRC opening positions. Note that board12
4548 is really defective for later FRC positions, as it has no way to
4549 indicate which Rook can castle if they are on the same side of King.
4550 For the initial position we grant rights to the outermost Rooks,
4551 and remember thos rights, and we then copy them on positions
4552 later in an FRC game. This means WB might not recognize castlings with
4553 Rooks that have moved back to their original position as illegal,
4554 but in ICS mode that is not its job anyway.
4556 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4557 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4559 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4560 if(board[0][i] == WhiteRook) j = i;
4561 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4562 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4563 if(board[0][i] == WhiteRook) j = i;
4564 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4565 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4566 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4567 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4568 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4569 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4570 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4572 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4573 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4574 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4575 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4576 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4577 if(board[BOARD_HEIGHT-1][k] == bKing)
4578 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4579 if(gameInfo.variant == VariantTwoKings) {
4580 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4581 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4582 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4585 r = boards[moveNum][CASTLING][0] = initialRights[0];
4586 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4587 r = boards[moveNum][CASTLING][1] = initialRights[1];
4588 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4589 r = boards[moveNum][CASTLING][3] = initialRights[3];
4590 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4591 r = boards[moveNum][CASTLING][4] = initialRights[4];
4592 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4593 /* wildcastle kludge: always assume King has rights */
4594 r = boards[moveNum][CASTLING][2] = initialRights[2];
4595 r = boards[moveNum][CASTLING][5] = initialRights[5];
4597 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4598 boards[moveNum][EP_STATUS] = EP_NONE;
4599 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4600 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4601 if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4604 if (ics_getting_history == H_GOT_REQ_HEADER ||
4605 ics_getting_history == H_GOT_UNREQ_HEADER) {
4606 /* This was an initial position from a move list, not
4607 the current position */
4611 /* Update currentMove and known move number limits */
4612 newMove = newGame || moveNum > forwardMostMove;
4615 forwardMostMove = backwardMostMove = currentMove = moveNum;
4616 if (gameMode == IcsExamining && moveNum == 0) {
4617 /* Workaround for ICS limitation: we are not told the wild
4618 type when starting to examine a game. But if we ask for
4619 the move list, the move list header will tell us */
4620 ics_getting_history = H_REQUESTED;
4621 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4624 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4625 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4627 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4628 /* [HGM] applied this also to an engine that is silently watching */
4629 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4630 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4631 gameInfo.variant == currentlyInitializedVariant) {
4632 takeback = forwardMostMove - moveNum;
4633 for (i = 0; i < takeback; i++) {
4634 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4635 SendToProgram("undo\n", &first);
4640 forwardMostMove = moveNum;
4641 if (!pausing || currentMove > forwardMostMove)
4642 currentMove = forwardMostMove;
4644 /* New part of history that is not contiguous with old part */
4645 if (pausing && gameMode == IcsExamining) {
4646 pauseExamInvalid = TRUE;
4647 forwardMostMove = pauseExamForwardMostMove;
4650 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4652 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4653 // [HGM] when we will receive the move list we now request, it will be
4654 // fed to the engine from the first move on. So if the engine is not
4655 // in the initial position now, bring it there.
4656 InitChessProgram(&first, 0);
4659 ics_getting_history = H_REQUESTED;
4660 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4663 forwardMostMove = backwardMostMove = currentMove = moveNum;
4666 /* Update the clocks */
4667 if (strchr(elapsed_time, '.')) {
4669 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4670 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4672 /* Time is in seconds */
4673 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4674 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4679 if (appData.zippyPlay && newGame &&
4680 gameMode != IcsObserving && gameMode != IcsIdle &&
4681 gameMode != IcsExamining)
4682 ZippyFirstBoard(moveNum, basetime, increment);
4685 /* Put the move on the move list, first converting
4686 to canonical algebraic form. */
4688 if (appData.debugMode) {
4689 int f = forwardMostMove;
4690 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4691 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4692 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4693 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4694 fprintf(debugFP, "moveNum = %d\n", moveNum);
4695 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4696 setbuf(debugFP, NULL);
4698 if (moveNum <= backwardMostMove) {
4699 /* We don't know what the board looked like before
4701 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4702 strcat(parseList[moveNum - 1], " ");
4703 strcat(parseList[moveNum - 1], elapsed_time);
4704 moveList[moveNum - 1][0] = NULLCHAR;
4705 } else if (strcmp(move_str, "none") == 0) {
4706 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4707 /* Again, we don't know what the board looked like;
4708 this is really the start of the game. */
4709 parseList[moveNum - 1][0] = NULLCHAR;
4710 moveList[moveNum - 1][0] = NULLCHAR;
4711 backwardMostMove = moveNum;
4712 startedFromSetupPosition = TRUE;
4713 fromX = fromY = toX = toY = -1;
4715 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4716 // So we parse the long-algebraic move string in stead of the SAN move
4717 int valid; char buf[MSG_SIZ], *prom;
4719 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4720 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4721 // str looks something like "Q/a1-a2"; kill the slash
4723 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4724 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4725 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4726 strcat(buf, prom); // long move lacks promo specification!
4727 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4728 if(appData.debugMode)
4729 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4730 safeStrCpy(move_str, buf, MSG_SIZ);
4732 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4733 &fromX, &fromY, &toX, &toY, &promoChar)
4734 || ParseOneMove(buf, moveNum - 1, &moveType,
4735 &fromX, &fromY, &toX, &toY, &promoChar);
4736 // end of long SAN patch
4738 (void) CoordsToAlgebraic(boards[moveNum - 1],
4739 PosFlags(moveNum - 1),
4740 fromY, fromX, toY, toX, promoChar,
4741 parseList[moveNum-1]);
4742 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4748 if(gameInfo.variant != VariantShogi)
4749 strcat(parseList[moveNum - 1], "+");
4752 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4753 strcat(parseList[moveNum - 1], "#");
4756 strcat(parseList[moveNum - 1], " ");
4757 strcat(parseList[moveNum - 1], elapsed_time);
4758 /* currentMoveString is set as a side-effect of ParseOneMove */
4759 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4760 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4761 strcat(moveList[moveNum - 1], "\n");
4763 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4764 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4765 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4766 ChessSquare old, new = boards[moveNum][k][j];
4767 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4768 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4769 if(old == new) continue;
4770 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4771 else if(new == WhiteWazir || new == BlackWazir) {
4772 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4773 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4774 else boards[moveNum][k][j] = old; // preserve type of Gold
4775 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4776 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4779 /* Move from ICS was illegal!? Punt. */
4780 if (appData.debugMode) {
4781 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4782 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4784 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4785 strcat(parseList[moveNum - 1], " ");
4786 strcat(parseList[moveNum - 1], elapsed_time);
4787 moveList[moveNum - 1][0] = NULLCHAR;
4788 fromX = fromY = toX = toY = -1;
4791 if (appData.debugMode) {
4792 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4793 setbuf(debugFP, NULL);
4797 /* Send move to chess program (BEFORE animating it). */
4798 if (appData.zippyPlay && !newGame && newMove &&
4799 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4801 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4802 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4803 if (moveList[moveNum - 1][0] == NULLCHAR) {
4804 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4806 DisplayError(str, 0);
4808 if (first.sendTime) {
4809 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4811 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4812 if (firstMove && !bookHit) {
4814 if (first.useColors) {
4815 SendToProgram(gameMode == IcsPlayingWhite ?
4817 "black\ngo\n", &first);
4819 SendToProgram("go\n", &first);
4821 first.maybeThinking = TRUE;
4824 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4825 if (moveList[moveNum - 1][0] == NULLCHAR) {
4826 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4827 DisplayError(str, 0);
4829 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4830 SendMoveToProgram(moveNum - 1, &first);
4837 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4838 /* If move comes from a remote source, animate it. If it
4839 isn't remote, it will have already been animated. */
4840 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4841 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4843 if (!pausing && appData.highlightLastMove) {
4844 SetHighlights(fromX, fromY, toX, toY);
4848 /* Start the clocks */
4849 whiteFlag = blackFlag = FALSE;
4850 appData.clockMode = !(basetime == 0 && increment == 0);
4852 ics_clock_paused = TRUE;
4854 } else if (ticking == 1) {
4855 ics_clock_paused = FALSE;
4857 if (gameMode == IcsIdle ||
4858 relation == RELATION_OBSERVING_STATIC ||
4859 relation == RELATION_EXAMINING ||
4861 DisplayBothClocks();
4865 /* Display opponents and material strengths */
4866 if (gameInfo.variant != VariantBughouse &&
4867 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4868 if (tinyLayout || smallLayout) {
4869 if(gameInfo.variant == VariantNormal)
4870 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4871 gameInfo.white, white_stren, gameInfo.black, black_stren,
4872 basetime, increment);
4874 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4875 gameInfo.white, white_stren, gameInfo.black, black_stren,
4876 basetime, increment, (int) gameInfo.variant);
4878 if(gameInfo.variant == VariantNormal)
4879 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4880 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4881 basetime, increment);
4883 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
4884 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4885 basetime, increment, VariantName(gameInfo.variant));
4888 if (appData.debugMode) {
4889 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4894 /* Display the board */
4895 if (!pausing && !appData.noGUI) {
4897 if (appData.premove)
4899 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4900 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4901 ClearPremoveHighlights();
4903 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4904 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4905 DrawPosition(j, boards[currentMove]);
4907 DisplayMove(moveNum - 1);
4908 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4909 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4910 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4911 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4915 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4917 if(bookHit) { // [HGM] book: simulate book reply
4918 static char bookMove[MSG_SIZ]; // a bit generous?
4920 programStats.nodes = programStats.depth = programStats.time =
4921 programStats.score = programStats.got_only_move = 0;
4922 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4924 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4925 strcat(bookMove, bookHit);
4926 HandleMachineMove(bookMove, &first);
4935 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4936 ics_getting_history = H_REQUESTED;
4937 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4943 SendToBoth (char *msg)
4944 { // to make it easy to keep two engines in step in dual analysis
4945 SendToProgram(msg, &first);
4946 if(second.analyzing) SendToProgram(msg, &second);
4950 AnalysisPeriodicEvent (int force)
4952 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4953 && !force) || !appData.periodicUpdates)
4956 /* Send . command to Crafty to collect stats */
4959 /* Don't send another until we get a response (this makes
4960 us stop sending to old Crafty's which don't understand
4961 the "." command (sending illegal cmds resets node count & time,
4962 which looks bad)) */
4963 programStats.ok_to_send = 0;
4967 ics_update_width (int new_width)
4969 ics_printf("set width %d\n", new_width);
4973 SendMoveToProgram (int moveNum, ChessProgramState *cps)
4977 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
4978 // null move in variant where engine does not understand it (for analysis purposes)
4979 SendBoard(cps, moveNum + 1); // send position after move in stead.
4982 if (cps->useUsermove) {
4983 SendToProgram("usermove ", cps);
4987 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4988 int len = space - parseList[moveNum];
4989 memcpy(buf, parseList[moveNum], len);
4991 buf[len] = NULLCHAR;
4993 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4995 SendToProgram(buf, cps);
4997 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4998 AlphaRank(moveList[moveNum], 4);
4999 SendToProgram(moveList[moveNum], cps);
5000 AlphaRank(moveList[moveNum], 4); // and back
5002 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5003 * the engine. It would be nice to have a better way to identify castle
5005 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
5006 && cps->useOOCastle) {
5007 int fromX = moveList[moveNum][0] - AAA;
5008 int fromY = moveList[moveNum][1] - ONE;
5009 int toX = moveList[moveNum][2] - AAA;
5010 int toY = moveList[moveNum][3] - ONE;
5011 if((boards[moveNum][fromY][fromX] == WhiteKing
5012 && boards[moveNum][toY][toX] == WhiteRook)
5013 || (boards[moveNum][fromY][fromX] == BlackKing
5014 && boards[moveNum][toY][toX] == BlackRook)) {
5015 if(toX > fromX) SendToProgram("O-O\n", cps);
5016 else SendToProgram("O-O-O\n", cps);
5018 else SendToProgram(moveList[moveNum], cps);
5020 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5021 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5022 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5023 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5024 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5026 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5027 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5028 SendToProgram(buf, cps);
5030 else SendToProgram(moveList[moveNum], cps);
5031 /* End of additions by Tord */
5034 /* [HGM] setting up the opening has brought engine in force mode! */
5035 /* Send 'go' if we are in a mode where machine should play. */
5036 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5037 (gameMode == TwoMachinesPlay ||
5039 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
5041 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5042 SendToProgram("go\n", cps);
5043 if (appData.debugMode) {
5044 fprintf(debugFP, "(extra)\n");
5047 setboardSpoiledMachineBlack = 0;
5051 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5053 char user_move[MSG_SIZ];
5056 if(gameInfo.variant == VariantSChess && promoChar) {
5057 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5058 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5059 } else suffix[0] = NULLCHAR;
5063 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5064 (int)moveType, fromX, fromY, toX, toY);
5065 DisplayError(user_move + strlen("say "), 0);
5067 case WhiteKingSideCastle:
5068 case BlackKingSideCastle:
5069 case WhiteQueenSideCastleWild:
5070 case BlackQueenSideCastleWild:
5072 case WhiteHSideCastleFR:
5073 case BlackHSideCastleFR:
5075 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5077 case WhiteQueenSideCastle:
5078 case BlackQueenSideCastle:
5079 case WhiteKingSideCastleWild:
5080 case BlackKingSideCastleWild:
5082 case WhiteASideCastleFR:
5083 case BlackASideCastleFR:
5085 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5087 case WhiteNonPromotion:
5088 case BlackNonPromotion:
5089 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5091 case WhitePromotion:
5092 case BlackPromotion:
5093 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5094 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5095 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5096 PieceToChar(WhiteFerz));
5097 else if(gameInfo.variant == VariantGreat)
5098 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5099 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5100 PieceToChar(WhiteMan));
5102 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5103 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5109 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5110 ToUpper(PieceToChar((ChessSquare) fromX)),
5111 AAA + toX, ONE + toY);
5113 case IllegalMove: /* could be a variant we don't quite understand */
5114 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5116 case WhiteCapturesEnPassant:
5117 case BlackCapturesEnPassant:
5118 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5119 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5122 SendToICS(user_move);
5123 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5124 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5129 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5130 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5131 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5132 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5133 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5136 if(gameMode != IcsExamining) { // is this ever not the case?
5137 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5139 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5140 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5141 } else { // on FICS we must first go to general examine mode
5142 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5144 if(gameInfo.variant != VariantNormal) {
5145 // try figure out wild number, as xboard names are not always valid on ICS
5146 for(i=1; i<=36; i++) {
5147 snprintf(buf, MSG_SIZ, "wild/%d", i);
5148 if(StringToVariant(buf) == gameInfo.variant) break;
5150 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5151 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5152 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5153 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5154 SendToICS(ics_prefix);
5156 if(startedFromSetupPosition || backwardMostMove != 0) {
5157 fen = PositionToFEN(backwardMostMove, NULL);
5158 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5159 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5161 } else { // FICS: everything has to set by separate bsetup commands
5162 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5163 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5165 if(!WhiteOnMove(backwardMostMove)) {
5166 SendToICS("bsetup tomove black\n");
5168 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5169 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5171 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5172 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5174 i = boards[backwardMostMove][EP_STATUS];
5175 if(i >= 0) { // set e.p.
5176 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5182 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5183 SendToICS("bsetup done\n"); // switch to normal examining.
5185 for(i = backwardMostMove; i<last; i++) {
5187 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5188 if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5189 int len = strlen(moveList[i]);
5190 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5191 if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5195 SendToICS(ics_prefix);
5196 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5200 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5202 if (rf == DROP_RANK) {
5203 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5204 sprintf(move, "%c@%c%c\n",
5205 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5207 if (promoChar == 'x' || promoChar == NULLCHAR) {
5208 sprintf(move, "%c%c%c%c\n",
5209 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5211 sprintf(move, "%c%c%c%c%c\n",
5212 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5218 ProcessICSInitScript (FILE *f)
5222 while (fgets(buf, MSG_SIZ, f)) {
5223 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5230 static int lastX, lastY, selectFlag, dragging;
5235 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5236 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5237 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5238 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5239 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5240 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
5243 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5244 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5245 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5246 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5247 if(!step) step = -1;
5248 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5249 appData.testLegality && (promoSweep == king ||
5250 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
5252 int victim = boards[currentMove][toY][toX];
5253 boards[currentMove][toY][toX] = promoSweep;
5254 DrawPosition(FALSE, boards[currentMove]);
5255 boards[currentMove][toY][toX] = victim;
5257 ChangeDragPiece(promoSweep);
5261 PromoScroll (int x, int y)
5265 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5266 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5267 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5268 if(!step) return FALSE;
5269 lastX = x; lastY = y;
5270 if((promoSweep < BlackPawn) == flipView) step = -step;
5271 if(step > 0) selectFlag = 1;
5272 if(!selectFlag) Sweep(step);
5277 NextPiece (int step)
5279 ChessSquare piece = boards[currentMove][toY][toX];
5282 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5283 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5284 if(!step) step = -1;
5285 } while(PieceToChar(pieceSweep) == '.');
5286 boards[currentMove][toY][toX] = pieceSweep;
5287 DrawPosition(FALSE, boards[currentMove]);
5288 boards[currentMove][toY][toX] = piece;
5290 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5292 AlphaRank (char *move, int n)
5294 // char *p = move, c; int x, y;
5296 if (appData.debugMode) {
5297 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5301 move[2]>='0' && move[2]<='9' &&
5302 move[3]>='a' && move[3]<='x' ) {
5304 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5305 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5307 if(move[0]>='0' && move[0]<='9' &&
5308 move[1]>='a' && move[1]<='x' &&
5309 move[2]>='0' && move[2]<='9' &&
5310 move[3]>='a' && move[3]<='x' ) {
5311 /* input move, Shogi -> normal */
5312 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5313 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5314 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5315 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5318 move[3]>='0' && move[3]<='9' &&
5319 move[2]>='a' && move[2]<='x' ) {
5321 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5322 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5325 move[0]>='a' && move[0]<='x' &&
5326 move[3]>='0' && move[3]<='9' &&
5327 move[2]>='a' && move[2]<='x' ) {
5328 /* output move, normal -> Shogi */
5329 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5330 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5331 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5332 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5333 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5335 if (appData.debugMode) {
5336 fprintf(debugFP, " out = '%s'\n", move);
5340 char yy_textstr[8000];
5342 /* Parser for moves from gnuchess, ICS, or user typein box */
5344 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5346 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5348 switch (*moveType) {
5349 case WhitePromotion:
5350 case BlackPromotion:
5351 case WhiteNonPromotion:
5352 case BlackNonPromotion:
5354 case WhiteCapturesEnPassant:
5355 case BlackCapturesEnPassant:
5356 case WhiteKingSideCastle:
5357 case WhiteQueenSideCastle:
5358 case BlackKingSideCastle:
5359 case BlackQueenSideCastle:
5360 case WhiteKingSideCastleWild:
5361 case WhiteQueenSideCastleWild:
5362 case BlackKingSideCastleWild:
5363 case BlackQueenSideCastleWild:
5364 /* Code added by Tord: */
5365 case WhiteHSideCastleFR:
5366 case WhiteASideCastleFR:
5367 case BlackHSideCastleFR:
5368 case BlackASideCastleFR:
5369 /* End of code added by Tord */
5370 case IllegalMove: /* bug or odd chess variant */
5371 *fromX = currentMoveString[0] - AAA;
5372 *fromY = currentMoveString[1] - ONE;
5373 *toX = currentMoveString[2] - AAA;
5374 *toY = currentMoveString[3] - ONE;
5375 *promoChar = currentMoveString[4];
5376 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5377 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5378 if (appData.debugMode) {
5379 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5381 *fromX = *fromY = *toX = *toY = 0;
5384 if (appData.testLegality) {
5385 return (*moveType != IllegalMove);
5387 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5388 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5393 *fromX = *moveType == WhiteDrop ?
5394 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5395 (int) CharToPiece(ToLower(currentMoveString[0]));
5397 *toX = currentMoveString[2] - AAA;
5398 *toY = currentMoveString[3] - ONE;
5399 *promoChar = NULLCHAR;
5403 case ImpossibleMove:
5413 if (appData.debugMode) {
5414 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5417 *fromX = *fromY = *toX = *toY = 0;
5418 *promoChar = NULLCHAR;
5423 Boolean pushed = FALSE;
5424 char *lastParseAttempt;
5427 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5428 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5429 int fromX, fromY, toX, toY; char promoChar;
5434 lastParseAttempt = pv; if(!*pv) return; // turns out we crash when we parse an empty PV
5435 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5436 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5439 endPV = forwardMostMove;
5441 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5442 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5443 lastParseAttempt = pv;
5444 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5445 if(!valid && nr == 0 &&
5446 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5447 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5448 // Hande case where played move is different from leading PV move
5449 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5450 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5451 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5452 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5453 endPV += 2; // if position different, keep this
5454 moveList[endPV-1][0] = fromX + AAA;
5455 moveList[endPV-1][1] = fromY + ONE;
5456 moveList[endPV-1][2] = toX + AAA;
5457 moveList[endPV-1][3] = toY + ONE;
5458 parseList[endPV-1][0] = NULLCHAR;
5459 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5462 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5463 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5464 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5465 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5466 valid++; // allow comments in PV
5470 if(endPV+1 > framePtr) break; // no space, truncate
5473 CopyBoard(boards[endPV], boards[endPV-1]);
5474 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5475 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5476 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5477 CoordsToAlgebraic(boards[endPV - 1],
5478 PosFlags(endPV - 1),
5479 fromY, fromX, toY, toX, promoChar,
5480 parseList[endPV - 1]);
5482 if(atEnd == 2) return; // used hidden, for PV conversion
5483 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5484 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5485 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5486 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5487 DrawPosition(TRUE, boards[currentMove]);
5491 MultiPV (ChessProgramState *cps)
5492 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5494 for(i=0; i<cps->nrOptions; i++)
5495 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5500 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5503 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5505 int startPV, multi, lineStart, origIndex = index;
5506 char *p, buf2[MSG_SIZ];
5507 ChessProgramState *cps = (pane ? &second : &first);
5509 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5510 lastX = x; lastY = y;
5511 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5512 lineStart = startPV = index;
5513 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5514 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5516 do{ while(buf[index] && buf[index] != '\n') index++;
5517 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5519 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(cps)) >= 0) {
5520 int n = cps->option[multi].value;
5521 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5522 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5523 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5524 cps->option[multi].value = n;
5527 } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5528 ExcludeClick(origIndex - lineStart);
5531 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5532 *start = startPV; *end = index-1;
5533 extendGame = (gameMode == AnalyzeMode && appData.autoExtend);
5540 static char buf[10*MSG_SIZ];
5541 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5543 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5544 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5545 for(i = forwardMostMove; i<endPV; i++){
5546 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5547 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5550 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5551 if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5552 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5558 LoadPV (int x, int y)
5559 { // called on right mouse click to load PV
5560 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5561 lastX = x; lastY = y;
5562 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5570 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5571 if(endPV < 0) return;
5572 if(appData.autoCopyPV) CopyFENToClipboard();
5574 if(extendGame && currentMove > forwardMostMove) {
5575 Boolean saveAnimate = appData.animate;
5577 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5578 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5579 } else storedGames--; // abandon shelved tail of original game
5582 forwardMostMove = currentMove;
5583 currentMove = oldFMM;
5584 appData.animate = FALSE;
5585 ToNrEvent(forwardMostMove);
5586 appData.animate = saveAnimate;
5588 currentMove = forwardMostMove;
5589 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5590 ClearPremoveHighlights();
5591 DrawPosition(TRUE, boards[currentMove]);
5595 MovePV (int x, int y, int h)
5596 { // step through PV based on mouse coordinates (called on mouse move)
5597 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5599 // we must somehow check if right button is still down (might be released off board!)
5600 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5601 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5602 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5604 lastX = x; lastY = y;
5606 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5607 if(endPV < 0) return;
5608 if(y < margin) step = 1; else
5609 if(y > h - margin) step = -1;
5610 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5611 currentMove += step;
5612 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5613 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5614 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5615 DrawPosition(FALSE, boards[currentMove]);
5619 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5620 // All positions will have equal probability, but the current method will not provide a unique
5621 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5627 int piecesLeft[(int)BlackPawn];
5628 int seed, nrOfShuffles;
5631 GetPositionNumber ()
5632 { // sets global variable seed
5635 seed = appData.defaultFrcPosition;
5636 if(seed < 0) { // randomize based on time for negative FRC position numbers
5637 for(i=0; i<50; i++) seed += random();
5638 seed = random() ^ random() >> 8 ^ random() << 8;
5639 if(seed<0) seed = -seed;
5644 put (Board board, int pieceType, int rank, int n, int shade)
5645 // put the piece on the (n-1)-th empty squares of the given shade
5649 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5650 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5651 board[rank][i] = (ChessSquare) pieceType;
5652 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5654 piecesLeft[pieceType]--;
5663 AddOnePiece (Board board, int pieceType, int rank, int shade)
5664 // calculate where the next piece goes, (any empty square), and put it there
5668 i = seed % squaresLeft[shade];
5669 nrOfShuffles *= squaresLeft[shade];
5670 seed /= squaresLeft[shade];
5671 put(board, pieceType, rank, i, shade);
5675 AddTwoPieces (Board board, int pieceType, int rank)
5676 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5678 int i, n=squaresLeft[ANY], j=n-1, k;
5680 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5681 i = seed % k; // pick one
5684 while(i >= j) i -= j--;
5685 j = n - 1 - j; i += j;
5686 put(board, pieceType, rank, j, ANY);
5687 put(board, pieceType, rank, i, ANY);
5691 SetUpShuffle (Board board, int number)
5695 GetPositionNumber(); nrOfShuffles = 1;
5697 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5698 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5699 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5701 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5703 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5704 p = (int) board[0][i];
5705 if(p < (int) BlackPawn) piecesLeft[p] ++;
5706 board[0][i] = EmptySquare;
5709 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5710 // shuffles restricted to allow normal castling put KRR first
5711 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5712 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5713 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5714 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5715 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5716 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5717 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5718 put(board, WhiteRook, 0, 0, ANY);
5719 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5722 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5723 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5724 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5725 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5726 while(piecesLeft[p] >= 2) {
5727 AddOnePiece(board, p, 0, LITE);
5728 AddOnePiece(board, p, 0, DARK);
5730 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5733 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5734 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5735 // but we leave King and Rooks for last, to possibly obey FRC restriction
5736 if(p == (int)WhiteRook) continue;
5737 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5738 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5741 // now everything is placed, except perhaps King (Unicorn) and Rooks
5743 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5744 // Last King gets castling rights
5745 while(piecesLeft[(int)WhiteUnicorn]) {
5746 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5747 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5750 while(piecesLeft[(int)WhiteKing]) {
5751 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5752 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5757 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5758 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5761 // Only Rooks can be left; simply place them all
5762 while(piecesLeft[(int)WhiteRook]) {
5763 i = put(board, WhiteRook, 0, 0, ANY);
5764 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5767 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5769 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5772 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5773 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5776 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5780 SetCharTable (char *table, const char * map)
5781 /* [HGM] moved here from winboard.c because of its general usefulness */
5782 /* Basically a safe strcpy that uses the last character as King */
5784 int result = FALSE; int NrPieces;
5786 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5787 && NrPieces >= 12 && !(NrPieces&1)) {
5788 int i; /* [HGM] Accept even length from 12 to 34 */
5790 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5791 for( i=0; i<NrPieces/2-1; i++ ) {
5793 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5795 table[(int) WhiteKing] = map[NrPieces/2-1];
5796 table[(int) BlackKing] = map[NrPieces-1];
5805 Prelude (Board board)
5806 { // [HGM] superchess: random selection of exo-pieces
5807 int i, j, k; ChessSquare p;
5808 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5810 GetPositionNumber(); // use FRC position number
5812 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5813 SetCharTable(pieceToChar, appData.pieceToCharTable);
5814 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5815 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5818 j = seed%4; seed /= 4;
5819 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5820 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5821 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5822 j = seed%3 + (seed%3 >= j); seed /= 3;
5823 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5824 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5825 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5826 j = seed%3; seed /= 3;
5827 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5828 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5829 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5830 j = seed%2 + (seed%2 >= j); seed /= 2;
5831 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5832 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5833 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5834 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5835 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5836 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5837 put(board, exoPieces[0], 0, 0, ANY);
5838 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5842 InitPosition (int redraw)
5844 ChessSquare (* pieces)[BOARD_FILES];
5845 int i, j, pawnRow, overrule,
5846 oldx = gameInfo.boardWidth,
5847 oldy = gameInfo.boardHeight,
5848 oldh = gameInfo.holdingsWidth;
5851 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5853 /* [AS] Initialize pv info list [HGM] and game status */
5855 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5856 pvInfoList[i].depth = 0;
5857 boards[i][EP_STATUS] = EP_NONE;
5858 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5861 initialRulePlies = 0; /* 50-move counter start */
5863 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5864 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5868 /* [HGM] logic here is completely changed. In stead of full positions */
5869 /* the initialized data only consist of the two backranks. The switch */
5870 /* selects which one we will use, which is than copied to the Board */
5871 /* initialPosition, which for the rest is initialized by Pawns and */
5872 /* empty squares. This initial position is then copied to boards[0], */
5873 /* possibly after shuffling, so that it remains available. */
5875 gameInfo.holdingsWidth = 0; /* default board sizes */
5876 gameInfo.boardWidth = 8;
5877 gameInfo.boardHeight = 8;
5878 gameInfo.holdingsSize = 0;
5879 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5880 for(i=0; i<BOARD_FILES-2; i++)
5881 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5882 initialPosition[EP_STATUS] = EP_NONE;
5883 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5884 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5885 SetCharTable(pieceNickName, appData.pieceNickNames);
5886 else SetCharTable(pieceNickName, "............");
5889 switch (gameInfo.variant) {
5890 case VariantFischeRandom:
5891 shuffleOpenings = TRUE;
5894 case VariantShatranj:
5895 pieces = ShatranjArray;
5896 nrCastlingRights = 0;
5897 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5900 pieces = makrukArray;
5901 nrCastlingRights = 0;
5902 startedFromSetupPosition = TRUE;
5903 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5905 case VariantTwoKings:
5906 pieces = twoKingsArray;
5909 pieces = GrandArray;
5910 nrCastlingRights = 0;
5911 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5912 gameInfo.boardWidth = 10;
5913 gameInfo.boardHeight = 10;
5914 gameInfo.holdingsSize = 7;
5916 case VariantCapaRandom:
5917 shuffleOpenings = TRUE;
5918 case VariantCapablanca:
5919 pieces = CapablancaArray;
5920 gameInfo.boardWidth = 10;
5921 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5924 pieces = GothicArray;
5925 gameInfo.boardWidth = 10;
5926 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5929 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5930 gameInfo.holdingsSize = 7;
5931 for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
5934 pieces = JanusArray;
5935 gameInfo.boardWidth = 10;
5936 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5937 nrCastlingRights = 6;
5938 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5939 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5940 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5941 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5942 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5943 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5946 pieces = FalconArray;
5947 gameInfo.boardWidth = 10;
5948 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5950 case VariantXiangqi:
5951 pieces = XiangqiArray;
5952 gameInfo.boardWidth = 9;
5953 gameInfo.boardHeight = 10;
5954 nrCastlingRights = 0;
5955 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5958 pieces = ShogiArray;
5959 gameInfo.boardWidth = 9;
5960 gameInfo.boardHeight = 9;
5961 gameInfo.holdingsSize = 7;
5962 nrCastlingRights = 0;
5963 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5965 case VariantCourier:
5966 pieces = CourierArray;
5967 gameInfo.boardWidth = 12;
5968 nrCastlingRights = 0;
5969 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5971 case VariantKnightmate:
5972 pieces = KnightmateArray;
5973 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5975 case VariantSpartan:
5976 pieces = SpartanArray;
5977 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5980 pieces = fairyArray;
5981 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5984 pieces = GreatArray;
5985 gameInfo.boardWidth = 10;
5986 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5987 gameInfo.holdingsSize = 8;
5991 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5992 gameInfo.holdingsSize = 8;
5993 startedFromSetupPosition = TRUE;
5995 case VariantCrazyhouse:
5996 case VariantBughouse:
5998 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5999 gameInfo.holdingsSize = 5;
6001 case VariantWildCastle:
6003 /* !!?shuffle with kings guaranteed to be on d or e file */
6004 shuffleOpenings = 1;
6006 case VariantNoCastle:
6008 nrCastlingRights = 0;
6009 /* !!?unconstrained back-rank shuffle */
6010 shuffleOpenings = 1;
6015 if(appData.NrFiles >= 0) {
6016 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6017 gameInfo.boardWidth = appData.NrFiles;
6019 if(appData.NrRanks >= 0) {
6020 gameInfo.boardHeight = appData.NrRanks;
6022 if(appData.holdingsSize >= 0) {
6023 i = appData.holdingsSize;
6024 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6025 gameInfo.holdingsSize = i;
6027 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6028 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6029 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6031 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6032 if(pawnRow < 1) pawnRow = 1;
6033 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) pawnRow = 2;
6035 /* User pieceToChar list overrules defaults */
6036 if(appData.pieceToCharTable != NULL)
6037 SetCharTable(pieceToChar, appData.pieceToCharTable);
6039 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6041 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6042 s = (ChessSquare) 0; /* account holding counts in guard band */
6043 for( i=0; i<BOARD_HEIGHT; i++ )
6044 initialPosition[i][j] = s;
6046 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6047 initialPosition[gameInfo.variant == VariantGrand][j] = pieces[0][j-gameInfo.holdingsWidth];
6048 initialPosition[pawnRow][j] = WhitePawn;
6049 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6050 if(gameInfo.variant == VariantXiangqi) {
6052 initialPosition[pawnRow][j] =
6053 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6054 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6055 initialPosition[2][j] = WhiteCannon;
6056 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6060 if(gameInfo.variant == VariantGrand) {
6061 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6062 initialPosition[0][j] = WhiteRook;
6063 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6066 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand)][j] = pieces[1][j-gameInfo.holdingsWidth];
6068 if( (gameInfo.variant == VariantShogi) && !overrule ) {
6071 initialPosition[1][j] = WhiteBishop;
6072 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6074 initialPosition[1][j] = WhiteRook;
6075 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6078 if( nrCastlingRights == -1) {
6079 /* [HGM] Build normal castling rights (must be done after board sizing!) */
6080 /* This sets default castling rights from none to normal corners */
6081 /* Variants with other castling rights must set them themselves above */
6082 nrCastlingRights = 6;
6084 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6085 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6086 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6087 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6088 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6089 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6092 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6093 if(gameInfo.variant == VariantGreat) { // promotion commoners
6094 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6095 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6096 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6097 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
6099 if( gameInfo.variant == VariantSChess ) {
6100 initialPosition[1][0] = BlackMarshall;
6101 initialPosition[2][0] = BlackAngel;
6102 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6103 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6104 initialPosition[1][1] = initialPosition[2][1] =
6105 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6107 if (appData.debugMode) {
6108 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6110 if(shuffleOpenings) {
6111 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6112 startedFromSetupPosition = TRUE;
6114 if(startedFromPositionFile) {
6115 /* [HGM] loadPos: use PositionFile for every new game */
6116 CopyBoard(initialPosition, filePosition);
6117 for(i=0; i<nrCastlingRights; i++)
6118 initialRights[i] = filePosition[CASTLING][i];
6119 startedFromSetupPosition = TRUE;
6122 CopyBoard(boards[0], initialPosition);
6124 if(oldx != gameInfo.boardWidth ||
6125 oldy != gameInfo.boardHeight ||
6126 oldv != gameInfo.variant ||
6127 oldh != gameInfo.holdingsWidth
6129 InitDrawingSizes(-2 ,0);
6131 oldv = gameInfo.variant;
6133 DrawPosition(TRUE, boards[currentMove]);
6137 SendBoard (ChessProgramState *cps, int moveNum)
6139 char message[MSG_SIZ];
6141 if (cps->useSetboard) {
6142 char* fen = PositionToFEN(moveNum, cps->fenOverride);
6143 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6144 SendToProgram(message, cps);
6149 int i, j, left=0, right=BOARD_WIDTH;
6150 /* Kludge to set black to move, avoiding the troublesome and now
6151 * deprecated "black" command.
6153 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6154 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6156 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6158 SendToProgram("edit\n", cps);
6159 SendToProgram("#\n", cps);
6160 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6161 bp = &boards[moveNum][i][left];
6162 for (j = left; j < right; j++, bp++) {
6163 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6164 if ((int) *bp < (int) BlackPawn) {
6165 if(j == BOARD_RGHT+1)
6166 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6167 else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6168 if(message[0] == '+' || message[0] == '~') {
6169 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6170 PieceToChar((ChessSquare)(DEMOTED *bp)),
6173 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6174 message[1] = BOARD_RGHT - 1 - j + '1';
6175 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6177 SendToProgram(message, cps);
6182 SendToProgram("c\n", cps);
6183 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6184 bp = &boards[moveNum][i][left];
6185 for (j = left; j < right; j++, bp++) {
6186 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6187 if (((int) *bp != (int) EmptySquare)
6188 && ((int) *bp >= (int) BlackPawn)) {
6189 if(j == BOARD_LEFT-2)
6190 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6191 else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6193 if(message[0] == '+' || message[0] == '~') {
6194 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6195 PieceToChar((ChessSquare)(DEMOTED *bp)),
6198 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6199 message[1] = BOARD_RGHT - 1 - j + '1';
6200 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6202 SendToProgram(message, cps);
6207 SendToProgram(".\n", cps);
6209 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6212 char exclusionHeader[MSG_SIZ];
6213 int exCnt, excludePtr;
6214 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6215 static Exclusion excluTab[200];
6216 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6222 for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6223 exclusionHeader[19] = s ? '-' : '+'; // update tail state
6229 safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
6230 excludePtr = 24; exCnt = 0;
6235 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6236 { // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6237 char buf[2*MOVE_LEN], *p;
6238 Exclusion *e = excluTab;
6240 for(i=0; i<exCnt; i++)
6241 if(e[i].ff == fromX && e[i].fr == fromY &&
6242 e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
6243 if(i == exCnt) { // was not in exclude list; add it
6244 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6245 if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6246 if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6249 e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6250 excludePtr++; e[i].mark = excludePtr++;
6251 for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6254 exclusionHeader[e[i].mark] = state;
6258 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6259 { // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6263 if((signed char)promoChar == -1) { // kludge to indicate best move
6264 if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6265 return 1; // if unparsable, abort
6267 // update exclusion map (resolving toggle by consulting existing state)
6268 k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6270 if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6271 if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6272 excludeMap[k] |= 1<<j;
6273 else excludeMap[k] &= ~(1<<j);
6275 UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6277 snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6278 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6280 return (state == '+');
6284 ExcludeClick (int index)
6287 Exclusion *e = excluTab;
6288 if(index < 25) { // none, best or tail clicked
6289 if(index < 13) { // none: include all
6290 WriteMap(0); // clear map
6291 for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6292 SendToBoth("include all\n"); // and inform engine
6293 } else if(index > 18) { // tail
6294 if(exclusionHeader[19] == '-') { // tail was excluded
6295 SendToBoth("include all\n");
6296 WriteMap(0); // clear map completely
6297 // now re-exclude selected moves
6298 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6299 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6300 } else { // tail was included or in mixed state
6301 SendToBoth("exclude all\n");
6302 WriteMap(0xFF); // fill map completely
6303 // now re-include selected moves
6304 j = 0; // count them
6305 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6306 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6307 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6310 ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6313 for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6314 char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6315 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6322 DefaultPromoChoice (int white)
6325 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
6326 result = WhiteFerz; // no choice
6327 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6328 result= WhiteKing; // in Suicide Q is the last thing we want
6329 else if(gameInfo.variant == VariantSpartan)
6330 result = white ? WhiteQueen : WhiteAngel;
6331 else result = WhiteQueen;
6332 if(!white) result = WHITE_TO_BLACK result;
6336 static int autoQueen; // [HGM] oneclick
6339 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6341 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6342 /* [HGM] add Shogi promotions */
6343 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6348 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6349 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6351 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6352 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6355 piece = boards[currentMove][fromY][fromX];
6356 if(gameInfo.variant == VariantShogi) {
6357 promotionZoneSize = BOARD_HEIGHT/3;
6358 highestPromotingPiece = (int)WhiteFerz;
6359 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) {
6360 promotionZoneSize = 3;
6363 // Treat Lance as Pawn when it is not representing Amazon
6364 if(gameInfo.variant != VariantSuper) {
6365 if(piece == WhiteLance) piece = WhitePawn; else
6366 if(piece == BlackLance) piece = BlackPawn;
6369 // next weed out all moves that do not touch the promotion zone at all
6370 if((int)piece >= BlackPawn) {
6371 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6373 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6375 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6376 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6379 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6381 // weed out mandatory Shogi promotions
6382 if(gameInfo.variant == VariantShogi) {
6383 if(piece >= BlackPawn) {
6384 if(toY == 0 && piece == BlackPawn ||
6385 toY == 0 && piece == BlackQueen ||
6386 toY <= 1 && piece == BlackKnight) {
6391 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6392 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6393 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6400 // weed out obviously illegal Pawn moves
6401 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6402 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6403 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6404 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6405 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6406 // note we are not allowed to test for valid (non-)capture, due to premove
6409 // we either have a choice what to promote to, or (in Shogi) whether to promote
6410 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
6411 *promoChoice = PieceToChar(BlackFerz); // no choice
6414 // no sense asking what we must promote to if it is going to explode...
6415 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6416 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6419 // give caller the default choice even if we will not make it
6420 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6421 if(gameInfo.variant == VariantShogi) *promoChoice = (defaultPromoChoice == piece ? '=' : '+');
6422 if( sweepSelect && gameInfo.variant != VariantGreat
6423 && gameInfo.variant != VariantGrand
6424 && gameInfo.variant != VariantSuper) return FALSE;
6425 if(autoQueen) return FALSE; // predetermined
6427 // suppress promotion popup on illegal moves that are not premoves
6428 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6429 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6430 if(appData.testLegality && !premove) {
6431 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6432 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
6433 if(moveType != WhitePromotion && moveType != BlackPromotion)
6441 InPalace (int row, int column)
6442 { /* [HGM] for Xiangqi */
6443 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6444 column < (BOARD_WIDTH + 4)/2 &&
6445 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6450 PieceForSquare (int x, int y)
6452 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6455 return boards[currentMove][y][x];
6459 OKToStartUserMove (int x, int y)
6461 ChessSquare from_piece;
6464 if (matchMode) return FALSE;
6465 if (gameMode == EditPosition) return TRUE;
6467 if (x >= 0 && y >= 0)
6468 from_piece = boards[currentMove][y][x];
6470 from_piece = EmptySquare;
6472 if (from_piece == EmptySquare) return FALSE;
6474 white_piece = (int)from_piece >= (int)WhitePawn &&
6475 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6479 case TwoMachinesPlay:
6487 case MachinePlaysWhite:
6488 case IcsPlayingBlack:
6489 if (appData.zippyPlay) return FALSE;
6491 DisplayMoveError(_("You are playing Black"));
6496 case MachinePlaysBlack:
6497 case IcsPlayingWhite:
6498 if (appData.zippyPlay) return FALSE;
6500 DisplayMoveError(_("You are playing White"));
6505 case PlayFromGameFile:
6506 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6508 if (!white_piece && WhiteOnMove(currentMove)) {
6509 DisplayMoveError(_("It is White's turn"));
6512 if (white_piece && !WhiteOnMove(currentMove)) {
6513 DisplayMoveError(_("It is Black's turn"));
6516 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6517 /* Editing correspondence game history */
6518 /* Could disallow this or prompt for confirmation */
6523 case BeginningOfGame:
6524 if (appData.icsActive) return FALSE;
6525 if (!appData.noChessProgram) {
6527 DisplayMoveError(_("You are playing White"));
6534 if (!white_piece && WhiteOnMove(currentMove)) {
6535 DisplayMoveError(_("It is White's turn"));
6538 if (white_piece && !WhiteOnMove(currentMove)) {
6539 DisplayMoveError(_("It is Black's turn"));
6548 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6549 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6550 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6551 && gameMode != AnalyzeFile && gameMode != Training) {
6552 DisplayMoveError(_("Displayed position is not current"));
6559 OnlyMove (int *x, int *y, Boolean captures)
6561 DisambiguateClosure cl;
6562 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6564 case MachinePlaysBlack:
6565 case IcsPlayingWhite:
6566 case BeginningOfGame:
6567 if(!WhiteOnMove(currentMove)) return FALSE;
6569 case MachinePlaysWhite:
6570 case IcsPlayingBlack:
6571 if(WhiteOnMove(currentMove)) return FALSE;
6578 cl.pieceIn = EmptySquare;
6583 cl.promoCharIn = NULLCHAR;
6584 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6585 if( cl.kind == NormalMove ||
6586 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6587 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6588 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6595 if(cl.kind != ImpossibleMove) return FALSE;
6596 cl.pieceIn = EmptySquare;
6601 cl.promoCharIn = NULLCHAR;
6602 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6603 if( cl.kind == NormalMove ||
6604 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6605 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6606 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6611 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6617 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6618 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6619 int lastLoadGameUseList = FALSE;
6620 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6621 ChessMove lastLoadGameStart = EndOfFile;
6625 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6629 int ff=fromX, rf=fromY, ft=toX, rt=toY;
6631 /* Check if the user is playing in turn. This is complicated because we
6632 let the user "pick up" a piece before it is his turn. So the piece he
6633 tried to pick up may have been captured by the time he puts it down!
6634 Therefore we use the color the user is supposed to be playing in this
6635 test, not the color of the piece that is currently on the starting
6636 square---except in EditGame mode, where the user is playing both
6637 sides; fortunately there the capture race can't happen. (It can
6638 now happen in IcsExamining mode, but that's just too bad. The user
6639 will get a somewhat confusing message in that case.)
6644 case TwoMachinesPlay:
6648 /* We switched into a game mode where moves are not accepted,
6649 perhaps while the mouse button was down. */
6652 case MachinePlaysWhite:
6653 /* User is moving for Black */
6654 if (WhiteOnMove(currentMove)) {
6655 DisplayMoveError(_("It is White's turn"));
6660 case MachinePlaysBlack:
6661 /* User is moving for White */
6662 if (!WhiteOnMove(currentMove)) {
6663 DisplayMoveError(_("It is Black's turn"));
6668 case PlayFromGameFile:
6669 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6672 case BeginningOfGame:
6675 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6676 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6677 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6678 /* User is moving for Black */
6679 if (WhiteOnMove(currentMove)) {
6680 DisplayMoveError(_("It is White's turn"));
6684 /* User is moving for White */
6685 if (!WhiteOnMove(currentMove)) {
6686 DisplayMoveError(_("It is Black's turn"));
6692 case IcsPlayingBlack:
6693 /* User is moving for Black */
6694 if (WhiteOnMove(currentMove)) {
6695 if (!appData.premove) {
6696 DisplayMoveError(_("It is White's turn"));
6697 } else if (toX >= 0 && toY >= 0) {
6700 premoveFromX = fromX;
6701 premoveFromY = fromY;
6702 premovePromoChar = promoChar;
6704 if (appData.debugMode)
6705 fprintf(debugFP, "Got premove: fromX %d,"
6706 "fromY %d, toX %d, toY %d\n",
6707 fromX, fromY, toX, toY);
6713 case IcsPlayingWhite:
6714 /* User is moving for White */
6715 if (!WhiteOnMove(currentMove)) {
6716 if (!appData.premove) {
6717 DisplayMoveError(_("It is Black's turn"));
6718 } else if (toX >= 0 && toY >= 0) {
6721 premoveFromX = fromX;
6722 premoveFromY = fromY;
6723 premovePromoChar = promoChar;
6725 if (appData.debugMode)
6726 fprintf(debugFP, "Got premove: fromX %d,"
6727 "fromY %d, toX %d, toY %d\n",
6728 fromX, fromY, toX, toY);
6738 /* EditPosition, empty square, or different color piece;
6739 click-click move is possible */
6740 if (toX == -2 || toY == -2) {
6741 boards[0][fromY][fromX] = EmptySquare;
6742 DrawPosition(FALSE, boards[currentMove]);
6744 } else if (toX >= 0 && toY >= 0) {
6745 boards[0][toY][toX] = boards[0][fromY][fromX];
6746 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6747 if(boards[0][fromY][0] != EmptySquare) {
6748 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6749 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6752 if(fromX == BOARD_RGHT+1) {
6753 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6754 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6755 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6758 boards[0][fromY][fromX] = gatingPiece;
6759 DrawPosition(FALSE, boards[currentMove]);
6765 if(toX < 0 || toY < 0) return;
6766 pup = boards[currentMove][toY][toX];
6768 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6769 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6770 if( pup != EmptySquare ) return;
6771 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6772 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6773 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6774 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6775 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6776 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6777 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6781 /* [HGM] always test for legality, to get promotion info */
6782 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6783 fromY, fromX, toY, toX, promoChar);
6785 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame)) moveType = NormalMove;
6787 /* [HGM] but possibly ignore an IllegalMove result */
6788 if (appData.testLegality) {
6789 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6790 DisplayMoveError(_("Illegal move"));
6795 if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
6796 if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
6797 ClearPremoveHighlights(); // was included
6798 else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
6802 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6805 /* Common tail of UserMoveEvent and DropMenuEvent */
6807 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
6811 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
6812 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
6813 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6814 if(WhiteOnMove(currentMove)) {
6815 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6817 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6821 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6822 move type in caller when we know the move is a legal promotion */
6823 if(moveType == NormalMove && promoChar)
6824 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6826 /* [HGM] <popupFix> The following if has been moved here from
6827 UserMoveEvent(). Because it seemed to belong here (why not allow
6828 piece drops in training games?), and because it can only be
6829 performed after it is known to what we promote. */
6830 if (gameMode == Training) {
6831 /* compare the move played on the board to the next move in the
6832 * game. If they match, display the move and the opponent's response.
6833 * If they don't match, display an error message.
6837 CopyBoard(testBoard, boards[currentMove]);
6838 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6840 if (CompareBoards(testBoard, boards[currentMove+1])) {
6841 ForwardInner(currentMove+1);
6843 /* Autoplay the opponent's response.
6844 * if appData.animate was TRUE when Training mode was entered,
6845 * the response will be animated.
6847 saveAnimate = appData.animate;
6848 appData.animate = animateTraining;
6849 ForwardInner(currentMove+1);
6850 appData.animate = saveAnimate;
6852 /* check for the end of the game */
6853 if (currentMove >= forwardMostMove) {
6854 gameMode = PlayFromGameFile;
6856 SetTrainingModeOff();
6857 DisplayInformation(_("End of game"));
6860 DisplayError(_("Incorrect move"), 0);
6865 /* Ok, now we know that the move is good, so we can kill
6866 the previous line in Analysis Mode */
6867 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
6868 && currentMove < forwardMostMove) {
6869 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6870 else forwardMostMove = currentMove;
6875 /* If we need the chess program but it's dead, restart it */
6876 ResurrectChessProgram();
6878 /* A user move restarts a paused game*/
6882 thinkOutput[0] = NULLCHAR;
6884 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6886 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6887 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6891 if (gameMode == BeginningOfGame) {
6892 if (appData.noChessProgram) {
6893 gameMode = EditGame;
6897 gameMode = MachinePlaysBlack;
6900 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
6902 if (first.sendName) {
6903 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6904 SendToProgram(buf, &first);
6911 /* Relay move to ICS or chess engine */
6912 if (appData.icsActive) {
6913 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6914 gameMode == IcsExamining) {
6915 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6916 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6918 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6920 // also send plain move, in case ICS does not understand atomic claims
6921 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6925 if (first.sendTime && (gameMode == BeginningOfGame ||
6926 gameMode == MachinePlaysWhite ||
6927 gameMode == MachinePlaysBlack)) {
6928 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6930 if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
6931 // [HGM] book: if program might be playing, let it use book
6932 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6933 first.maybeThinking = TRUE;
6934 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
6935 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
6936 SendBoard(&first, currentMove+1);
6937 if(second.analyzing) {
6938 if(!second.useSetboard) SendToProgram("undo\n", &second);
6939 SendBoard(&second, currentMove+1);
6942 SendMoveToProgram(forwardMostMove-1, &first);
6943 if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
6945 if (currentMove == cmailOldMove + 1) {
6946 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6950 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6954 if(appData.testLegality)
6955 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6961 if (WhiteOnMove(currentMove)) {
6962 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6964 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6968 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6973 case MachinePlaysBlack:
6974 case MachinePlaysWhite:
6975 /* disable certain menu options while machine is thinking */
6976 SetMachineThinkingEnables();
6983 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6984 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6986 if(bookHit) { // [HGM] book: simulate book reply
6987 static char bookMove[MSG_SIZ]; // a bit generous?
6989 programStats.nodes = programStats.depth = programStats.time =
6990 programStats.score = programStats.got_only_move = 0;
6991 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6993 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6994 strcat(bookMove, bookHit);
6995 HandleMachineMove(bookMove, &first);
7001 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7003 typedef char Markers[BOARD_RANKS][BOARD_FILES];
7004 Markers *m = (Markers *) closure;
7005 if(rf == fromY && ff == fromX)
7006 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7007 || kind == WhiteCapturesEnPassant
7008 || kind == BlackCapturesEnPassant);
7009 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
7013 MarkTargetSquares (int clear)
7016 if(clear) // no reason to ever suppress clearing
7017 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
7018 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7019 !appData.testLegality || gameMode == EditPosition) return;
7022 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7023 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7024 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7026 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
7029 DrawPosition(FALSE, NULL);
7033 Explode (Board board, int fromX, int fromY, int toX, int toY)
7035 if(gameInfo.variant == VariantAtomic &&
7036 (board[toY][toX] != EmptySquare || // capture?
7037 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
7038 board[fromY][fromX] == BlackPawn )
7040 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7046 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7049 CanPromote (ChessSquare piece, int y)
7051 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7052 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7053 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
7054 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
7055 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7056 gameInfo.variant == VariantMakruk) return FALSE;
7057 return (piece == BlackPawn && y == 1 ||
7058 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
7059 piece == BlackLance && y == 1 ||
7060 piece == WhiteLance && y == BOARD_HEIGHT-2 );
7064 LeftClick (ClickType clickType, int xPix, int yPix)
7067 Boolean saveAnimate;
7068 static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0;
7069 char promoChoice = NULLCHAR;
7071 static TimeMark lastClickTime, prevClickTime;
7073 if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7075 prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7077 if (clickType == Press) ErrorPopDown();
7079 x = EventToSquare(xPix, BOARD_WIDTH);
7080 y = EventToSquare(yPix, BOARD_HEIGHT);
7081 if (!flipView && y >= 0) {
7082 y = BOARD_HEIGHT - 1 - y;
7084 if (flipView && x >= 0) {
7085 x = BOARD_WIDTH - 1 - x;
7088 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7089 defaultPromoChoice = promoSweep;
7090 promoSweep = EmptySquare; // terminate sweep
7091 promoDefaultAltered = TRUE;
7092 if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7095 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7096 if(clickType == Release) return; // ignore upclick of click-click destination
7097 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7098 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7099 if(gameInfo.holdingsWidth &&
7100 (WhiteOnMove(currentMove)
7101 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7102 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7103 // click in right holdings, for determining promotion piece
7104 ChessSquare p = boards[currentMove][y][x];
7105 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7106 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7107 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7108 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7113 DrawPosition(FALSE, boards[currentMove]);
7117 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7118 if(clickType == Press
7119 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7120 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7121 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7124 if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7125 // could be static click on premove from-square: abort premove
7127 ClearPremoveHighlights();
7130 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7131 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7133 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7134 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7135 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7136 defaultPromoChoice = DefaultPromoChoice(side);
7139 autoQueen = appData.alwaysPromoteToQueen;
7143 gatingPiece = EmptySquare;
7144 if (clickType != Press) {
7145 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7146 DragPieceEnd(xPix, yPix); dragging = 0;
7147 DrawPosition(FALSE, NULL);
7151 doubleClick = FALSE;
7152 if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7153 doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7155 fromX = x; fromY = y; toX = toY = -1;
7156 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7157 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7158 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7160 if (OKToStartUserMove(fromX, fromY)) {
7162 MarkTargetSquares(0);
7163 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7164 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7165 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7166 promoSweep = defaultPromoChoice;
7167 selectFlag = 0; lastX = xPix; lastY = yPix;
7168 Sweep(0); // Pawn that is going to promote: preview promotion piece
7169 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7171 if (appData.highlightDragging) {
7172 SetHighlights(fromX, fromY, -1, -1);
7176 } else fromX = fromY = -1;
7182 if (clickType == Press && gameMode != EditPosition) {
7187 // ignore off-board to clicks
7188 if(y < 0 || x < 0) return;
7190 /* Check if clicking again on the same color piece */
7191 fromP = boards[currentMove][fromY][fromX];
7192 toP = boards[currentMove][y][x];
7193 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
7194 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
7195 WhitePawn <= toP && toP <= WhiteKing &&
7196 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7197 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7198 (BlackPawn <= fromP && fromP <= BlackKing &&
7199 BlackPawn <= toP && toP <= BlackKing &&
7200 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7201 !(fromP == BlackKing && toP == BlackRook && frc))) {
7202 /* Clicked again on same color piece -- changed his mind */
7203 second = (x == fromX && y == fromY);
7204 if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7205 second = FALSE; // first double-click rather than scond click
7206 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7208 promoDefaultAltered = FALSE;
7209 MarkTargetSquares(1);
7210 if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
7211 if (appData.highlightDragging) {
7212 SetHighlights(x, y, -1, -1);
7216 if (OKToStartUserMove(x, y)) {
7217 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7218 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7219 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7220 gatingPiece = boards[currentMove][fromY][fromX];
7221 else gatingPiece = doubleClick ? fromP : EmptySquare;
7223 fromY = y; dragging = 1;
7224 MarkTargetSquares(0);
7225 DragPieceBegin(xPix, yPix, FALSE);
7226 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7227 promoSweep = defaultPromoChoice;
7228 selectFlag = 0; lastX = xPix; lastY = yPix;
7229 Sweep(0); // Pawn that is going to promote: preview promotion piece
7233 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7236 // ignore clicks on holdings
7237 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7240 if (clickType == Release && x == fromX && y == fromY) {
7241 DragPieceEnd(xPix, yPix); dragging = 0;
7243 // a deferred attempt to click-click move an empty square on top of a piece
7244 boards[currentMove][y][x] = EmptySquare;
7246 DrawPosition(FALSE, boards[currentMove]);
7247 fromX = fromY = -1; clearFlag = 0;
7250 if (appData.animateDragging) {
7251 /* Undo animation damage if any */
7252 DrawPosition(FALSE, NULL);
7254 if (second || sweepSelecting) {
7255 /* Second up/down in same square; just abort move */
7256 if(sweepSelecting) DrawPosition(FALSE, boards[currentMove]);
7257 second = sweepSelecting = 0;
7259 gatingPiece = EmptySquare;
7260 MarkTargetSquares(1);
7263 ClearPremoveHighlights();
7265 /* First upclick in same square; start click-click mode */
7266 SetHighlights(x, y, -1, -1);
7273 /* we now have a different from- and (possibly off-board) to-square */
7274 /* Completed move */
7275 if(!sweepSelecting) {
7278 } else sweepSelecting = 0; // this must be the up-click corresponding to the down-click that started the sweep
7280 saveAnimate = appData.animate;
7281 if (clickType == Press) {
7282 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7283 // must be Edit Position mode with empty-square selected
7284 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7285 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7288 if(HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7289 if(appData.sweepSelect) {
7290 ChessSquare piece = boards[currentMove][fromY][fromX];
7291 promoSweep = defaultPromoChoice;
7292 if(PieceToChar(PROMOTED piece) == '+') promoSweep = PROMOTED piece;
7293 selectFlag = 0; lastX = xPix; lastY = yPix;
7294 Sweep(0); // Pawn that is going to promote: preview promotion piece
7296 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7297 MarkTargetSquares(1);
7299 return; // promo popup appears on up-click
7301 /* Finish clickclick move */
7302 if (appData.animate || appData.highlightLastMove) {
7303 SetHighlights(fromX, fromY, toX, toY);
7309 // [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
7310 /* Finish drag move */
7311 if (appData.highlightLastMove) {
7312 SetHighlights(fromX, fromY, toX, toY);
7317 DragPieceEnd(xPix, yPix); dragging = 0;
7318 /* Don't animate move and drag both */
7319 appData.animate = FALSE;
7322 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7323 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7324 ChessSquare piece = boards[currentMove][fromY][fromX];
7325 if(gameMode == EditPosition && piece != EmptySquare &&
7326 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7329 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7330 n = PieceToNumber(piece - (int)BlackPawn);
7331 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7332 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7333 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7335 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7336 n = PieceToNumber(piece);
7337 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7338 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7339 boards[currentMove][n][BOARD_WIDTH-2]++;
7341 boards[currentMove][fromY][fromX] = EmptySquare;
7345 MarkTargetSquares(1);
7346 DrawPosition(TRUE, boards[currentMove]);
7350 // off-board moves should not be highlighted
7351 if(x < 0 || y < 0) ClearHighlights();
7353 if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7355 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7356 SetHighlights(fromX, fromY, toX, toY);
7357 MarkTargetSquares(1);
7358 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7359 // [HGM] super: promotion to captured piece selected from holdings
7360 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7361 promotionChoice = TRUE;
7362 // kludge follows to temporarily execute move on display, without promoting yet
7363 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7364 boards[currentMove][toY][toX] = p;
7365 DrawPosition(FALSE, boards[currentMove]);
7366 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7367 boards[currentMove][toY][toX] = q;
7368 DisplayMessage("Click in holdings to choose piece", "");
7373 int oldMove = currentMove;
7374 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7375 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7376 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7377 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7378 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7379 DrawPosition(TRUE, boards[currentMove]);
7380 MarkTargetSquares(1);
7383 appData.animate = saveAnimate;
7384 if (appData.animate || appData.animateDragging) {
7385 /* Undo animation damage if needed */
7386 DrawPosition(FALSE, NULL);
7391 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7392 { // front-end-free part taken out of PieceMenuPopup
7393 int whichMenu; int xSqr, ySqr;
7395 if(seekGraphUp) { // [HGM] seekgraph
7396 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7397 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7401 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7402 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7403 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7404 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7405 if(action == Press) {
7406 originalFlip = flipView;
7407 flipView = !flipView; // temporarily flip board to see game from partners perspective
7408 DrawPosition(TRUE, partnerBoard);
7409 DisplayMessage(partnerStatus, "");
7411 } else if(action == Release) {
7412 flipView = originalFlip;
7413 DrawPosition(TRUE, boards[currentMove]);
7419 xSqr = EventToSquare(x, BOARD_WIDTH);
7420 ySqr = EventToSquare(y, BOARD_HEIGHT);
7421 if (action == Release) {
7422 if(pieceSweep != EmptySquare) {
7423 EditPositionMenuEvent(pieceSweep, toX, toY);
7424 pieceSweep = EmptySquare;
7425 } else UnLoadPV(); // [HGM] pv
7427 if (action != Press) return -2; // return code to be ignored
7430 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7432 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7433 if (xSqr < 0 || ySqr < 0) return -1;
7434 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7435 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7436 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7437 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7441 if(!appData.icsEngineAnalyze) return -1;
7442 case IcsPlayingWhite:
7443 case IcsPlayingBlack:
7444 if(!appData.zippyPlay) goto noZip;
7447 case MachinePlaysWhite:
7448 case MachinePlaysBlack:
7449 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7450 if (!appData.dropMenu) {
7452 return 2; // flag front-end to grab mouse events
7454 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7455 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7458 if (xSqr < 0 || ySqr < 0) return -1;
7459 if (!appData.dropMenu || appData.testLegality &&
7460 gameInfo.variant != VariantBughouse &&
7461 gameInfo.variant != VariantCrazyhouse) return -1;
7462 whichMenu = 1; // drop menu
7468 if (((*fromX = xSqr) < 0) ||
7469 ((*fromY = ySqr) < 0)) {
7470 *fromX = *fromY = -1;
7474 *fromX = BOARD_WIDTH - 1 - *fromX;
7476 *fromY = BOARD_HEIGHT - 1 - *fromY;
7482 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7484 // char * hint = lastHint;
7485 FrontEndProgramStats stats;
7487 stats.which = cps == &first ? 0 : 1;
7488 stats.depth = cpstats->depth;
7489 stats.nodes = cpstats->nodes;
7490 stats.score = cpstats->score;
7491 stats.time = cpstats->time;
7492 stats.pv = cpstats->movelist;
7493 stats.hint = lastHint;
7494 stats.an_move_index = 0;
7495 stats.an_move_count = 0;
7497 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7498 stats.hint = cpstats->move_name;
7499 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7500 stats.an_move_count = cpstats->nr_moves;
7503 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
7505 SetProgramStats( &stats );
7509 ClearEngineOutputPane (int which)
7511 static FrontEndProgramStats dummyStats;
7512 dummyStats.which = which;
7513 dummyStats.pv = "#";
7514 SetProgramStats( &dummyStats );
7517 #define MAXPLAYERS 500
7520 TourneyStandings (int display)
7522 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7523 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7524 char result, *p, *names[MAXPLAYERS];
7526 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7527 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7528 names[0] = p = strdup(appData.participants);
7529 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7531 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7533 while(result = appData.results[nr]) {
7534 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7535 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7536 wScore = bScore = 0;
7538 case '+': wScore = 2; break;
7539 case '-': bScore = 2; break;
7540 case '=': wScore = bScore = 1; break;
7542 case '*': return strdup("busy"); // tourney not finished
7550 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7551 for(w=0; w<nPlayers; w++) {
7553 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7554 ranking[w] = b; points[w] = bScore; score[b] = -2;
7556 p = malloc(nPlayers*34+1);
7557 for(w=0; w<nPlayers && w<display; w++)
7558 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7564 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7565 { // count all piece types
7567 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7568 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7569 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7572 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7573 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7574 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7575 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7576 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7577 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7582 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7584 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7585 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7587 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7588 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7589 if(myPawns == 2 && nMine == 3) // KPP
7590 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7591 if(myPawns == 1 && nMine == 2) // KP
7592 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7593 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7594 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7595 if(myPawns) return FALSE;
7596 if(pCnt[WhiteRook+side])
7597 return pCnt[BlackRook-side] ||
7598 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7599 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7600 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7601 if(pCnt[WhiteCannon+side]) {
7602 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7603 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7605 if(pCnt[WhiteKnight+side])
7606 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7611 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7613 VariantClass v = gameInfo.variant;
7615 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7616 if(v == VariantShatranj) return TRUE; // always winnable through baring
7617 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7618 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7620 if(v == VariantXiangqi) {
7621 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7623 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7624 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7625 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7626 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7627 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7628 if(stale) // we have at least one last-rank P plus perhaps C
7629 return majors // KPKX
7630 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7632 return pCnt[WhiteFerz+side] // KCAK
7633 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7634 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7635 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7637 } else if(v == VariantKnightmate) {
7638 if(nMine == 1) return FALSE;
7639 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
7640 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7641 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7643 if(nMine == 1) return FALSE; // bare King
7644 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
7645 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7646 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7647 // by now we have King + 1 piece (or multiple Bishops on the same color)
7648 if(pCnt[WhiteKnight+side])
7649 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7650 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7651 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7653 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7654 if(pCnt[WhiteAlfil+side])
7655 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7656 if(pCnt[WhiteWazir+side])
7657 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7664 CompareWithRights (Board b1, Board b2)
7667 if(!CompareBoards(b1, b2)) return FALSE;
7668 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
7669 /* compare castling rights */
7670 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
7671 rights++; /* King lost rights, while rook still had them */
7672 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
7673 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
7674 rights++; /* but at least one rook lost them */
7676 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
7678 if( b1[CASTLING][5] != NoRights ) {
7679 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
7686 Adjudicate (ChessProgramState *cps)
7687 { // [HGM] some adjudications useful with buggy engines
7688 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7689 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7690 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7691 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7692 int k, drop, count = 0; static int bare = 1;
7693 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7694 Boolean canAdjudicate = !appData.icsActive;
7696 // most tests only when we understand the game, i.e. legality-checking on
7697 if( appData.testLegality )
7698 { /* [HGM] Some more adjudications for obstinate engines */
7699 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7700 static int moveCount = 6;
7702 char *reason = NULL;
7704 /* Count what is on board. */
7705 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7707 /* Some material-based adjudications that have to be made before stalemate test */
7708 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7709 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7710 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7711 if(canAdjudicate && appData.checkMates) {
7713 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7714 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7715 "Xboard adjudication: King destroyed", GE_XBOARD );
7720 /* Bare King in Shatranj (loses) or Losers (wins) */
7721 if( nrW == 1 || nrB == 1) {
7722 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7723 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7724 if(canAdjudicate && appData.checkMates) {
7726 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7727 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7728 "Xboard adjudication: Bare king", GE_XBOARD );
7732 if( gameInfo.variant == VariantShatranj && --bare < 0)
7734 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7735 if(canAdjudicate && appData.checkMates) {
7736 /* but only adjudicate if adjudication enabled */
7738 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7739 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7740 "Xboard adjudication: Bare king", GE_XBOARD );
7747 // don't wait for engine to announce game end if we can judge ourselves
7748 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7750 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7751 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7752 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7753 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7756 reason = "Xboard adjudication: 3rd check";
7757 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7767 reason = "Xboard adjudication: Stalemate";
7768 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7769 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7770 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7771 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7772 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7773 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7774 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7775 EP_CHECKMATE : EP_WINS);
7776 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
7777 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7781 reason = "Xboard adjudication: Checkmate";
7782 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7783 if(gameInfo.variant == VariantShogi) {
7784 if(forwardMostMove > backwardMostMove
7785 && moveList[forwardMostMove-1][1] == '@'
7786 && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
7787 reason = "XBoard adjudication: pawn-drop mate";
7788 boards[forwardMostMove][EP_STATUS] = EP_WINS;
7794 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7796 result = GameIsDrawn; break;
7798 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7800 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7804 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7806 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7807 GameEnds( result, reason, GE_XBOARD );
7811 /* Next absolutely insufficient mating material. */
7812 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7813 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7814 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7816 /* always flag draws, for judging claims */
7817 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7819 if(canAdjudicate && appData.materialDraws) {
7820 /* but only adjudicate them if adjudication enabled */
7821 if(engineOpponent) {
7822 SendToProgram("force\n", engineOpponent); // suppress reply
7823 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7825 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7830 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7831 if(gameInfo.variant == VariantXiangqi ?
7832 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7834 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7835 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7836 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7837 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7839 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7840 { /* if the first 3 moves do not show a tactical win, declare draw */
7841 if(engineOpponent) {
7842 SendToProgram("force\n", engineOpponent); // suppress reply
7843 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7845 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7848 } else moveCount = 6;
7851 // Repetition draws and 50-move rule can be applied independently of legality testing
7853 /* Check for rep-draws */
7855 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
7856 && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
7857 for(k = forwardMostMove-2;
7858 k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
7859 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7860 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
7863 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7864 /* compare castling rights */
7865 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7866 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7867 rights++; /* King lost rights, while rook still had them */
7868 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7869 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7870 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7871 rights++; /* but at least one rook lost them */
7873 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7874 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7876 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7877 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7878 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7881 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7882 && appData.drawRepeats > 1) {
7883 /* adjudicate after user-specified nr of repeats */
7884 int result = GameIsDrawn;
7885 char *details = "XBoard adjudication: repetition draw";
7886 if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
7887 // [HGM] xiangqi: check for forbidden perpetuals
7888 int m, ourPerpetual = 1, hisPerpetual = 1;
7889 for(m=forwardMostMove; m>k; m-=2) {
7890 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7891 ourPerpetual = 0; // the current mover did not always check
7892 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7893 hisPerpetual = 0; // the opponent did not always check
7895 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7896 ourPerpetual, hisPerpetual);
7897 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7898 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7899 details = "Xboard adjudication: perpetual checking";
7901 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7902 break; // (or we would have caught him before). Abort repetition-checking loop.
7904 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
7905 if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
7907 details = "Xboard adjudication: repetition";
7909 } else // it must be XQ
7910 // Now check for perpetual chases
7911 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7912 hisPerpetual = PerpetualChase(k, forwardMostMove);
7913 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7914 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7915 static char resdet[MSG_SIZ];
7916 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7918 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
7920 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7921 break; // Abort repetition-checking loop.
7923 // if neither of us is checking or chasing all the time, or both are, it is draw
7925 if(engineOpponent) {
7926 SendToProgram("force\n", engineOpponent); // suppress reply
7927 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7929 GameEnds( result, details, GE_XBOARD );
7932 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7933 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7937 /* Now we test for 50-move draws. Determine ply count */
7938 count = forwardMostMove;
7939 /* look for last irreversble move */
7940 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7942 /* if we hit starting position, add initial plies */
7943 if( count == backwardMostMove )
7944 count -= initialRulePlies;
7945 count = forwardMostMove - count;
7946 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7947 // adjust reversible move counter for checks in Xiangqi
7948 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7949 if(i < backwardMostMove) i = backwardMostMove;
7950 while(i <= forwardMostMove) {
7951 lastCheck = inCheck; // check evasion does not count
7952 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7953 if(inCheck || lastCheck) count--; // check does not count
7958 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7959 /* this is used to judge if draw claims are legal */
7960 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7961 if(engineOpponent) {
7962 SendToProgram("force\n", engineOpponent); // suppress reply
7963 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7965 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7969 /* if draw offer is pending, treat it as a draw claim
7970 * when draw condition present, to allow engines a way to
7971 * claim draws before making their move to avoid a race
7972 * condition occurring after their move
7974 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7976 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7977 p = "Draw claim: 50-move rule";
7978 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7979 p = "Draw claim: 3-fold repetition";
7980 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7981 p = "Draw claim: insufficient mating material";
7982 if( p != NULL && canAdjudicate) {
7983 if(engineOpponent) {
7984 SendToProgram("force\n", engineOpponent); // suppress reply
7985 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7987 GameEnds( GameIsDrawn, p, GE_XBOARD );
7992 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7993 if(engineOpponent) {
7994 SendToProgram("force\n", engineOpponent); // suppress reply
7995 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7997 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
8004 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8005 { // [HGM] book: this routine intercepts moves to simulate book replies
8006 char *bookHit = NULL;
8008 //first determine if the incoming move brings opponent into his book
8009 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8010 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8011 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8012 if(bookHit != NULL && !cps->bookSuspend) {
8013 // make sure opponent is not going to reply after receiving move to book position
8014 SendToProgram("force\n", cps);
8015 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8017 if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
8018 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8019 // now arrange restart after book miss
8021 // after a book hit we never send 'go', and the code after the call to this routine
8022 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8023 char buf[MSG_SIZ], *move = bookHit;
8025 int fromX, fromY, toX, toY;
8029 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8030 &fromX, &fromY, &toX, &toY, &promoChar)) {
8031 (void) CoordsToAlgebraic(boards[forwardMostMove],
8032 PosFlags(forwardMostMove),
8033 fromY, fromX, toY, toX, promoChar, move);
8035 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8039 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8040 SendToProgram(buf, cps);
8041 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8042 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8043 SendToProgram("go\n", cps);
8044 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8045 } else { // 'go' might be sent based on 'firstMove' after this routine returns
8046 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8047 SendToProgram("go\n", cps);
8048 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8050 return bookHit; // notify caller of hit, so it can take action to send move to opponent
8054 LoadError (char *errmess, ChessProgramState *cps)
8055 { // unloads engine and switches back to -ncp mode if it was first
8056 if(cps->initDone) return FALSE;
8057 cps->isr = NULL; // this should suppress further error popups from breaking pipes
8058 DestroyChildProcess(cps->pr, 9 ); // just to be sure
8061 appData.noChessProgram = TRUE;
8062 gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8063 gameMode = BeginningOfGame; ModeHighlight();
8066 if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8067 DisplayMessage("", ""); // erase waiting message
8068 if(errmess) DisplayError(errmess, 0); // announce reason, if given
8073 ChessProgramState *savedState;
8075 DeferredBookMove (void)
8077 if(savedState->lastPing != savedState->lastPong)
8078 ScheduleDelayedEvent(DeferredBookMove, 10);
8080 HandleMachineMove(savedMessage, savedState);
8083 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8084 static ChessProgramState *stalledEngine;
8085 static char stashedInputMove[MSG_SIZ];
8088 HandleMachineMove (char *message, ChessProgramState *cps)
8090 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8091 char realname[MSG_SIZ];
8092 int fromX, fromY, toX, toY;
8096 int machineWhite, oldError;
8099 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8100 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8101 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8102 DisplayError(_("Invalid pairing from pairing engine"), 0);
8105 pairingReceived = 1;
8107 return; // Skim the pairing messages here.
8110 oldError = cps->userError; cps->userError = 0;
8112 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8114 * Kludge to ignore BEL characters
8116 while (*message == '\007') message++;
8119 * [HGM] engine debug message: ignore lines starting with '#' character
8121 if(cps->debug && *message == '#') return;
8124 * Look for book output
8126 if (cps == &first && bookRequested) {
8127 if (message[0] == '\t' || message[0] == ' ') {
8128 /* Part of the book output is here; append it */
8129 strcat(bookOutput, message);
8130 strcat(bookOutput, " \n");
8132 } else if (bookOutput[0] != NULLCHAR) {
8133 /* All of book output has arrived; display it */
8134 char *p = bookOutput;
8135 while (*p != NULLCHAR) {
8136 if (*p == '\t') *p = ' ';
8139 DisplayInformation(bookOutput);
8140 bookRequested = FALSE;
8141 /* Fall through to parse the current output */
8146 * Look for machine move.
8148 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8149 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8151 if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8152 if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8153 safeStrCpy(stashedInputMove, message, MSG_SIZ);
8154 stalledEngine = cps;
8155 if(appData.ponderNextMove) { // bring opponent out of ponder
8156 if(gameMode == TwoMachinesPlay) {
8157 if(cps->other->pause)
8158 PauseEngine(cps->other);
8160 SendToProgram("easy\n", cps->other);
8167 /* This method is only useful on engines that support ping */
8168 if (cps->lastPing != cps->lastPong) {
8169 if (gameMode == BeginningOfGame) {
8170 /* Extra move from before last new; ignore */
8171 if (appData.debugMode) {
8172 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8175 if (appData.debugMode) {
8176 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8177 cps->which, gameMode);
8180 SendToProgram("undo\n", cps);
8186 case BeginningOfGame:
8187 /* Extra move from before last reset; ignore */
8188 if (appData.debugMode) {
8189 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8196 /* Extra move after we tried to stop. The mode test is
8197 not a reliable way of detecting this problem, but it's
8198 the best we can do on engines that don't support ping.
8200 if (appData.debugMode) {
8201 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8202 cps->which, gameMode);
8204 SendToProgram("undo\n", cps);
8207 case MachinePlaysWhite:
8208 case IcsPlayingWhite:
8209 machineWhite = TRUE;
8212 case MachinePlaysBlack:
8213 case IcsPlayingBlack:
8214 machineWhite = FALSE;
8217 case TwoMachinesPlay:
8218 machineWhite = (cps->twoMachinesColor[0] == 'w');
8221 if (WhiteOnMove(forwardMostMove) != machineWhite) {
8222 if (appData.debugMode) {
8224 "Ignoring move out of turn by %s, gameMode %d"
8225 ", forwardMost %d\n",
8226 cps->which, gameMode, forwardMostMove);
8231 if(cps->alphaRank) AlphaRank(machineMove, 4);
8232 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
8233 &fromX, &fromY, &toX, &toY, &promoChar)) {
8234 /* Machine move could not be parsed; ignore it. */
8235 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
8236 machineMove, _(cps->which));
8237 DisplayMoveError(buf1);
8238 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
8239 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
8240 if (gameMode == TwoMachinesPlay) {
8241 GameEnds(machineWhite ? BlackWins : WhiteWins,
8247 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
8248 /* So we have to redo legality test with true e.p. status here, */
8249 /* to make sure an illegal e.p. capture does not slip through, */
8250 /* to cause a forfeit on a justified illegal-move complaint */
8251 /* of the opponent. */
8252 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
8254 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
8255 fromY, fromX, toY, toX, promoChar);
8256 if(moveType == IllegalMove) {
8257 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
8258 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
8259 GameEnds(machineWhite ? BlackWins : WhiteWins,
8262 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
8263 /* [HGM] Kludge to handle engines that send FRC-style castling
8264 when they shouldn't (like TSCP-Gothic) */
8266 case WhiteASideCastleFR:
8267 case BlackASideCastleFR:
8269 currentMoveString[2]++;
8271 case WhiteHSideCastleFR:
8272 case BlackHSideCastleFR:
8274 currentMoveString[2]--;
8276 default: ; // nothing to do, but suppresses warning of pedantic compilers
8279 hintRequested = FALSE;
8280 lastHint[0] = NULLCHAR;
8281 bookRequested = FALSE;
8282 /* Program may be pondering now */
8283 cps->maybeThinking = TRUE;
8284 if (cps->sendTime == 2) cps->sendTime = 1;
8285 if (cps->offeredDraw) cps->offeredDraw--;
8287 /* [AS] Save move info*/
8288 pvInfoList[ forwardMostMove ].score = programStats.score;
8289 pvInfoList[ forwardMostMove ].depth = programStats.depth;
8290 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
8292 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
8294 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
8295 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
8298 while( count < adjudicateLossPlies ) {
8299 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
8302 score = -score; /* Flip score for winning side */
8305 if( score > adjudicateLossThreshold ) {
8312 if( count >= adjudicateLossPlies ) {
8313 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8315 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8316 "Xboard adjudication",
8323 if(Adjudicate(cps)) {
8324 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8325 return; // [HGM] adjudicate: for all automatic game ends
8329 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8331 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8332 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8334 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8336 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8338 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8339 char buf[3*MSG_SIZ];
8341 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8342 programStats.score / 100.,
8344 programStats.time / 100.,
8345 (unsigned int)programStats.nodes,
8346 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8347 programStats.movelist);
8349 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
8354 /* [AS] Clear stats for next move */
8355 ClearProgramStats();
8356 thinkOutput[0] = NULLCHAR;
8357 hiddenThinkOutputState = 0;
8360 if (gameMode == TwoMachinesPlay) {
8361 /* [HGM] relaying draw offers moved to after reception of move */
8362 /* and interpreting offer as claim if it brings draw condition */
8363 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8364 SendToProgram("draw\n", cps->other);
8366 if (cps->other->sendTime) {
8367 SendTimeRemaining(cps->other,
8368 cps->other->twoMachinesColor[0] == 'w');
8370 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8371 if (firstMove && !bookHit) {
8373 if (cps->other->useColors) {
8374 SendToProgram(cps->other->twoMachinesColor, cps->other);
8376 SendToProgram("go\n", cps->other);
8378 cps->other->maybeThinking = TRUE;
8381 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8383 if (!pausing && appData.ringBellAfterMoves) {
8388 * Reenable menu items that were disabled while
8389 * machine was thinking
8391 if (gameMode != TwoMachinesPlay)
8392 SetUserThinkingEnables();
8394 // [HGM] book: after book hit opponent has received move and is now in force mode
8395 // force the book reply into it, and then fake that it outputted this move by jumping
8396 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8398 static char bookMove[MSG_SIZ]; // a bit generous?
8400 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8401 strcat(bookMove, bookHit);
8404 programStats.nodes = programStats.depth = programStats.time =
8405 programStats.score = programStats.got_only_move = 0;
8406 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8408 if(cps->lastPing != cps->lastPong) {
8409 savedMessage = message; // args for deferred call
8411 ScheduleDelayedEvent(DeferredBookMove, 10);
8420 /* Set special modes for chess engines. Later something general
8421 * could be added here; for now there is just one kludge feature,
8422 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8423 * when "xboard" is given as an interactive command.
8425 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8426 cps->useSigint = FALSE;
8427 cps->useSigterm = FALSE;
8429 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8430 ParseFeatures(message+8, cps);
8431 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8434 if (!strncmp(message, "setup ", 6) &&
8435 (!appData.testLegality || gameInfo.variant == VariantFairy || NonStandardBoardSize())
8436 ) { // [HGM] allow first engine to define opening position
8437 int dummy, s=6; char buf[MSG_SIZ];
8438 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8439 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8440 if(startedFromSetupPosition) return;
8441 if(sscanf(message+s, "%dx%d+%d", &dummy, &dummy, &dummy) == 3) while(message[s] && message[s++] != ' '); // for compatibility with Alien Edition
8442 ParseFEN(boards[0], &dummy, message+s);
8443 DrawPosition(TRUE, boards[0]);
8444 startedFromSetupPosition = TRUE;
8447 /* [HGM] Allow engine to set up a position. Don't ask me why one would
8448 * want this, I was asked to put it in, and obliged.
8450 if (!strncmp(message, "setboard ", 9)) {
8451 Board initial_position;
8453 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8455 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
8456 DisplayError(_("Bad FEN received from engine"), 0);
8460 CopyBoard(boards[0], initial_position);
8461 initialRulePlies = FENrulePlies;
8462 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8463 else gameMode = MachinePlaysBlack;
8464 DrawPosition(FALSE, boards[currentMove]);
8470 * Look for communication commands
8472 if (!strncmp(message, "telluser ", 9)) {
8473 if(message[9] == '\\' && message[10] == '\\')
8474 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8476 DisplayNote(message + 9);
8479 if (!strncmp(message, "tellusererror ", 14)) {
8481 if(message[14] == '\\' && message[15] == '\\')
8482 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8484 DisplayError(message + 14, 0);
8487 if (!strncmp(message, "tellopponent ", 13)) {
8488 if (appData.icsActive) {
8490 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8494 DisplayNote(message + 13);
8498 if (!strncmp(message, "tellothers ", 11)) {
8499 if (appData.icsActive) {
8501 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8504 } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
8507 if (!strncmp(message, "tellall ", 8)) {
8508 if (appData.icsActive) {
8510 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
8514 DisplayNote(message + 8);
8518 if (strncmp(message, "warning", 7) == 0) {
8519 /* Undocumented feature, use tellusererror in new code */
8520 DisplayError(message, 0);
8523 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
8524 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
8525 strcat(realname, " query");
8526 AskQuestion(realname, buf2, buf1, cps->pr);
8529 /* Commands from the engine directly to ICS. We don't allow these to be
8530 * sent until we are logged on. Crafty kibitzes have been known to
8531 * interfere with the login process.
8534 if (!strncmp(message, "tellics ", 8)) {
8535 SendToICS(message + 8);
8539 if (!strncmp(message, "tellicsnoalias ", 15)) {
8540 SendToICS(ics_prefix);
8541 SendToICS(message + 15);
8545 /* The following are for backward compatibility only */
8546 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
8547 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
8548 SendToICS(ics_prefix);
8554 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
8558 * If the move is illegal, cancel it and redraw the board.
8559 * Also deal with other error cases. Matching is rather loose
8560 * here to accommodate engines written before the spec.
8562 if (strncmp(message + 1, "llegal move", 11) == 0 ||
8563 strncmp(message, "Error", 5) == 0) {
8564 if (StrStr(message, "name") ||
8565 StrStr(message, "rating") || StrStr(message, "?") ||
8566 StrStr(message, "result") || StrStr(message, "board") ||
8567 StrStr(message, "bk") || StrStr(message, "computer") ||
8568 StrStr(message, "variant") || StrStr(message, "hint") ||
8569 StrStr(message, "random") || StrStr(message, "depth") ||
8570 StrStr(message, "accepted")) {
8573 if (StrStr(message, "protover")) {
8574 /* Program is responding to input, so it's apparently done
8575 initializing, and this error message indicates it is
8576 protocol version 1. So we don't need to wait any longer
8577 for it to initialize and send feature commands. */
8578 FeatureDone(cps, 1);
8579 cps->protocolVersion = 1;
8582 cps->maybeThinking = FALSE;
8584 if (StrStr(message, "draw")) {
8585 /* Program doesn't have "draw" command */
8586 cps->sendDrawOffers = 0;
8589 if (cps->sendTime != 1 &&
8590 (StrStr(message, "time") || StrStr(message, "otim"))) {
8591 /* Program apparently doesn't have "time" or "otim" command */
8595 if (StrStr(message, "analyze")) {
8596 cps->analysisSupport = FALSE;
8597 cps->analyzing = FALSE;
8598 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
8599 EditGameEvent(); // [HGM] try to preserve loaded game
8600 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
8601 DisplayError(buf2, 0);
8604 if (StrStr(message, "(no matching move)st")) {
8605 /* Special kludge for GNU Chess 4 only */
8606 cps->stKludge = TRUE;
8607 SendTimeControl(cps, movesPerSession, timeControl,
8608 timeIncrement, appData.searchDepth,
8612 if (StrStr(message, "(no matching move)sd")) {
8613 /* Special kludge for GNU Chess 4 only */
8614 cps->sdKludge = TRUE;
8615 SendTimeControl(cps, movesPerSession, timeControl,
8616 timeIncrement, appData.searchDepth,
8620 if (!StrStr(message, "llegal")) {
8623 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8624 gameMode == IcsIdle) return;
8625 if (forwardMostMove <= backwardMostMove) return;
8626 if (pausing) PauseEvent();
8627 if(appData.forceIllegal) {
8628 // [HGM] illegal: machine refused move; force position after move into it
8629 SendToProgram("force\n", cps);
8630 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
8631 // we have a real problem now, as SendBoard will use the a2a3 kludge
8632 // when black is to move, while there might be nothing on a2 or black
8633 // might already have the move. So send the board as if white has the move.
8634 // But first we must change the stm of the engine, as it refused the last move
8635 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
8636 if(WhiteOnMove(forwardMostMove)) {
8637 SendToProgram("a7a6\n", cps); // for the engine black still had the move
8638 SendBoard(cps, forwardMostMove); // kludgeless board
8640 SendToProgram("a2a3\n", cps); // for the engine white still had the move
8641 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8642 SendBoard(cps, forwardMostMove+1); // kludgeless board
8644 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
8645 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
8646 gameMode == TwoMachinesPlay)
8647 SendToProgram("go\n", cps);
8650 if (gameMode == PlayFromGameFile) {
8651 /* Stop reading this game file */
8652 gameMode = EditGame;
8655 /* [HGM] illegal-move claim should forfeit game when Xboard */
8656 /* only passes fully legal moves */
8657 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
8658 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
8659 "False illegal-move claim", GE_XBOARD );
8660 return; // do not take back move we tested as valid
8662 currentMove = forwardMostMove-1;
8663 DisplayMove(currentMove-1); /* before DisplayMoveError */
8664 SwitchClocks(forwardMostMove-1); // [HGM] race
8665 DisplayBothClocks();
8666 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
8667 parseList[currentMove], _(cps->which));
8668 DisplayMoveError(buf1);
8669 DrawPosition(FALSE, boards[currentMove]);
8671 SetUserThinkingEnables();
8674 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
8675 /* Program has a broken "time" command that
8676 outputs a string not ending in newline.
8682 * If chess program startup fails, exit with an error message.
8683 * Attempts to recover here are futile. [HGM] Well, we try anyway
8685 if ((StrStr(message, "unknown host") != NULL)
8686 || (StrStr(message, "No remote directory") != NULL)
8687 || (StrStr(message, "not found") != NULL)
8688 || (StrStr(message, "No such file") != NULL)
8689 || (StrStr(message, "can't alloc") != NULL)
8690 || (StrStr(message, "Permission denied") != NULL)) {
8692 cps->maybeThinking = FALSE;
8693 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
8694 _(cps->which), cps->program, cps->host, message);
8695 RemoveInputSource(cps->isr);
8696 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
8697 if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
8698 if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
8704 * Look for hint output
8706 if (sscanf(message, "Hint: %s", buf1) == 1) {
8707 if (cps == &first && hintRequested) {
8708 hintRequested = FALSE;
8709 if (ParseOneMove(buf1, forwardMostMove, &moveType,
8710 &fromX, &fromY, &toX, &toY, &promoChar)) {
8711 (void) CoordsToAlgebraic(boards[forwardMostMove],
8712 PosFlags(forwardMostMove),
8713 fromY, fromX, toY, toX, promoChar, buf1);
8714 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
8715 DisplayInformation(buf2);
8717 /* Hint move could not be parsed!? */
8718 snprintf(buf2, sizeof(buf2),
8719 _("Illegal hint move \"%s\"\nfrom %s chess program"),
8720 buf1, _(cps->which));
8721 DisplayError(buf2, 0);
8724 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
8730 * Ignore other messages if game is not in progress
8732 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8733 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
8736 * look for win, lose, draw, or draw offer
8738 if (strncmp(message, "1-0", 3) == 0) {
8739 char *p, *q, *r = "";
8740 p = strchr(message, '{');
8748 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8750 } else if (strncmp(message, "0-1", 3) == 0) {
8751 char *p, *q, *r = "";
8752 p = strchr(message, '{');
8760 /* Kludge for Arasan 4.1 bug */
8761 if (strcmp(r, "Black resigns") == 0) {
8762 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8765 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8767 } else if (strncmp(message, "1/2", 3) == 0) {
8768 char *p, *q, *r = "";
8769 p = strchr(message, '{');
8778 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8781 } else if (strncmp(message, "White resign", 12) == 0) {
8782 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8784 } else if (strncmp(message, "Black resign", 12) == 0) {
8785 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8787 } else if (strncmp(message, "White matches", 13) == 0 ||
8788 strncmp(message, "Black matches", 13) == 0 ) {
8789 /* [HGM] ignore GNUShogi noises */
8791 } else if (strncmp(message, "White", 5) == 0 &&
8792 message[5] != '(' &&
8793 StrStr(message, "Black") == NULL) {
8794 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8796 } else if (strncmp(message, "Black", 5) == 0 &&
8797 message[5] != '(') {
8798 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8800 } else if (strcmp(message, "resign") == 0 ||
8801 strcmp(message, "computer resigns") == 0) {
8803 case MachinePlaysBlack:
8804 case IcsPlayingBlack:
8805 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8807 case MachinePlaysWhite:
8808 case IcsPlayingWhite:
8809 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8811 case TwoMachinesPlay:
8812 if (cps->twoMachinesColor[0] == 'w')
8813 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8815 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8822 } else if (strncmp(message, "opponent mates", 14) == 0) {
8824 case MachinePlaysBlack:
8825 case IcsPlayingBlack:
8826 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8828 case MachinePlaysWhite:
8829 case IcsPlayingWhite:
8830 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8832 case TwoMachinesPlay:
8833 if (cps->twoMachinesColor[0] == 'w')
8834 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8836 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8843 } else if (strncmp(message, "computer mates", 14) == 0) {
8845 case MachinePlaysBlack:
8846 case IcsPlayingBlack:
8847 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8849 case MachinePlaysWhite:
8850 case IcsPlayingWhite:
8851 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8853 case TwoMachinesPlay:
8854 if (cps->twoMachinesColor[0] == 'w')
8855 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8857 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8864 } else if (strncmp(message, "checkmate", 9) == 0) {
8865 if (WhiteOnMove(forwardMostMove)) {
8866 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8868 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8871 } else if (strstr(message, "Draw") != NULL ||
8872 strstr(message, "game is a draw") != NULL) {
8873 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8875 } else if (strstr(message, "offer") != NULL &&
8876 strstr(message, "draw") != NULL) {
8878 if (appData.zippyPlay && first.initDone) {
8879 /* Relay offer to ICS */
8880 SendToICS(ics_prefix);
8881 SendToICS("draw\n");
8884 cps->offeredDraw = 2; /* valid until this engine moves twice */
8885 if (gameMode == TwoMachinesPlay) {
8886 if (cps->other->offeredDraw) {
8887 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8888 /* [HGM] in two-machine mode we delay relaying draw offer */
8889 /* until after we also have move, to see if it is really claim */
8891 } else if (gameMode == MachinePlaysWhite ||
8892 gameMode == MachinePlaysBlack) {
8893 if (userOfferedDraw) {
8894 DisplayInformation(_("Machine accepts your draw offer"));
8895 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8897 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8904 * Look for thinking output
8906 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8907 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8909 int plylev, mvleft, mvtot, curscore, time;
8910 char mvname[MOVE_LEN];
8914 int prefixHint = FALSE;
8915 mvname[0] = NULLCHAR;
8918 case MachinePlaysBlack:
8919 case IcsPlayingBlack:
8920 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8922 case MachinePlaysWhite:
8923 case IcsPlayingWhite:
8924 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8929 case IcsObserving: /* [DM] icsEngineAnalyze */
8930 if (!appData.icsEngineAnalyze) ignore = TRUE;
8932 case TwoMachinesPlay:
8933 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8943 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8945 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8946 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8948 if (plyext != ' ' && plyext != '\t') {
8952 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8953 if( cps->scoreIsAbsolute &&
8954 ( gameMode == MachinePlaysBlack ||
8955 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8956 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8957 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8958 !WhiteOnMove(currentMove)
8961 curscore = -curscore;
8964 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
8966 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
8969 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
8970 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
8971 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
8972 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
8973 if(f = fopen(buf, "w")) { // export PV to applicable PV file
8974 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
8976 } else DisplayError(_("failed writing PV"), 0);
8979 tempStats.depth = plylev;
8980 tempStats.nodes = nodes;
8981 tempStats.time = time;
8982 tempStats.score = curscore;
8983 tempStats.got_only_move = 0;
8985 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8988 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8989 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8990 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8991 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8992 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8993 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8994 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8995 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8998 /* Buffer overflow protection */
8999 if (pv[0] != NULLCHAR) {
9000 if (strlen(pv) >= sizeof(tempStats.movelist)
9001 && appData.debugMode) {
9003 "PV is too long; using the first %u bytes.\n",
9004 (unsigned) sizeof(tempStats.movelist) - 1);
9007 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9009 sprintf(tempStats.movelist, " no PV\n");
9012 if (tempStats.seen_stat) {
9013 tempStats.ok_to_send = 1;
9016 if (strchr(tempStats.movelist, '(') != NULL) {
9017 tempStats.line_is_book = 1;
9018 tempStats.nr_moves = 0;
9019 tempStats.moves_left = 0;
9021 tempStats.line_is_book = 0;
9024 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9025 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9027 SendProgramStatsToFrontend( cps, &tempStats );
9030 [AS] Protect the thinkOutput buffer from overflow... this
9031 is only useful if buf1 hasn't overflowed first!
9033 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
9035 (gameMode == TwoMachinesPlay ?
9036 ToUpper(cps->twoMachinesColor[0]) : ' '),
9037 ((double) curscore) / 100.0,
9038 prefixHint ? lastHint : "",
9039 prefixHint ? " " : "" );
9041 if( buf1[0] != NULLCHAR ) {
9042 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
9044 if( strlen(pv) > max_len ) {
9045 if( appData.debugMode) {
9046 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
9048 pv[max_len+1] = '\0';
9051 strcat( thinkOutput, pv);
9054 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
9055 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9056 DisplayMove(currentMove - 1);
9060 } else if ((p=StrStr(message, "(only move)")) != NULL) {
9061 /* crafty (9.25+) says "(only move) <move>"
9062 * if there is only 1 legal move
9064 sscanf(p, "(only move) %s", buf1);
9065 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
9066 sprintf(programStats.movelist, "%s (only move)", buf1);
9067 programStats.depth = 1;
9068 programStats.nr_moves = 1;
9069 programStats.moves_left = 1;
9070 programStats.nodes = 1;
9071 programStats.time = 1;
9072 programStats.got_only_move = 1;
9074 /* Not really, but we also use this member to
9075 mean "line isn't going to change" (Crafty
9076 isn't searching, so stats won't change) */
9077 programStats.line_is_book = 1;
9079 SendProgramStatsToFrontend( cps, &programStats );
9081 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9082 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9083 DisplayMove(currentMove - 1);
9086 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
9087 &time, &nodes, &plylev, &mvleft,
9088 &mvtot, mvname) >= 5) {
9089 /* The stat01: line is from Crafty (9.29+) in response
9090 to the "." command */
9091 programStats.seen_stat = 1;
9092 cps->maybeThinking = TRUE;
9094 if (programStats.got_only_move || !appData.periodicUpdates)
9097 programStats.depth = plylev;
9098 programStats.time = time;
9099 programStats.nodes = nodes;
9100 programStats.moves_left = mvleft;
9101 programStats.nr_moves = mvtot;
9102 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
9103 programStats.ok_to_send = 1;
9104 programStats.movelist[0] = '\0';
9106 SendProgramStatsToFrontend( cps, &programStats );
9110 } else if (strncmp(message,"++",2) == 0) {
9111 /* Crafty 9.29+ outputs this */
9112 programStats.got_fail = 2;
9115 } else if (strncmp(message,"--",2) == 0) {
9116 /* Crafty 9.29+ outputs this */
9117 programStats.got_fail = 1;
9120 } else if (thinkOutput[0] != NULLCHAR &&
9121 strncmp(message, " ", 4) == 0) {
9122 unsigned message_len;
9125 while (*p && *p == ' ') p++;
9127 message_len = strlen( p );
9129 /* [AS] Avoid buffer overflow */
9130 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
9131 strcat(thinkOutput, " ");
9132 strcat(thinkOutput, p);
9135 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
9136 strcat(programStats.movelist, " ");
9137 strcat(programStats.movelist, p);
9140 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9141 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9142 DisplayMove(currentMove - 1);
9150 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9151 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
9153 ChessProgramStats cpstats;
9155 if (plyext != ' ' && plyext != '\t') {
9159 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9160 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
9161 curscore = -curscore;
9164 cpstats.depth = plylev;
9165 cpstats.nodes = nodes;
9166 cpstats.time = time;
9167 cpstats.score = curscore;
9168 cpstats.got_only_move = 0;
9169 cpstats.movelist[0] = '\0';
9171 if (buf1[0] != NULLCHAR) {
9172 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
9175 cpstats.ok_to_send = 0;
9176 cpstats.line_is_book = 0;
9177 cpstats.nr_moves = 0;
9178 cpstats.moves_left = 0;
9180 SendProgramStatsToFrontend( cps, &cpstats );
9187 /* Parse a game score from the character string "game", and
9188 record it as the history of the current game. The game
9189 score is NOT assumed to start from the standard position.
9190 The display is not updated in any way.
9193 ParseGameHistory (char *game)
9196 int fromX, fromY, toX, toY, boardIndex;
9201 if (appData.debugMode)
9202 fprintf(debugFP, "Parsing game history: %s\n", game);
9204 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
9205 gameInfo.site = StrSave(appData.icsHost);
9206 gameInfo.date = PGNDate();
9207 gameInfo.round = StrSave("-");
9209 /* Parse out names of players */
9210 while (*game == ' ') game++;
9212 while (*game != ' ') *p++ = *game++;
9214 gameInfo.white = StrSave(buf);
9215 while (*game == ' ') game++;
9217 while (*game != ' ' && *game != '\n') *p++ = *game++;
9219 gameInfo.black = StrSave(buf);
9222 boardIndex = blackPlaysFirst ? 1 : 0;
9225 yyboardindex = boardIndex;
9226 moveType = (ChessMove) Myylex();
9228 case IllegalMove: /* maybe suicide chess, etc. */
9229 if (appData.debugMode) {
9230 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
9231 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9232 setbuf(debugFP, NULL);
9234 case WhitePromotion:
9235 case BlackPromotion:
9236 case WhiteNonPromotion:
9237 case BlackNonPromotion:
9239 case WhiteCapturesEnPassant:
9240 case BlackCapturesEnPassant:
9241 case WhiteKingSideCastle:
9242 case WhiteQueenSideCastle:
9243 case BlackKingSideCastle:
9244 case BlackQueenSideCastle:
9245 case WhiteKingSideCastleWild:
9246 case WhiteQueenSideCastleWild:
9247 case BlackKingSideCastleWild:
9248 case BlackQueenSideCastleWild:
9250 case WhiteHSideCastleFR:
9251 case WhiteASideCastleFR:
9252 case BlackHSideCastleFR:
9253 case BlackASideCastleFR:
9255 fromX = currentMoveString[0] - AAA;
9256 fromY = currentMoveString[1] - ONE;
9257 toX = currentMoveString[2] - AAA;
9258 toY = currentMoveString[3] - ONE;
9259 promoChar = currentMoveString[4];
9263 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
9264 fromX = moveType == WhiteDrop ?
9265 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9266 (int) CharToPiece(ToLower(currentMoveString[0]));
9268 toX = currentMoveString[2] - AAA;
9269 toY = currentMoveString[3] - ONE;
9270 promoChar = NULLCHAR;
9274 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
9275 if (appData.debugMode) {
9276 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
9277 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9278 setbuf(debugFP, NULL);
9280 DisplayError(buf, 0);
9282 case ImpossibleMove:
9284 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
9285 if (appData.debugMode) {
9286 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
9287 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9288 setbuf(debugFP, NULL);
9290 DisplayError(buf, 0);
9293 if (boardIndex < backwardMostMove) {
9294 /* Oops, gap. How did that happen? */
9295 DisplayError(_("Gap in move list"), 0);
9298 backwardMostMove = blackPlaysFirst ? 1 : 0;
9299 if (boardIndex > forwardMostMove) {
9300 forwardMostMove = boardIndex;
9304 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
9305 strcat(parseList[boardIndex-1], " ");
9306 strcat(parseList[boardIndex-1], yy_text);
9318 case GameUnfinished:
9319 if (gameMode == IcsExamining) {
9320 if (boardIndex < backwardMostMove) {
9321 /* Oops, gap. How did that happen? */
9324 backwardMostMove = blackPlaysFirst ? 1 : 0;
9327 gameInfo.result = moveType;
9328 p = strchr(yy_text, '{');
9329 if (p == NULL) p = strchr(yy_text, '(');
9332 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9334 q = strchr(p, *p == '{' ? '}' : ')');
9335 if (q != NULL) *q = NULLCHAR;
9338 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9339 gameInfo.resultDetails = StrSave(p);
9342 if (boardIndex >= forwardMostMove &&
9343 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9344 backwardMostMove = blackPlaysFirst ? 1 : 0;
9347 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9348 fromY, fromX, toY, toX, promoChar,
9349 parseList[boardIndex]);
9350 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9351 /* currentMoveString is set as a side-effect of yylex */
9352 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9353 strcat(moveList[boardIndex], "\n");
9355 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9356 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9362 if(gameInfo.variant != VariantShogi)
9363 strcat(parseList[boardIndex - 1], "+");
9367 strcat(parseList[boardIndex - 1], "#");
9374 /* Apply a move to the given board */
9376 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9378 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9379 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
9381 /* [HGM] compute & store e.p. status and castling rights for new position */
9382 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9384 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9385 oldEP = (signed char)board[EP_STATUS];
9386 board[EP_STATUS] = EP_NONE;
9388 if (fromY == DROP_RANK) {
9390 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9391 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9394 piece = board[toY][toX] = (ChessSquare) fromX;
9398 if( board[toY][toX] != EmptySquare )
9399 board[EP_STATUS] = EP_CAPTURE;
9401 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9402 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9403 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9405 if( board[fromY][fromX] == WhitePawn ) {
9406 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9407 board[EP_STATUS] = EP_PAWN_MOVE;
9409 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9410 gameInfo.variant != VariantBerolina || toX < fromX)
9411 board[EP_STATUS] = toX | berolina;
9412 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9413 gameInfo.variant != VariantBerolina || toX > fromX)
9414 board[EP_STATUS] = toX;
9417 if( board[fromY][fromX] == BlackPawn ) {
9418 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9419 board[EP_STATUS] = EP_PAWN_MOVE;
9420 if( toY-fromY== -2) {
9421 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9422 gameInfo.variant != VariantBerolina || toX < fromX)
9423 board[EP_STATUS] = toX | berolina;
9424 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9425 gameInfo.variant != VariantBerolina || toX > fromX)
9426 board[EP_STATUS] = toX;
9430 for(i=0; i<nrCastlingRights; i++) {
9431 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9432 board[CASTLING][i] == toX && castlingRank[i] == toY
9433 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9436 if(gameInfo.variant == VariantSChess) { // update virginity
9437 if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
9438 if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
9439 if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
9440 if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
9443 if (fromX == toX && fromY == toY) return;
9445 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9446 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9447 if(gameInfo.variant == VariantKnightmate)
9448 king += (int) WhiteUnicorn - (int) WhiteKing;
9450 /* Code added by Tord: */
9451 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9452 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9453 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9454 board[fromY][fromX] = EmptySquare;
9455 board[toY][toX] = EmptySquare;
9456 if((toX > fromX) != (piece == WhiteRook)) {
9457 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9459 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9461 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9462 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9463 board[fromY][fromX] = EmptySquare;
9464 board[toY][toX] = EmptySquare;
9465 if((toX > fromX) != (piece == BlackRook)) {
9466 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9468 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9470 /* End of code added by Tord */
9472 } else if (board[fromY][fromX] == king
9473 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9474 && toY == fromY && toX > fromX+1) {
9475 board[fromY][fromX] = EmptySquare;
9476 board[toY][toX] = king;
9477 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9478 board[fromY][BOARD_RGHT-1] = EmptySquare;
9479 } else if (board[fromY][fromX] == king
9480 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9481 && toY == fromY && toX < fromX-1) {
9482 board[fromY][fromX] = EmptySquare;
9483 board[toY][toX] = king;
9484 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9485 board[fromY][BOARD_LEFT] = EmptySquare;
9486 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
9487 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9488 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
9490 /* white pawn promotion */
9491 board[toY][toX] = CharToPiece(ToUpper(promoChar));
9492 if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
9493 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9494 board[fromY][fromX] = EmptySquare;
9495 } else if ((fromY >= BOARD_HEIGHT>>1)
9496 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality)
9498 && gameInfo.variant != VariantXiangqi
9499 && gameInfo.variant != VariantBerolina
9500 && (board[fromY][fromX] == WhitePawn)
9501 && (board[toY][toX] == EmptySquare)) {
9502 board[fromY][fromX] = EmptySquare;
9503 board[toY][toX] = WhitePawn;
9504 captured = board[toY - 1][toX];
9505 board[toY - 1][toX] = EmptySquare;
9506 } else if ((fromY == BOARD_HEIGHT-4)
9508 && gameInfo.variant == VariantBerolina
9509 && (board[fromY][fromX] == WhitePawn)
9510 && (board[toY][toX] == EmptySquare)) {
9511 board[fromY][fromX] = EmptySquare;
9512 board[toY][toX] = WhitePawn;
9513 if(oldEP & EP_BEROLIN_A) {
9514 captured = board[fromY][fromX-1];
9515 board[fromY][fromX-1] = EmptySquare;
9516 }else{ captured = board[fromY][fromX+1];
9517 board[fromY][fromX+1] = EmptySquare;
9519 } else if (board[fromY][fromX] == king
9520 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9521 && toY == fromY && toX > fromX+1) {
9522 board[fromY][fromX] = EmptySquare;
9523 board[toY][toX] = king;
9524 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9525 board[fromY][BOARD_RGHT-1] = EmptySquare;
9526 } else if (board[fromY][fromX] == king
9527 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9528 && toY == fromY && toX < fromX-1) {
9529 board[fromY][fromX] = EmptySquare;
9530 board[toY][toX] = king;
9531 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9532 board[fromY][BOARD_LEFT] = EmptySquare;
9533 } else if (fromY == 7 && fromX == 3
9534 && board[fromY][fromX] == BlackKing
9535 && toY == 7 && toX == 5) {
9536 board[fromY][fromX] = EmptySquare;
9537 board[toY][toX] = BlackKing;
9538 board[fromY][7] = EmptySquare;
9539 board[toY][4] = BlackRook;
9540 } else if (fromY == 7 && fromX == 3
9541 && board[fromY][fromX] == BlackKing
9542 && toY == 7 && toX == 1) {
9543 board[fromY][fromX] = EmptySquare;
9544 board[toY][toX] = BlackKing;
9545 board[fromY][0] = EmptySquare;
9546 board[toY][2] = BlackRook;
9547 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
9548 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9549 && toY < promoRank && promoChar
9551 /* black pawn promotion */
9552 board[toY][toX] = CharToPiece(ToLower(promoChar));
9553 if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
9554 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9555 board[fromY][fromX] = EmptySquare;
9556 } else if ((fromY < BOARD_HEIGHT>>1)
9557 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality)
9559 && gameInfo.variant != VariantXiangqi
9560 && gameInfo.variant != VariantBerolina
9561 && (board[fromY][fromX] == BlackPawn)
9562 && (board[toY][toX] == EmptySquare)) {
9563 board[fromY][fromX] = EmptySquare;
9564 board[toY][toX] = BlackPawn;
9565 captured = board[toY + 1][toX];
9566 board[toY + 1][toX] = EmptySquare;
9567 } else if ((fromY == 3)
9569 && gameInfo.variant == VariantBerolina
9570 && (board[fromY][fromX] == BlackPawn)
9571 && (board[toY][toX] == EmptySquare)) {
9572 board[fromY][fromX] = EmptySquare;
9573 board[toY][toX] = BlackPawn;
9574 if(oldEP & EP_BEROLIN_A) {
9575 captured = board[fromY][fromX-1];
9576 board[fromY][fromX-1] = EmptySquare;
9577 }else{ captured = board[fromY][fromX+1];
9578 board[fromY][fromX+1] = EmptySquare;
9581 board[toY][toX] = board[fromY][fromX];
9582 board[fromY][fromX] = EmptySquare;
9586 if (gameInfo.holdingsWidth != 0) {
9588 /* !!A lot more code needs to be written to support holdings */
9589 /* [HGM] OK, so I have written it. Holdings are stored in the */
9590 /* penultimate board files, so they are automaticlly stored */
9591 /* in the game history. */
9592 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
9593 && promoChar && piece != WhitePawn && piece != BlackPawn) {
9594 /* Delete from holdings, by decreasing count */
9595 /* and erasing image if necessary */
9596 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
9597 if(p < (int) BlackPawn) { /* white drop */
9598 p -= (int)WhitePawn;
9599 p = PieceToNumber((ChessSquare)p);
9600 if(p >= gameInfo.holdingsSize) p = 0;
9601 if(--board[p][BOARD_WIDTH-2] <= 0)
9602 board[p][BOARD_WIDTH-1] = EmptySquare;
9603 if((int)board[p][BOARD_WIDTH-2] < 0)
9604 board[p][BOARD_WIDTH-2] = 0;
9605 } else { /* black drop */
9606 p -= (int)BlackPawn;
9607 p = PieceToNumber((ChessSquare)p);
9608 if(p >= gameInfo.holdingsSize) p = 0;
9609 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
9610 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
9611 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
9612 board[BOARD_HEIGHT-1-p][1] = 0;
9615 if (captured != EmptySquare && gameInfo.holdingsSize > 0
9616 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
9617 /* [HGM] holdings: Add to holdings, if holdings exist */
9618 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
9619 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
9620 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
9623 if (p >= (int) BlackPawn) {
9624 p -= (int)BlackPawn;
9625 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9626 /* in Shogi restore piece to its original first */
9627 captured = (ChessSquare) (DEMOTED captured);
9630 p = PieceToNumber((ChessSquare)p);
9631 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
9632 board[p][BOARD_WIDTH-2]++;
9633 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
9635 p -= (int)WhitePawn;
9636 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9637 captured = (ChessSquare) (DEMOTED captured);
9640 p = PieceToNumber((ChessSquare)p);
9641 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
9642 board[BOARD_HEIGHT-1-p][1]++;
9643 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
9646 } else if (gameInfo.variant == VariantAtomic) {
9647 if (captured != EmptySquare) {
9649 for (y = toY-1; y <= toY+1; y++) {
9650 for (x = toX-1; x <= toX+1; x++) {
9651 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
9652 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
9653 board[y][x] = EmptySquare;
9657 board[toY][toX] = EmptySquare;
9660 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
9661 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
9663 if(promoChar == '+') {
9664 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
9665 board[toY][toX] = (ChessSquare) (PROMOTED piece);
9666 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
9667 ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
9668 if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
9669 && pieceToChar[PROMOTED newPiece] == '~') newPiece = PROMOTED newPiece; // but promoted version available
9670 board[toY][toX] = newPiece;
9672 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
9673 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
9674 // [HGM] superchess: take promotion piece out of holdings
9675 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
9676 if((int)piece < (int)BlackPawn) { // determine stm from piece color
9677 if(!--board[k][BOARD_WIDTH-2])
9678 board[k][BOARD_WIDTH-1] = EmptySquare;
9680 if(!--board[BOARD_HEIGHT-1-k][1])
9681 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
9687 /* Updates forwardMostMove */
9689 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
9691 // forwardMostMove++; // [HGM] bare: moved downstream
9693 (void) CoordsToAlgebraic(boards[forwardMostMove],
9694 PosFlags(forwardMostMove),
9695 fromY, fromX, toY, toX, promoChar,
9696 parseList[forwardMostMove]);
9698 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
9699 int timeLeft; static int lastLoadFlag=0; int king, piece;
9700 piece = boards[forwardMostMove][fromY][fromX];
9701 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
9702 if(gameInfo.variant == VariantKnightmate)
9703 king += (int) WhiteUnicorn - (int) WhiteKing;
9704 if(forwardMostMove == 0) {
9705 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
9706 fprintf(serverMoves, "%s;", UserName());
9707 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
9708 fprintf(serverMoves, "%s;", second.tidy);
9709 fprintf(serverMoves, "%s;", first.tidy);
9710 if(gameMode == MachinePlaysWhite)
9711 fprintf(serverMoves, "%s;", UserName());
9712 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
9713 fprintf(serverMoves, "%s;", second.tidy);
9714 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
9715 lastLoadFlag = loadFlag;
9717 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
9718 // print castling suffix
9719 if( toY == fromY && piece == king ) {
9721 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
9723 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
9726 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
9727 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
9728 boards[forwardMostMove][toY][toX] == EmptySquare
9729 && fromX != toX && fromY != toY)
9730 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
9732 if(promoChar != NULLCHAR) {
9733 if(fromY == 0 || fromY == BOARD_HEIGHT-1)
9734 fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
9735 ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
9736 else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
9739 char buf[MOVE_LEN*2], *p; int len;
9740 fprintf(serverMoves, "/%d/%d",
9741 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
9742 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
9743 else timeLeft = blackTimeRemaining/1000;
9744 fprintf(serverMoves, "/%d", timeLeft);
9745 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
9746 if(p = strchr(buf, '/')) *p = NULLCHAR; else
9747 if(p = strchr(buf, '=')) *p = NULLCHAR;
9748 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
9749 fprintf(serverMoves, "/%s", buf);
9751 fflush(serverMoves);
9754 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
9755 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
9758 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
9759 if (commentList[forwardMostMove+1] != NULL) {
9760 free(commentList[forwardMostMove+1]);
9761 commentList[forwardMostMove+1] = NULL;
9763 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9764 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
9765 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
9766 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
9767 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9768 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9769 adjustedClock = FALSE;
9770 gameInfo.result = GameUnfinished;
9771 if (gameInfo.resultDetails != NULL) {
9772 free(gameInfo.resultDetails);
9773 gameInfo.resultDetails = NULL;
9775 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9776 moveList[forwardMostMove - 1]);
9777 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9783 if(gameInfo.variant != VariantShogi)
9784 strcat(parseList[forwardMostMove - 1], "+");
9788 strcat(parseList[forwardMostMove - 1], "#");
9794 /* Updates currentMove if not pausing */
9796 ShowMove (int fromX, int fromY, int toX, int toY)
9798 int instant = (gameMode == PlayFromGameFile) ?
9799 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9800 if(appData.noGUI) return;
9801 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9803 if (forwardMostMove == currentMove + 1) {
9804 AnimateMove(boards[forwardMostMove - 1],
9805 fromX, fromY, toX, toY);
9808 currentMove = forwardMostMove;
9811 if (instant) return;
9813 DisplayMove(currentMove - 1);
9814 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9815 if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
9816 SetHighlights(fromX, fromY, toX, toY);
9819 DrawPosition(FALSE, boards[currentMove]);
9820 DisplayBothClocks();
9821 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9825 SendEgtPath (ChessProgramState *cps)
9826 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9827 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9829 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9832 char c, *q = name+1, *r, *s;
9834 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9835 while(*p && *p != ',') *q++ = *p++;
9837 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9838 strcmp(name, ",nalimov:") == 0 ) {
9839 // take nalimov path from the menu-changeable option first, if it is defined
9840 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9841 SendToProgram(buf,cps); // send egtbpath command for nalimov
9843 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9844 (s = StrStr(appData.egtFormats, name)) != NULL) {
9845 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9846 s = r = StrStr(s, ":") + 1; // beginning of path info
9847 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9848 c = *r; *r = 0; // temporarily null-terminate path info
9849 *--q = 0; // strip of trailig ':' from name
9850 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9852 SendToProgram(buf,cps); // send egtbpath command for this format
9854 if(*p == ',') p++; // read away comma to position for next format name
9859 NonStandardBoardSize ()
9861 /* [HGM] Awkward testing. Should really be a table */
9862 int overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9863 if( gameInfo.variant == VariantXiangqi )
9864 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9865 if( gameInfo.variant == VariantShogi )
9866 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9867 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9868 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9869 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9870 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9871 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9872 if( gameInfo.variant == VariantCourier )
9873 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9874 if( gameInfo.variant == VariantSuper )
9875 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9876 if( gameInfo.variant == VariantGreat )
9877 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9878 if( gameInfo.variant == VariantSChess )
9879 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9880 if( gameInfo.variant == VariantGrand )
9881 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 7;
9886 InitChessProgram (ChessProgramState *cps, int setup)
9887 /* setup needed to setup FRC opening position */
9889 char buf[MSG_SIZ], b[MSG_SIZ];
9890 if (appData.noChessProgram) return;
9891 hintRequested = FALSE;
9892 bookRequested = FALSE;
9894 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
9895 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9896 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9897 if(cps->memSize) { /* [HGM] memory */
9898 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9899 SendToProgram(buf, cps);
9901 SendEgtPath(cps); /* [HGM] EGT */
9902 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9903 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9904 SendToProgram(buf, cps);
9907 SendToProgram(cps->initString, cps);
9908 if (gameInfo.variant != VariantNormal &&
9909 gameInfo.variant != VariantLoadable
9910 /* [HGM] also send variant if board size non-standard */
9911 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9913 char *v = VariantName(gameInfo.variant);
9914 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9915 /* [HGM] in protocol 1 we have to assume all variants valid */
9916 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9917 DisplayFatalError(buf, 0, 1);
9921 if(NonStandardBoardSize()) { /* [HGM] make prefix for non-standard board size. */
9922 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9923 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9924 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9925 if(StrStr(cps->variants, b) == NULL) {
9926 // specific sized variant not known, check if general sizing allowed
9927 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9928 if(StrStr(cps->variants, "boardsize") == NULL) {
9929 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9930 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9931 DisplayFatalError(buf, 0, 1);
9934 /* [HGM] here we really should compare with the maximum supported board size */
9937 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9938 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9939 SendToProgram(buf, cps);
9941 currentlyInitializedVariant = gameInfo.variant;
9943 /* [HGM] send opening position in FRC to first engine */
9945 SendToProgram("force\n", cps);
9947 /* engine is now in force mode! Set flag to wake it up after first move. */
9948 setboardSpoiledMachineBlack = 1;
9952 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9953 SendToProgram(buf, cps);
9955 cps->maybeThinking = FALSE;
9956 cps->offeredDraw = 0;
9957 if (!appData.icsActive) {
9958 SendTimeControl(cps, movesPerSession, timeControl,
9959 timeIncrement, appData.searchDepth,
9962 if (appData.showThinking
9963 // [HGM] thinking: four options require thinking output to be sent
9964 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9966 SendToProgram("post\n", cps);
9968 SendToProgram("hard\n", cps);
9969 if (!appData.ponderNextMove) {
9970 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9971 it without being sure what state we are in first. "hard"
9972 is not a toggle, so that one is OK.
9974 SendToProgram("easy\n", cps);
9977 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9978 SendToProgram(buf, cps);
9980 cps->initDone = TRUE;
9981 ClearEngineOutputPane(cps == &second);
9986 ResendOptions (ChessProgramState *cps)
9987 { // send the stored value of the options
9990 Option *opt = cps->option;
9991 for(i=0; i<cps->nrOptions; i++, opt++) {
9996 snprintf(buf, MSG_SIZ, "option %s=%d\n", opt->name, opt->value);
9999 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->choice[opt->value]);
10002 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->textValue);
10008 SendToProgram(buf, cps);
10013 StartChessProgram (ChessProgramState *cps)
10018 if (appData.noChessProgram) return;
10019 cps->initDone = FALSE;
10021 if (strcmp(cps->host, "localhost") == 0) {
10022 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
10023 } else if (*appData.remoteShell == NULLCHAR) {
10024 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
10026 if (*appData.remoteUser == NULLCHAR) {
10027 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
10030 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
10031 cps->host, appData.remoteUser, cps->program);
10033 err = StartChildProcess(buf, "", &cps->pr);
10037 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
10038 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
10039 if(cps != &first) return;
10040 appData.noChessProgram = TRUE;
10043 // DisplayFatalError(buf, err, 1);
10044 // cps->pr = NoProc;
10045 // cps->isr = NULL;
10049 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
10050 if (cps->protocolVersion > 1) {
10051 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
10052 if(!cps->reload) { // do not clear options when reloading because of -xreuse
10053 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
10054 cps->comboCnt = 0; // and values of combo boxes
10056 SendToProgram(buf, cps);
10057 if(cps->reload) ResendOptions(cps);
10059 SendToProgram("xboard\n", cps);
10064 TwoMachinesEventIfReady P((void))
10066 static int curMess = 0;
10067 if (first.lastPing != first.lastPong) {
10068 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
10069 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10072 if (second.lastPing != second.lastPong) {
10073 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
10074 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10077 DisplayMessage("", ""); curMess = 0;
10078 TwoMachinesEvent();
10082 MakeName (char *template)
10086 static char buf[MSG_SIZ];
10090 clock = time((time_t *)NULL);
10091 tm = localtime(&clock);
10093 while(*p++ = *template++) if(p[-1] == '%') {
10094 switch(*template++) {
10095 case 0: *p = 0; return buf;
10096 case 'Y': i = tm->tm_year+1900; break;
10097 case 'y': i = tm->tm_year-100; break;
10098 case 'M': i = tm->tm_mon+1; break;
10099 case 'd': i = tm->tm_mday; break;
10100 case 'h': i = tm->tm_hour; break;
10101 case 'm': i = tm->tm_min; break;
10102 case 's': i = tm->tm_sec; break;
10105 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
10111 CountPlayers (char *p)
10114 while(p = strchr(p, '\n')) p++, n++; // count participants
10119 WriteTourneyFile (char *results, FILE *f)
10120 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
10121 if(f == NULL) f = fopen(appData.tourneyFile, "w");
10122 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
10123 // create a file with tournament description
10124 fprintf(f, "-participants {%s}\n", appData.participants);
10125 fprintf(f, "-seedBase %d\n", appData.seedBase);
10126 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
10127 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
10128 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
10129 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
10130 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
10131 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
10132 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
10133 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
10134 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
10135 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
10136 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
10137 fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
10138 fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
10139 fprintf(f, "-bookDepth %d\n", appData.bookDepth);
10140 fprintf(f, "-bookVariation %d\n", appData.bookStrength);
10141 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
10142 fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
10143 fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
10144 fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
10145 fprintf(f, "-smpCores %d\n", appData.smpCores);
10147 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
10149 fprintf(f, "-mps %d\n", appData.movesPerSession);
10150 fprintf(f, "-tc %s\n", appData.timeControl);
10151 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
10153 fprintf(f, "-results \"%s\"\n", results);
10158 char *command[MAXENGINES], *mnemonic[MAXENGINES];
10161 Substitute (char *participants, int expunge)
10163 int i, changed, changes=0, nPlayers=0;
10164 char *p, *q, *r, buf[MSG_SIZ];
10165 if(participants == NULL) return;
10166 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
10167 r = p = participants; q = appData.participants;
10168 while(*p && *p == *q) {
10169 if(*p == '\n') r = p+1, nPlayers++;
10172 if(*p) { // difference
10173 while(*p && *p++ != '\n');
10174 while(*q && *q++ != '\n');
10175 changed = nPlayers;
10176 changes = 1 + (strcmp(p, q) != 0);
10178 if(changes == 1) { // a single engine mnemonic was changed
10179 q = r; while(*q) nPlayers += (*q++ == '\n');
10180 p = buf; while(*r && (*p = *r++) != '\n') p++;
10182 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10183 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
10184 if(mnemonic[i]) { // The substitute is valid
10186 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
10187 flock(fileno(f), LOCK_EX);
10188 ParseArgsFromFile(f);
10189 fseek(f, 0, SEEK_SET);
10190 FREE(appData.participants); appData.participants = participants;
10191 if(expunge) { // erase results of replaced engine
10192 int len = strlen(appData.results), w, b, dummy;
10193 for(i=0; i<len; i++) {
10194 Pairing(i, nPlayers, &w, &b, &dummy);
10195 if((w == changed || b == changed) && appData.results[i] == '*') {
10196 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
10201 for(i=0; i<len; i++) {
10202 Pairing(i, nPlayers, &w, &b, &dummy);
10203 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
10206 WriteTourneyFile(appData.results, f);
10207 fclose(f); // release lock
10210 } else DisplayError(_("No engine with the name you gave is installed"), 0);
10212 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
10213 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
10214 free(participants);
10219 CheckPlayers (char *participants)
10222 char buf[MSG_SIZ], *p;
10223 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10224 while(p = strchr(participants, '\n')) {
10226 for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
10228 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
10230 DisplayError(buf, 0);
10234 participants = p + 1;
10240 CreateTourney (char *name)
10243 if(matchMode && strcmp(name, appData.tourneyFile)) {
10244 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
10246 if(name[0] == NULLCHAR) {
10247 if(appData.participants[0])
10248 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
10251 f = fopen(name, "r");
10252 if(f) { // file exists
10253 ASSIGN(appData.tourneyFile, name);
10254 ParseArgsFromFile(f); // parse it
10256 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
10257 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
10258 DisplayError(_("Not enough participants"), 0);
10261 if(CheckPlayers(appData.participants)) return 0;
10262 ASSIGN(appData.tourneyFile, name);
10263 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
10264 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
10267 appData.noChessProgram = FALSE;
10268 appData.clockMode = TRUE;
10274 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
10276 char buf[MSG_SIZ], *p, *q;
10277 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
10278 insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
10279 skip = !all && group[0]; // if group requested, we start in skip mode
10280 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
10281 p = names; q = buf; header = 0;
10282 while(*p && *p != '\n') *q++ = *p++;
10284 if(*p == '\n') p++;
10285 if(buf[0] == '#') {
10286 if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
10287 depth++; // we must be entering a new group
10288 if(all) continue; // suppress printing group headers when complete list requested
10290 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
10292 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
10293 if(engineList[i]) free(engineList[i]);
10294 engineList[i] = strdup(buf);
10295 if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
10296 if(engineMnemonic[i]) free(engineMnemonic[i]);
10297 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
10299 sscanf(q + 8, "%s", buf + strlen(buf));
10302 engineMnemonic[i] = strdup(buf);
10305 engineList[i] = engineMnemonic[i] = NULL;
10309 // following implemented as macro to avoid type limitations
10310 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
10313 SwapEngines (int n)
10314 { // swap settings for first engine and other engine (so far only some selected options)
10319 SWAP(chessProgram, p)
10321 SWAP(hasOwnBookUCI, h)
10322 SWAP(protocolVersion, h)
10324 SWAP(scoreIsAbsolute, h)
10329 SWAP(engOptions, p)
10330 SWAP(engInitString, p)
10331 SWAP(computerString, p)
10333 SWAP(fenOverride, p)
10335 SWAP(accumulateTC, h)
10340 GetEngineLine (char *s, int n)
10344 extern char *icsNames;
10345 if(!s || !*s) return 0;
10346 NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
10347 for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
10348 if(!mnemonic[i]) return 0;
10349 if(n == 11) return 1; // just testing if there was a match
10350 snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
10351 if(n == 1) SwapEngines(n);
10352 ParseArgsFromString(buf);
10353 if(n == 1) SwapEngines(n);
10354 if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
10355 SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
10356 ParseArgsFromString(buf);
10362 SetPlayer (int player, char *p)
10363 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
10365 char buf[MSG_SIZ], *engineName;
10366 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
10367 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
10368 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
10370 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
10371 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
10372 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
10373 ParseArgsFromString(buf);
10374 } else { // no engine with this nickname is installed!
10375 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
10376 ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
10377 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10379 DisplayError(buf, 0);
10386 char *recentEngines;
10389 RecentEngineEvent (int nr)
10392 // SwapEngines(1); // bump first to second
10393 // ReplaceEngine(&second, 1); // and load it there
10394 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10395 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
10396 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
10397 ReplaceEngine(&first, 0);
10398 FloatToFront(&appData.recentEngineList, command[n]);
10403 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
10404 { // determine players from game number
10405 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
10407 if(appData.tourneyType == 0) {
10408 roundsPerCycle = (nPlayers - 1) | 1;
10409 pairingsPerRound = nPlayers / 2;
10410 } else if(appData.tourneyType > 0) {
10411 roundsPerCycle = nPlayers - appData.tourneyType;
10412 pairingsPerRound = appData.tourneyType;
10414 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
10415 gamesPerCycle = gamesPerRound * roundsPerCycle;
10416 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
10417 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
10418 curRound = nr / gamesPerRound; nr %= gamesPerRound;
10419 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
10420 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
10421 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
10423 if(appData.cycleSync) *syncInterval = gamesPerCycle;
10424 if(appData.roundSync) *syncInterval = gamesPerRound;
10426 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
10428 if(appData.tourneyType == 0) {
10429 if(curPairing == (nPlayers-1)/2 ) {
10430 *whitePlayer = curRound;
10431 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
10433 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
10434 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
10435 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
10436 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
10438 } else if(appData.tourneyType > 1) {
10439 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
10440 *whitePlayer = curRound + appData.tourneyType;
10441 } else if(appData.tourneyType > 0) {
10442 *whitePlayer = curPairing;
10443 *blackPlayer = curRound + appData.tourneyType;
10446 // take care of white/black alternation per round.
10447 // For cycles and games this is already taken care of by default, derived from matchGame!
10448 return curRound & 1;
10452 NextTourneyGame (int nr, int *swapColors)
10453 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
10455 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
10457 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
10458 tf = fopen(appData.tourneyFile, "r");
10459 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
10460 ParseArgsFromFile(tf); fclose(tf);
10461 InitTimeControls(); // TC might be altered from tourney file
10463 nPlayers = CountPlayers(appData.participants); // count participants
10464 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
10465 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
10468 p = q = appData.results;
10469 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
10470 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
10471 DisplayMessage(_("Waiting for other game(s)"),"");
10472 waitingForGame = TRUE;
10473 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
10476 waitingForGame = FALSE;
10479 if(appData.tourneyType < 0) {
10480 if(nr>=0 && !pairingReceived) {
10482 if(pairing.pr == NoProc) {
10483 if(!appData.pairingEngine[0]) {
10484 DisplayFatalError(_("No pairing engine specified"), 0, 1);
10487 StartChessProgram(&pairing); // starts the pairing engine
10489 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
10490 SendToProgram(buf, &pairing);
10491 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
10492 SendToProgram(buf, &pairing);
10493 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
10495 pairingReceived = 0; // ... so we continue here
10497 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
10498 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
10499 matchGame = 1; roundNr = nr / syncInterval + 1;
10502 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
10504 // redefine engines, engine dir, etc.
10505 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10506 if(first.pr == NoProc) {
10507 if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
10508 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
10510 if(second.pr == NoProc) {
10512 if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
10513 SwapEngines(1); // and make that valid for second engine by swapping
10514 InitEngine(&second, 1);
10516 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
10517 UpdateLogos(FALSE); // leave display to ModeHiglight()
10523 { // performs game initialization that does not invoke engines, and then tries to start the game
10524 int res, firstWhite, swapColors = 0;
10525 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
10526 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
10528 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
10529 if(strcmp(buf, currentDebugFile)) { // name has changed
10530 FILE *f = fopen(buf, "w");
10531 if(f) { // if opening the new file failed, just keep using the old one
10532 ASSIGN(currentDebugFile, buf);
10536 if(appData.serverFileName) {
10537 if(serverFP) fclose(serverFP);
10538 serverFP = fopen(appData.serverFileName, "w");
10539 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
10540 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
10544 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
10545 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
10546 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
10547 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
10548 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
10549 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
10550 Reset(FALSE, first.pr != NoProc);
10551 res = LoadGameOrPosition(matchGame); // setup game
10552 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
10553 if(!res) return; // abort when bad game/pos file
10554 TwoMachinesEvent();
10558 UserAdjudicationEvent (int result)
10560 ChessMove gameResult = GameIsDrawn;
10563 gameResult = WhiteWins;
10565 else if( result < 0 ) {
10566 gameResult = BlackWins;
10569 if( gameMode == TwoMachinesPlay ) {
10570 GameEnds( gameResult, "User adjudication", GE_XBOARD );
10575 // [HGM] save: calculate checksum of game to make games easily identifiable
10577 StringCheckSum (char *s)
10580 if(s==NULL) return 0;
10581 while(*s) i = i*259 + *s++;
10589 for(i=backwardMostMove; i<forwardMostMove; i++) {
10590 sum += pvInfoList[i].depth;
10591 sum += StringCheckSum(parseList[i]);
10592 sum += StringCheckSum(commentList[i]);
10595 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
10596 return sum + StringCheckSum(commentList[i]);
10597 } // end of save patch
10600 GameEnds (ChessMove result, char *resultDetails, int whosays)
10602 GameMode nextGameMode;
10604 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
10606 if(endingGame) return; /* [HGM] crash: forbid recursion */
10608 if(twoBoards) { // [HGM] dual: switch back to one board
10609 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
10610 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
10612 if (appData.debugMode) {
10613 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
10614 result, resultDetails ? resultDetails : "(null)", whosays);
10617 fromX = fromY = -1; // [HGM] abort any move the user is entering.
10619 if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
10621 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
10622 /* If we are playing on ICS, the server decides when the
10623 game is over, but the engine can offer to draw, claim
10627 if (appData.zippyPlay && first.initDone) {
10628 if (result == GameIsDrawn) {
10629 /* In case draw still needs to be claimed */
10630 SendToICS(ics_prefix);
10631 SendToICS("draw\n");
10632 } else if (StrCaseStr(resultDetails, "resign")) {
10633 SendToICS(ics_prefix);
10634 SendToICS("resign\n");
10638 endingGame = 0; /* [HGM] crash */
10642 /* If we're loading the game from a file, stop */
10643 if (whosays == GE_FILE) {
10644 (void) StopLoadGameTimer();
10648 /* Cancel draw offers */
10649 first.offeredDraw = second.offeredDraw = 0;
10651 /* If this is an ICS game, only ICS can really say it's done;
10652 if not, anyone can. */
10653 isIcsGame = (gameMode == IcsPlayingWhite ||
10654 gameMode == IcsPlayingBlack ||
10655 gameMode == IcsObserving ||
10656 gameMode == IcsExamining);
10658 if (!isIcsGame || whosays == GE_ICS) {
10659 /* OK -- not an ICS game, or ICS said it was done */
10661 if (!isIcsGame && !appData.noChessProgram)
10662 SetUserThinkingEnables();
10664 /* [HGM] if a machine claims the game end we verify this claim */
10665 if(gameMode == TwoMachinesPlay && appData.testClaims) {
10666 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
10668 ChessMove trueResult = (ChessMove) -1;
10670 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
10671 first.twoMachinesColor[0] :
10672 second.twoMachinesColor[0] ;
10674 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
10675 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
10676 /* [HGM] verify: engine mate claims accepted if they were flagged */
10677 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
10679 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
10680 /* [HGM] verify: engine mate claims accepted if they were flagged */
10681 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
10683 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
10684 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
10687 // now verify win claims, but not in drop games, as we don't understand those yet
10688 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10689 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
10690 (result == WhiteWins && claimer == 'w' ||
10691 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
10692 if (appData.debugMode) {
10693 fprintf(debugFP, "result=%d sp=%d move=%d\n",
10694 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
10696 if(result != trueResult) {
10697 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
10698 result = claimer == 'w' ? BlackWins : WhiteWins;
10699 resultDetails = buf;
10702 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
10703 && (forwardMostMove <= backwardMostMove ||
10704 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
10705 (claimer=='b')==(forwardMostMove&1))
10707 /* [HGM] verify: draws that were not flagged are false claims */
10708 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
10709 result = claimer == 'w' ? BlackWins : WhiteWins;
10710 resultDetails = buf;
10712 /* (Claiming a loss is accepted no questions asked!) */
10713 } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
10714 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
10715 result = GameUnfinished;
10716 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
10718 /* [HGM] bare: don't allow bare King to win */
10719 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10720 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10721 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
10722 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
10723 && result != GameIsDrawn)
10724 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
10725 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
10726 int p = (signed char)boards[forwardMostMove][i][j] - color;
10727 if(p >= 0 && p <= (int)WhiteKing) k++;
10729 if (appData.debugMode) {
10730 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
10731 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
10734 result = GameIsDrawn;
10735 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
10736 resultDetails = buf;
10742 if(serverMoves != NULL && !loadFlag) { char c = '=';
10743 if(result==WhiteWins) c = '+';
10744 if(result==BlackWins) c = '-';
10745 if(resultDetails != NULL)
10746 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
10748 if (resultDetails != NULL) {
10749 gameInfo.result = result;
10750 gameInfo.resultDetails = StrSave(resultDetails);
10752 /* display last move only if game was not loaded from file */
10753 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
10754 DisplayMove(currentMove - 1);
10756 if (forwardMostMove != 0) {
10757 if (gameMode != PlayFromGameFile && gameMode != EditGame
10758 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
10760 if (*appData.saveGameFile != NULLCHAR) {
10761 if(result == GameUnfinished && matchMode && *appData.tourneyFile)
10762 AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
10764 SaveGameToFile(appData.saveGameFile, TRUE);
10765 } else if (appData.autoSaveGames) {
10766 if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
10768 if (*appData.savePositionFile != NULLCHAR) {
10769 SavePositionToFile(appData.savePositionFile);
10771 AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
10775 /* Tell program how game ended in case it is learning */
10776 /* [HGM] Moved this to after saving the PGN, just in case */
10777 /* engine died and we got here through time loss. In that */
10778 /* case we will get a fatal error writing the pipe, which */
10779 /* would otherwise lose us the PGN. */
10780 /* [HGM] crash: not needed anymore, but doesn't hurt; */
10781 /* output during GameEnds should never be fatal anymore */
10782 if (gameMode == MachinePlaysWhite ||
10783 gameMode == MachinePlaysBlack ||
10784 gameMode == TwoMachinesPlay ||
10785 gameMode == IcsPlayingWhite ||
10786 gameMode == IcsPlayingBlack ||
10787 gameMode == BeginningOfGame) {
10789 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
10791 if (first.pr != NoProc) {
10792 SendToProgram(buf, &first);
10794 if (second.pr != NoProc &&
10795 gameMode == TwoMachinesPlay) {
10796 SendToProgram(buf, &second);
10801 if (appData.icsActive) {
10802 if (appData.quietPlay &&
10803 (gameMode == IcsPlayingWhite ||
10804 gameMode == IcsPlayingBlack)) {
10805 SendToICS(ics_prefix);
10806 SendToICS("set shout 1\n");
10808 nextGameMode = IcsIdle;
10809 ics_user_moved = FALSE;
10810 /* clean up premove. It's ugly when the game has ended and the
10811 * premove highlights are still on the board.
10814 gotPremove = FALSE;
10815 ClearPremoveHighlights();
10816 DrawPosition(FALSE, boards[currentMove]);
10818 if (whosays == GE_ICS) {
10821 if (gameMode == IcsPlayingWhite)
10823 else if(gameMode == IcsPlayingBlack)
10824 PlayIcsLossSound();
10827 if (gameMode == IcsPlayingBlack)
10829 else if(gameMode == IcsPlayingWhite)
10830 PlayIcsLossSound();
10833 PlayIcsDrawSound();
10836 PlayIcsUnfinishedSound();
10839 } else if (gameMode == EditGame ||
10840 gameMode == PlayFromGameFile ||
10841 gameMode == AnalyzeMode ||
10842 gameMode == AnalyzeFile) {
10843 nextGameMode = gameMode;
10845 nextGameMode = EndOfGame;
10850 nextGameMode = gameMode;
10853 if (appData.noChessProgram) {
10854 gameMode = nextGameMode;
10856 endingGame = 0; /* [HGM] crash */
10861 /* Put first chess program into idle state */
10862 if (first.pr != NoProc &&
10863 (gameMode == MachinePlaysWhite ||
10864 gameMode == MachinePlaysBlack ||
10865 gameMode == TwoMachinesPlay ||
10866 gameMode == IcsPlayingWhite ||
10867 gameMode == IcsPlayingBlack ||
10868 gameMode == BeginningOfGame)) {
10869 SendToProgram("force\n", &first);
10870 if (first.usePing) {
10872 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
10873 SendToProgram(buf, &first);
10876 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10877 /* Kill off first chess program */
10878 if (first.isr != NULL)
10879 RemoveInputSource(first.isr);
10882 if (first.pr != NoProc) {
10884 DoSleep( appData.delayBeforeQuit );
10885 SendToProgram("quit\n", &first);
10886 DoSleep( appData.delayAfterQuit );
10887 DestroyChildProcess(first.pr, first.useSigterm);
10888 first.reload = TRUE;
10892 if (second.reuse) {
10893 /* Put second chess program into idle state */
10894 if (second.pr != NoProc &&
10895 gameMode == TwoMachinesPlay) {
10896 SendToProgram("force\n", &second);
10897 if (second.usePing) {
10899 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
10900 SendToProgram(buf, &second);
10903 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10904 /* Kill off second chess program */
10905 if (second.isr != NULL)
10906 RemoveInputSource(second.isr);
10909 if (second.pr != NoProc) {
10910 DoSleep( appData.delayBeforeQuit );
10911 SendToProgram("quit\n", &second);
10912 DoSleep( appData.delayAfterQuit );
10913 DestroyChildProcess(second.pr, second.useSigterm);
10914 second.reload = TRUE;
10916 second.pr = NoProc;
10919 if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
10920 char resChar = '=';
10924 if (first.twoMachinesColor[0] == 'w') {
10927 second.matchWins++;
10932 if (first.twoMachinesColor[0] == 'b') {
10935 second.matchWins++;
10938 case GameUnfinished:
10944 if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
10945 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
10946 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
10947 ReserveGame(nextGame, resChar); // sets nextGame
10948 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
10949 else ranking = strdup("busy"); //suppress popup when aborted but not finished
10950 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
10952 if (nextGame <= appData.matchGames && !abortMatch) {
10953 gameMode = nextGameMode;
10954 matchGame = nextGame; // this will be overruled in tourney mode!
10955 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
10956 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
10957 endingGame = 0; /* [HGM] crash */
10960 gameMode = nextGameMode;
10961 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
10962 first.tidy, second.tidy,
10963 first.matchWins, second.matchWins,
10964 appData.matchGames - (first.matchWins + second.matchWins));
10965 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
10966 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
10967 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
10968 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
10969 first.twoMachinesColor = "black\n";
10970 second.twoMachinesColor = "white\n";
10972 first.twoMachinesColor = "white\n";
10973 second.twoMachinesColor = "black\n";
10977 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
10978 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
10980 gameMode = nextGameMode;
10982 endingGame = 0; /* [HGM] crash */
10983 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
10984 if(matchMode == TRUE) { // match through command line: exit with or without popup
10986 ToNrEvent(forwardMostMove);
10987 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
10989 } else DisplayFatalError(buf, 0, 0);
10990 } else { // match through menu; just stop, with or without popup
10991 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10994 if(strcmp(ranking, "busy")) DisplayNote(ranking);
10995 } else DisplayNote(buf);
10997 if(ranking) free(ranking);
11001 /* Assumes program was just initialized (initString sent).
11002 Leaves program in force mode. */
11004 FeedMovesToProgram (ChessProgramState *cps, int upto)
11008 if (appData.debugMode)
11009 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
11010 startedFromSetupPosition ? "position and " : "",
11011 backwardMostMove, upto, cps->which);
11012 if(currentlyInitializedVariant != gameInfo.variant) {
11014 // [HGM] variantswitch: make engine aware of new variant
11015 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
11016 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
11017 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
11018 SendToProgram(buf, cps);
11019 currentlyInitializedVariant = gameInfo.variant;
11021 SendToProgram("force\n", cps);
11022 if (startedFromSetupPosition) {
11023 SendBoard(cps, backwardMostMove);
11024 if (appData.debugMode) {
11025 fprintf(debugFP, "feedMoves\n");
11028 for (i = backwardMostMove; i < upto; i++) {
11029 SendMoveToProgram(i, cps);
11035 ResurrectChessProgram ()
11037 /* The chess program may have exited.
11038 If so, restart it and feed it all the moves made so far. */
11039 static int doInit = 0;
11041 if (appData.noChessProgram) return 1;
11043 if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
11044 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
11045 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
11046 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
11048 if (first.pr != NoProc) return 1;
11049 StartChessProgram(&first);
11051 InitChessProgram(&first, FALSE);
11052 FeedMovesToProgram(&first, currentMove);
11054 if (!first.sendTime) {
11055 /* can't tell gnuchess what its clock should read,
11056 so we bow to its notion. */
11058 timeRemaining[0][currentMove] = whiteTimeRemaining;
11059 timeRemaining[1][currentMove] = blackTimeRemaining;
11062 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
11063 appData.icsEngineAnalyze) && first.analysisSupport) {
11064 SendToProgram("analyze\n", &first);
11065 first.analyzing = TRUE;
11071 * Button procedures
11074 Reset (int redraw, int init)
11078 if (appData.debugMode) {
11079 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
11080 redraw, init, gameMode);
11082 CleanupTail(); // [HGM] vari: delete any stored variations
11083 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
11084 pausing = pauseExamInvalid = FALSE;
11085 startedFromSetupPosition = blackPlaysFirst = FALSE;
11087 whiteFlag = blackFlag = FALSE;
11088 userOfferedDraw = FALSE;
11089 hintRequested = bookRequested = FALSE;
11090 first.maybeThinking = FALSE;
11091 second.maybeThinking = FALSE;
11092 first.bookSuspend = FALSE; // [HGM] book
11093 second.bookSuspend = FALSE;
11094 thinkOutput[0] = NULLCHAR;
11095 lastHint[0] = NULLCHAR;
11096 ClearGameInfo(&gameInfo);
11097 gameInfo.variant = StringToVariant(appData.variant);
11098 ics_user_moved = ics_clock_paused = FALSE;
11099 ics_getting_history = H_FALSE;
11101 white_holding[0] = black_holding[0] = NULLCHAR;
11102 ClearProgramStats();
11103 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
11107 flipView = appData.flipView;
11108 ClearPremoveHighlights();
11109 gotPremove = FALSE;
11110 alarmSounded = FALSE;
11112 GameEnds(EndOfFile, NULL, GE_PLAYER);
11113 if(appData.serverMovesName != NULL) {
11114 /* [HGM] prepare to make moves file for broadcasting */
11115 clock_t t = clock();
11116 if(serverMoves != NULL) fclose(serverMoves);
11117 serverMoves = fopen(appData.serverMovesName, "r");
11118 if(serverMoves != NULL) {
11119 fclose(serverMoves);
11120 /* delay 15 sec before overwriting, so all clients can see end */
11121 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
11123 serverMoves = fopen(appData.serverMovesName, "w");
11127 gameMode = BeginningOfGame;
11129 if(appData.icsActive) gameInfo.variant = VariantNormal;
11130 currentMove = forwardMostMove = backwardMostMove = 0;
11131 MarkTargetSquares(1);
11132 InitPosition(redraw);
11133 for (i = 0; i < MAX_MOVES; i++) {
11134 if (commentList[i] != NULL) {
11135 free(commentList[i]);
11136 commentList[i] = NULL;
11140 timeRemaining[0][0] = whiteTimeRemaining;
11141 timeRemaining[1][0] = blackTimeRemaining;
11143 if (first.pr == NoProc) {
11144 StartChessProgram(&first);
11147 InitChessProgram(&first, startedFromSetupPosition);
11150 DisplayMessage("", "");
11151 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11152 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
11153 ClearMap(); // [HGM] exclude: invalidate map
11157 AutoPlayGameLoop ()
11160 if (!AutoPlayOneMove())
11162 if (matchMode || appData.timeDelay == 0)
11164 if (appData.timeDelay < 0)
11166 StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
11174 ReloadGame(1); // next game
11180 int fromX, fromY, toX, toY;
11182 if (appData.debugMode) {
11183 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
11186 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
11189 if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
11190 pvInfoList[currentMove].depth = programStats.depth;
11191 pvInfoList[currentMove].score = programStats.score;
11192 pvInfoList[currentMove].time = 0;
11193 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
11194 else { // append analysis of final position as comment
11196 snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
11197 AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
11199 programStats.depth = 0;
11202 if (currentMove >= forwardMostMove) {
11203 if(gameMode == AnalyzeFile) {
11204 if(appData.loadGameIndex == -1) {
11205 GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
11206 ScheduleDelayedEvent(AnalyzeNextGame, 10);
11208 ExitAnalyzeMode(); SendToProgram("force\n", &first);
11211 // gameMode = EndOfGame;
11212 // ModeHighlight();
11214 /* [AS] Clear current move marker at the end of a game */
11215 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
11220 toX = moveList[currentMove][2] - AAA;
11221 toY = moveList[currentMove][3] - ONE;
11223 if (moveList[currentMove][1] == '@') {
11224 if (appData.highlightLastMove) {
11225 SetHighlights(-1, -1, toX, toY);
11228 fromX = moveList[currentMove][0] - AAA;
11229 fromY = moveList[currentMove][1] - ONE;
11231 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
11233 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11235 if (appData.highlightLastMove) {
11236 SetHighlights(fromX, fromY, toX, toY);
11239 DisplayMove(currentMove);
11240 SendMoveToProgram(currentMove++, &first);
11241 DisplayBothClocks();
11242 DrawPosition(FALSE, boards[currentMove]);
11243 // [HGM] PV info: always display, routine tests if empty
11244 DisplayComment(currentMove - 1, commentList[currentMove]);
11250 LoadGameOneMove (ChessMove readAhead)
11252 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
11253 char promoChar = NULLCHAR;
11254 ChessMove moveType;
11255 char move[MSG_SIZ];
11258 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
11259 gameMode != AnalyzeMode && gameMode != Training) {
11264 yyboardindex = forwardMostMove;
11265 if (readAhead != EndOfFile) {
11266 moveType = readAhead;
11268 if (gameFileFP == NULL)
11270 moveType = (ChessMove) Myylex();
11274 switch (moveType) {
11276 if (appData.debugMode)
11277 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11280 /* append the comment but don't display it */
11281 AppendComment(currentMove, p, FALSE);
11284 case WhiteCapturesEnPassant:
11285 case BlackCapturesEnPassant:
11286 case WhitePromotion:
11287 case BlackPromotion:
11288 case WhiteNonPromotion:
11289 case BlackNonPromotion:
11291 case WhiteKingSideCastle:
11292 case WhiteQueenSideCastle:
11293 case BlackKingSideCastle:
11294 case BlackQueenSideCastle:
11295 case WhiteKingSideCastleWild:
11296 case WhiteQueenSideCastleWild:
11297 case BlackKingSideCastleWild:
11298 case BlackQueenSideCastleWild:
11300 case WhiteHSideCastleFR:
11301 case WhiteASideCastleFR:
11302 case BlackHSideCastleFR:
11303 case BlackASideCastleFR:
11305 if (appData.debugMode)
11306 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11307 fromX = currentMoveString[0] - AAA;
11308 fromY = currentMoveString[1] - ONE;
11309 toX = currentMoveString[2] - AAA;
11310 toY = currentMoveString[3] - ONE;
11311 promoChar = currentMoveString[4];
11316 if (appData.debugMode)
11317 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11318 fromX = moveType == WhiteDrop ?
11319 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11320 (int) CharToPiece(ToLower(currentMoveString[0]));
11322 toX = currentMoveString[2] - AAA;
11323 toY = currentMoveString[3] - ONE;
11329 case GameUnfinished:
11330 if (appData.debugMode)
11331 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
11332 p = strchr(yy_text, '{');
11333 if (p == NULL) p = strchr(yy_text, '(');
11336 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
11338 q = strchr(p, *p == '{' ? '}' : ')');
11339 if (q != NULL) *q = NULLCHAR;
11342 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
11343 GameEnds(moveType, p, GE_FILE);
11345 if (cmailMsgLoaded) {
11347 flipView = WhiteOnMove(currentMove);
11348 if (moveType == GameUnfinished) flipView = !flipView;
11349 if (appData.debugMode)
11350 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
11355 if (appData.debugMode)
11356 fprintf(debugFP, "Parser hit end of file\n");
11357 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11363 if (WhiteOnMove(currentMove)) {
11364 GameEnds(BlackWins, "Black mates", GE_FILE);
11366 GameEnds(WhiteWins, "White mates", GE_FILE);
11370 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11376 case MoveNumberOne:
11377 if (lastLoadGameStart == GNUChessGame) {
11378 /* GNUChessGames have numbers, but they aren't move numbers */
11379 if (appData.debugMode)
11380 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11381 yy_text, (int) moveType);
11382 return LoadGameOneMove(EndOfFile); /* tail recursion */
11384 /* else fall thru */
11389 /* Reached start of next game in file */
11390 if (appData.debugMode)
11391 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
11392 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11398 if (WhiteOnMove(currentMove)) {
11399 GameEnds(BlackWins, "Black mates", GE_FILE);
11401 GameEnds(WhiteWins, "White mates", GE_FILE);
11405 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11411 case PositionDiagram: /* should not happen; ignore */
11412 case ElapsedTime: /* ignore */
11413 case NAG: /* ignore */
11414 if (appData.debugMode)
11415 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11416 yy_text, (int) moveType);
11417 return LoadGameOneMove(EndOfFile); /* tail recursion */
11420 if (appData.testLegality) {
11421 if (appData.debugMode)
11422 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
11423 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11424 (forwardMostMove / 2) + 1,
11425 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11426 DisplayError(move, 0);
11429 if (appData.debugMode)
11430 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
11431 yy_text, currentMoveString);
11432 fromX = currentMoveString[0] - AAA;
11433 fromY = currentMoveString[1] - ONE;
11434 toX = currentMoveString[2] - AAA;
11435 toY = currentMoveString[3] - ONE;
11436 promoChar = currentMoveString[4];
11440 case AmbiguousMove:
11441 if (appData.debugMode)
11442 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
11443 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
11444 (forwardMostMove / 2) + 1,
11445 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11446 DisplayError(move, 0);
11451 case ImpossibleMove:
11452 if (appData.debugMode)
11453 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
11454 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11455 (forwardMostMove / 2) + 1,
11456 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11457 DisplayError(move, 0);
11463 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
11464 DrawPosition(FALSE, boards[currentMove]);
11465 DisplayBothClocks();
11466 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
11467 DisplayComment(currentMove - 1, commentList[currentMove]);
11469 (void) StopLoadGameTimer();
11471 cmailOldMove = forwardMostMove;
11474 /* currentMoveString is set as a side-effect of yylex */
11476 thinkOutput[0] = NULLCHAR;
11477 MakeMove(fromX, fromY, toX, toY, promoChar);
11478 currentMove = forwardMostMove;
11483 /* Load the nth game from the given file */
11485 LoadGameFromFile (char *filename, int n, char *title, int useList)
11490 if (strcmp(filename, "-") == 0) {
11494 f = fopen(filename, "rb");
11496 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11497 DisplayError(buf, errno);
11501 if (fseek(f, 0, 0) == -1) {
11502 /* f is not seekable; probably a pipe */
11505 if (useList && n == 0) {
11506 int error = GameListBuild(f);
11508 DisplayError(_("Cannot build game list"), error);
11509 } else if (!ListEmpty(&gameList) &&
11510 ((ListGame *) gameList.tailPred)->number > 1) {
11511 GameListPopUp(f, title);
11518 return LoadGame(f, n, title, FALSE);
11523 MakeRegisteredMove ()
11525 int fromX, fromY, toX, toY;
11527 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11528 switch (cmailMoveType[lastLoadGameNumber - 1]) {
11531 if (appData.debugMode)
11532 fprintf(debugFP, "Restoring %s for game %d\n",
11533 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11535 thinkOutput[0] = NULLCHAR;
11536 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
11537 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
11538 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
11539 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
11540 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
11541 promoChar = cmailMove[lastLoadGameNumber - 1][4];
11542 MakeMove(fromX, fromY, toX, toY, promoChar);
11543 ShowMove(fromX, fromY, toX, toY);
11545 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11552 if (WhiteOnMove(currentMove)) {
11553 GameEnds(BlackWins, "Black mates", GE_PLAYER);
11555 GameEnds(WhiteWins, "White mates", GE_PLAYER);
11560 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
11567 if (WhiteOnMove(currentMove)) {
11568 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11570 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11575 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11586 /* Wrapper around LoadGame for use when a Cmail message is loaded */
11588 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
11592 if (gameNumber > nCmailGames) {
11593 DisplayError(_("No more games in this message"), 0);
11596 if (f == lastLoadGameFP) {
11597 int offset = gameNumber - lastLoadGameNumber;
11599 cmailMsg[0] = NULLCHAR;
11600 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11601 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11602 nCmailMovesRegistered--;
11604 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11605 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
11606 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
11609 if (! RegisterMove()) return FALSE;
11613 retVal = LoadGame(f, gameNumber, title, useList);
11615 /* Make move registered during previous look at this game, if any */
11616 MakeRegisteredMove();
11618 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
11619 commentList[currentMove]
11620 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
11621 DisplayComment(currentMove - 1, commentList[currentMove]);
11627 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
11629 ReloadGame (int offset)
11631 int gameNumber = lastLoadGameNumber + offset;
11632 if (lastLoadGameFP == NULL) {
11633 DisplayError(_("No game has been loaded yet"), 0);
11636 if (gameNumber <= 0) {
11637 DisplayError(_("Can't back up any further"), 0);
11640 if (cmailMsgLoaded) {
11641 return CmailLoadGame(lastLoadGameFP, gameNumber,
11642 lastLoadGameTitle, lastLoadGameUseList);
11644 return LoadGame(lastLoadGameFP, gameNumber,
11645 lastLoadGameTitle, lastLoadGameUseList);
11649 int keys[EmptySquare+1];
11652 PositionMatches (Board b1, Board b2)
11655 switch(appData.searchMode) {
11656 case 1: return CompareWithRights(b1, b2);
11658 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11659 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
11663 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11664 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
11665 sum += keys[b1[r][f]] - keys[b2[r][f]];
11669 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11670 sum += keys[b1[r][f]] - keys[b2[r][f]];
11682 int pieceList[256], quickBoard[256];
11683 ChessSquare pieceType[256] = { EmptySquare };
11684 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
11685 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
11686 int soughtTotal, turn;
11687 Boolean epOK, flipSearch;
11690 unsigned char piece, to;
11693 #define DSIZE (250000)
11695 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
11696 Move *moveDatabase = initialSpace;
11697 unsigned int movePtr, dataSize = DSIZE;
11700 MakePieceList (Board board, int *counts)
11702 int r, f, n=Q_PROMO, total=0;
11703 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
11704 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11705 int sq = f + (r<<4);
11706 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
11707 quickBoard[sq] = ++n;
11709 pieceType[n] = board[r][f];
11710 counts[board[r][f]]++;
11711 if(board[r][f] == WhiteKing) pieceList[1] = n; else
11712 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
11716 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
11721 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
11723 int sq = fromX + (fromY<<4);
11724 int piece = quickBoard[sq];
11725 quickBoard[sq] = 0;
11726 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
11727 if(piece == pieceList[1] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11728 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
11729 moveDatabase[movePtr++].piece = Q_WCASTL;
11730 quickBoard[sq] = piece;
11731 piece = quickBoard[from]; quickBoard[from] = 0;
11732 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11734 if(piece == pieceList[2] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11735 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
11736 moveDatabase[movePtr++].piece = Q_BCASTL;
11737 quickBoard[sq] = piece;
11738 piece = quickBoard[from]; quickBoard[from] = 0;
11739 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11741 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
11742 quickBoard[(fromY<<4)+toX] = 0;
11743 moveDatabase[movePtr].piece = Q_EP;
11744 moveDatabase[movePtr++].to = (fromY<<4)+toX;
11745 moveDatabase[movePtr].to = sq;
11747 if(promoPiece != pieceType[piece]) {
11748 moveDatabase[movePtr++].piece = Q_PROMO;
11749 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
11751 moveDatabase[movePtr].piece = piece;
11752 quickBoard[sq] = piece;
11757 PackGame (Board board)
11759 Move *newSpace = NULL;
11760 moveDatabase[movePtr].piece = 0; // terminate previous game
11761 if(movePtr > dataSize) {
11762 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
11763 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
11764 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
11767 Move *p = moveDatabase, *q = newSpace;
11768 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
11769 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
11770 moveDatabase = newSpace;
11771 } else { // calloc failed, we must be out of memory. Too bad...
11772 dataSize = 0; // prevent calloc events for all subsequent games
11773 return 0; // and signal this one isn't cached
11777 MakePieceList(board, counts);
11782 QuickCompare (Board board, int *minCounts, int *maxCounts)
11783 { // compare according to search mode
11785 switch(appData.searchMode)
11787 case 1: // exact position match
11788 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
11789 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11790 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11793 case 2: // can have extra material on empty squares
11794 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11795 if(board[r][f] == EmptySquare) continue;
11796 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11799 case 3: // material with exact Pawn structure
11800 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11801 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
11802 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11803 } // fall through to material comparison
11804 case 4: // exact material
11805 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
11807 case 6: // material range with given imbalance
11808 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
11809 // fall through to range comparison
11810 case 5: // material range
11811 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
11817 QuickScan (Board board, Move *move)
11818 { // reconstruct game,and compare all positions in it
11819 int cnt=0, stretch=0, total = MakePieceList(board, counts);
11821 int piece = move->piece;
11822 int to = move->to, from = pieceList[piece];
11823 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
11824 if(!piece) return -1;
11825 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
11826 piece = (++move)->piece;
11827 from = pieceList[piece];
11828 counts[pieceType[piece]]--;
11829 pieceType[piece] = (ChessSquare) move->to;
11830 counts[move->to]++;
11831 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
11832 counts[pieceType[quickBoard[to]]]--;
11833 quickBoard[to] = 0; total--;
11836 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
11837 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
11838 from = pieceList[piece]; // so this must be King
11839 quickBoard[from] = 0;
11840 pieceList[piece] = to;
11841 from = pieceList[(++move)->piece]; // for FRC this has to be done here
11842 quickBoard[from] = 0; // rook
11843 quickBoard[to] = piece;
11844 to = move->to; piece = move->piece;
11848 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
11849 if((total -= (quickBoard[to] != 0)) < soughtTotal) return -1; // piece count dropped below what we search for
11850 quickBoard[from] = 0;
11852 quickBoard[to] = piece;
11853 pieceList[piece] = to;
11855 if(QuickCompare(soughtBoard, minSought, maxSought) ||
11856 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
11857 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
11858 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
11860 static int lastCounts[EmptySquare+1];
11862 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
11863 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
11864 } else stretch = 0;
11865 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) return cnt + 1 - stretch;
11874 flipSearch = FALSE;
11875 CopyBoard(soughtBoard, boards[currentMove]);
11876 soughtTotal = MakePieceList(soughtBoard, maxSought);
11877 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
11878 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
11879 CopyBoard(reverseBoard, boards[currentMove]);
11880 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11881 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
11882 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
11883 reverseBoard[r][f] = piece;
11885 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
11886 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
11887 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
11888 || (boards[currentMove][CASTLING][2] == NoRights ||
11889 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
11890 && (boards[currentMove][CASTLING][5] == NoRights ||
11891 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
11894 CopyBoard(flipBoard, soughtBoard);
11895 CopyBoard(rotateBoard, reverseBoard);
11896 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11897 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
11898 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
11901 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
11902 if(appData.searchMode >= 5) {
11903 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
11904 MakePieceList(soughtBoard, minSought);
11905 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
11907 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
11908 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
11911 GameInfo dummyInfo;
11912 static int creatingBook;
11915 GameContainsPosition (FILE *f, ListGame *lg)
11917 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
11918 int fromX, fromY, toX, toY;
11920 static int initDone=FALSE;
11922 // weed out games based on numerical tag comparison
11923 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
11924 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
11925 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
11926 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
11928 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
11931 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen);
11932 else CopyBoard(boards[scratch], initialPosition); // default start position
11935 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
11936 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
11939 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11940 fseek(f, lg->offset, 0);
11943 yyboardindex = scratch;
11944 quickFlag = plyNr+1;
11949 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
11955 if(plyNr) return -1; // after we have seen moves, this is for new game
11958 case AmbiguousMove: // we cannot reconstruct the game beyond these two
11959 case ImpossibleMove:
11960 case WhiteWins: // game ends here with these four
11963 case GameUnfinished:
11967 if(appData.testLegality) return -1;
11968 case WhiteCapturesEnPassant:
11969 case BlackCapturesEnPassant:
11970 case WhitePromotion:
11971 case BlackPromotion:
11972 case WhiteNonPromotion:
11973 case BlackNonPromotion:
11975 case WhiteKingSideCastle:
11976 case WhiteQueenSideCastle:
11977 case BlackKingSideCastle:
11978 case BlackQueenSideCastle:
11979 case WhiteKingSideCastleWild:
11980 case WhiteQueenSideCastleWild:
11981 case BlackKingSideCastleWild:
11982 case BlackQueenSideCastleWild:
11983 case WhiteHSideCastleFR:
11984 case WhiteASideCastleFR:
11985 case BlackHSideCastleFR:
11986 case BlackASideCastleFR:
11987 fromX = currentMoveString[0] - AAA;
11988 fromY = currentMoveString[1] - ONE;
11989 toX = currentMoveString[2] - AAA;
11990 toY = currentMoveString[3] - ONE;
11991 promoChar = currentMoveString[4];
11995 fromX = next == WhiteDrop ?
11996 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11997 (int) CharToPiece(ToLower(currentMoveString[0]));
11999 toX = currentMoveString[2] - AAA;
12000 toY = currentMoveString[3] - ONE;
12004 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
12006 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
12007 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12008 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
12009 if(appData.findMirror) {
12010 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
12011 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
12016 /* Load the nth game from open file f */
12018 LoadGame (FILE *f, int gameNumber, char *title, int useList)
12022 int gn = gameNumber;
12023 ListGame *lg = NULL;
12024 int numPGNTags = 0;
12026 GameMode oldGameMode;
12027 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
12029 if (appData.debugMode)
12030 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
12032 if (gameMode == Training )
12033 SetTrainingModeOff();
12035 oldGameMode = gameMode;
12036 if (gameMode != BeginningOfGame) {
12037 Reset(FALSE, TRUE);
12041 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
12042 fclose(lastLoadGameFP);
12046 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
12049 fseek(f, lg->offset, 0);
12050 GameListHighlight(gameNumber);
12051 pos = lg->position;
12055 if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
12056 appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
12058 DisplayError(_("Game number out of range"), 0);
12063 if (fseek(f, 0, 0) == -1) {
12064 if (f == lastLoadGameFP ?
12065 gameNumber == lastLoadGameNumber + 1 :
12069 DisplayError(_("Can't seek on game file"), 0);
12074 lastLoadGameFP = f;
12075 lastLoadGameNumber = gameNumber;
12076 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
12077 lastLoadGameUseList = useList;
12081 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
12082 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
12083 lg->gameInfo.black);
12085 } else if (*title != NULLCHAR) {
12086 if (gameNumber > 1) {
12087 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
12090 DisplayTitle(title);
12094 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
12095 gameMode = PlayFromGameFile;
12099 currentMove = forwardMostMove = backwardMostMove = 0;
12100 CopyBoard(boards[0], initialPosition);
12104 * Skip the first gn-1 games in the file.
12105 * Also skip over anything that precedes an identifiable
12106 * start of game marker, to avoid being confused by
12107 * garbage at the start of the file. Currently
12108 * recognized start of game markers are the move number "1",
12109 * the pattern "gnuchess .* game", the pattern
12110 * "^[#;%] [^ ]* game file", and a PGN tag block.
12111 * A game that starts with one of the latter two patterns
12112 * will also have a move number 1, possibly
12113 * following a position diagram.
12114 * 5-4-02: Let's try being more lenient and allowing a game to
12115 * start with an unnumbered move. Does that break anything?
12117 cm = lastLoadGameStart = EndOfFile;
12119 yyboardindex = forwardMostMove;
12120 cm = (ChessMove) Myylex();
12123 if (cmailMsgLoaded) {
12124 nCmailGames = CMAIL_MAX_GAMES - gn;
12127 DisplayError(_("Game not found in file"), 0);
12134 lastLoadGameStart = cm;
12137 case MoveNumberOne:
12138 switch (lastLoadGameStart) {
12143 case MoveNumberOne:
12145 gn--; /* count this game */
12146 lastLoadGameStart = cm;
12155 switch (lastLoadGameStart) {
12158 case MoveNumberOne:
12160 gn--; /* count this game */
12161 lastLoadGameStart = cm;
12164 lastLoadGameStart = cm; /* game counted already */
12172 yyboardindex = forwardMostMove;
12173 cm = (ChessMove) Myylex();
12174 } while (cm == PGNTag || cm == Comment);
12181 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
12182 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
12183 != CMAIL_OLD_RESULT) {
12185 cmailResult[ CMAIL_MAX_GAMES
12186 - gn - 1] = CMAIL_OLD_RESULT;
12192 /* Only a NormalMove can be at the start of a game
12193 * without a position diagram. */
12194 if (lastLoadGameStart == EndOfFile ) {
12196 lastLoadGameStart = MoveNumberOne;
12205 if (appData.debugMode)
12206 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
12208 if (cm == XBoardGame) {
12209 /* Skip any header junk before position diagram and/or move 1 */
12211 yyboardindex = forwardMostMove;
12212 cm = (ChessMove) Myylex();
12214 if (cm == EndOfFile ||
12215 cm == GNUChessGame || cm == XBoardGame) {
12216 /* Empty game; pretend end-of-file and handle later */
12221 if (cm == MoveNumberOne || cm == PositionDiagram ||
12222 cm == PGNTag || cm == Comment)
12225 } else if (cm == GNUChessGame) {
12226 if (gameInfo.event != NULL) {
12227 free(gameInfo.event);
12229 gameInfo.event = StrSave(yy_text);
12232 startedFromSetupPosition = FALSE;
12233 while (cm == PGNTag) {
12234 if (appData.debugMode)
12235 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
12236 err = ParsePGNTag(yy_text, &gameInfo);
12237 if (!err) numPGNTags++;
12239 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
12240 if(gameInfo.variant != oldVariant) {
12241 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
12242 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
12243 InitPosition(TRUE);
12244 oldVariant = gameInfo.variant;
12245 if (appData.debugMode)
12246 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
12250 if (gameInfo.fen != NULL) {
12251 Board initial_position;
12252 startedFromSetupPosition = TRUE;
12253 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
12255 DisplayError(_("Bad FEN position in file"), 0);
12258 CopyBoard(boards[0], initial_position);
12259 if (blackPlaysFirst) {
12260 currentMove = forwardMostMove = backwardMostMove = 1;
12261 CopyBoard(boards[1], initial_position);
12262 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12263 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12264 timeRemaining[0][1] = whiteTimeRemaining;
12265 timeRemaining[1][1] = blackTimeRemaining;
12266 if (commentList[0] != NULL) {
12267 commentList[1] = commentList[0];
12268 commentList[0] = NULL;
12271 currentMove = forwardMostMove = backwardMostMove = 0;
12273 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
12275 initialRulePlies = FENrulePlies;
12276 for( i=0; i< nrCastlingRights; i++ )
12277 initialRights[i] = initial_position[CASTLING][i];
12279 yyboardindex = forwardMostMove;
12280 free(gameInfo.fen);
12281 gameInfo.fen = NULL;
12284 yyboardindex = forwardMostMove;
12285 cm = (ChessMove) Myylex();
12287 /* Handle comments interspersed among the tags */
12288 while (cm == Comment) {
12290 if (appData.debugMode)
12291 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12293 AppendComment(currentMove, p, FALSE);
12294 yyboardindex = forwardMostMove;
12295 cm = (ChessMove) Myylex();
12299 /* don't rely on existence of Event tag since if game was
12300 * pasted from clipboard the Event tag may not exist
12302 if (numPGNTags > 0){
12304 if (gameInfo.variant == VariantNormal) {
12305 VariantClass v = StringToVariant(gameInfo.event);
12306 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
12307 if(v < VariantShogi) gameInfo.variant = v;
12310 if( appData.autoDisplayTags ) {
12311 tags = PGNTags(&gameInfo);
12312 TagsPopUp(tags, CmailMsg());
12317 /* Make something up, but don't display it now */
12322 if (cm == PositionDiagram) {
12325 Board initial_position;
12327 if (appData.debugMode)
12328 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
12330 if (!startedFromSetupPosition) {
12332 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
12333 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
12344 initial_position[i][j++] = CharToPiece(*p);
12347 while (*p == ' ' || *p == '\t' ||
12348 *p == '\n' || *p == '\r') p++;
12350 if (strncmp(p, "black", strlen("black"))==0)
12351 blackPlaysFirst = TRUE;
12353 blackPlaysFirst = FALSE;
12354 startedFromSetupPosition = TRUE;
12356 CopyBoard(boards[0], initial_position);
12357 if (blackPlaysFirst) {
12358 currentMove = forwardMostMove = backwardMostMove = 1;
12359 CopyBoard(boards[1], initial_position);
12360 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12361 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12362 timeRemaining[0][1] = whiteTimeRemaining;
12363 timeRemaining[1][1] = blackTimeRemaining;
12364 if (commentList[0] != NULL) {
12365 commentList[1] = commentList[0];
12366 commentList[0] = NULL;
12369 currentMove = forwardMostMove = backwardMostMove = 0;
12372 yyboardindex = forwardMostMove;
12373 cm = (ChessMove) Myylex();
12376 if(!creatingBook) {
12377 if (first.pr == NoProc) {
12378 StartChessProgram(&first);
12380 InitChessProgram(&first, FALSE);
12381 SendToProgram("force\n", &first);
12382 if (startedFromSetupPosition) {
12383 SendBoard(&first, forwardMostMove);
12384 if (appData.debugMode) {
12385 fprintf(debugFP, "Load Game\n");
12387 DisplayBothClocks();
12391 /* [HGM] server: flag to write setup moves in broadcast file as one */
12392 loadFlag = appData.suppressLoadMoves;
12394 while (cm == Comment) {
12396 if (appData.debugMode)
12397 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12399 AppendComment(currentMove, p, FALSE);
12400 yyboardindex = forwardMostMove;
12401 cm = (ChessMove) Myylex();
12404 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
12405 cm == WhiteWins || cm == BlackWins ||
12406 cm == GameIsDrawn || cm == GameUnfinished) {
12407 DisplayMessage("", _("No moves in game"));
12408 if (cmailMsgLoaded) {
12409 if (appData.debugMode)
12410 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
12414 DrawPosition(FALSE, boards[currentMove]);
12415 DisplayBothClocks();
12416 gameMode = EditGame;
12423 // [HGM] PV info: routine tests if comment empty
12424 if (!matchMode && (pausing || appData.timeDelay != 0)) {
12425 DisplayComment(currentMove - 1, commentList[currentMove]);
12427 if (!matchMode && appData.timeDelay != 0)
12428 DrawPosition(FALSE, boards[currentMove]);
12430 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
12431 programStats.ok_to_send = 1;
12434 /* if the first token after the PGN tags is a move
12435 * and not move number 1, retrieve it from the parser
12437 if (cm != MoveNumberOne)
12438 LoadGameOneMove(cm);
12440 /* load the remaining moves from the file */
12441 while (LoadGameOneMove(EndOfFile)) {
12442 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12443 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12446 /* rewind to the start of the game */
12447 currentMove = backwardMostMove;
12449 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12451 if (oldGameMode == AnalyzeFile) {
12452 appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
12453 AnalyzeFileEvent();
12455 if (oldGameMode == AnalyzeMode) {
12456 AnalyzeFileEvent();
12459 if(creatingBook) return TRUE;
12460 if (!matchMode && pos > 0) {
12461 ToNrEvent(pos); // [HGM] no autoplay if selected on position
12463 if (matchMode || appData.timeDelay == 0) {
12465 } else if (appData.timeDelay > 0) {
12466 AutoPlayGameLoop();
12469 if (appData.debugMode)
12470 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
12472 loadFlag = 0; /* [HGM] true game starts */
12476 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
12478 ReloadPosition (int offset)
12480 int positionNumber = lastLoadPositionNumber + offset;
12481 if (lastLoadPositionFP == NULL) {
12482 DisplayError(_("No position has been loaded yet"), 0);
12485 if (positionNumber <= 0) {
12486 DisplayError(_("Can't back up any further"), 0);
12489 return LoadPosition(lastLoadPositionFP, positionNumber,
12490 lastLoadPositionTitle);
12493 /* Load the nth position from the given file */
12495 LoadPositionFromFile (char *filename, int n, char *title)
12500 if (strcmp(filename, "-") == 0) {
12501 return LoadPosition(stdin, n, "stdin");
12503 f = fopen(filename, "rb");
12505 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12506 DisplayError(buf, errno);
12509 return LoadPosition(f, n, title);
12514 /* Load the nth position from the given open file, and close it */
12516 LoadPosition (FILE *f, int positionNumber, char *title)
12518 char *p, line[MSG_SIZ];
12519 Board initial_position;
12520 int i, j, fenMode, pn;
12522 if (gameMode == Training )
12523 SetTrainingModeOff();
12525 if (gameMode != BeginningOfGame) {
12526 Reset(FALSE, TRUE);
12528 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
12529 fclose(lastLoadPositionFP);
12531 if (positionNumber == 0) positionNumber = 1;
12532 lastLoadPositionFP = f;
12533 lastLoadPositionNumber = positionNumber;
12534 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
12535 if (first.pr == NoProc && !appData.noChessProgram) {
12536 StartChessProgram(&first);
12537 InitChessProgram(&first, FALSE);
12539 pn = positionNumber;
12540 if (positionNumber < 0) {
12541 /* Negative position number means to seek to that byte offset */
12542 if (fseek(f, -positionNumber, 0) == -1) {
12543 DisplayError(_("Can't seek on position file"), 0);
12548 if (fseek(f, 0, 0) == -1) {
12549 if (f == lastLoadPositionFP ?
12550 positionNumber == lastLoadPositionNumber + 1 :
12551 positionNumber == 1) {
12554 DisplayError(_("Can't seek on position file"), 0);
12559 /* See if this file is FEN or old-style xboard */
12560 if (fgets(line, MSG_SIZ, f) == NULL) {
12561 DisplayError(_("Position not found in file"), 0);
12564 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
12565 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
12568 if (fenMode || line[0] == '#') pn--;
12570 /* skip positions before number pn */
12571 if (fgets(line, MSG_SIZ, f) == NULL) {
12573 DisplayError(_("Position not found in file"), 0);
12576 if (fenMode || line[0] == '#') pn--;
12581 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
12582 DisplayError(_("Bad FEN position in file"), 0);
12586 (void) fgets(line, MSG_SIZ, f);
12587 (void) fgets(line, MSG_SIZ, f);
12589 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
12590 (void) fgets(line, MSG_SIZ, f);
12591 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
12594 initial_position[i][j++] = CharToPiece(*p);
12598 blackPlaysFirst = FALSE;
12600 (void) fgets(line, MSG_SIZ, f);
12601 if (strncmp(line, "black", strlen("black"))==0)
12602 blackPlaysFirst = TRUE;
12605 startedFromSetupPosition = TRUE;
12607 CopyBoard(boards[0], initial_position);
12608 if (blackPlaysFirst) {
12609 currentMove = forwardMostMove = backwardMostMove = 1;
12610 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12611 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12612 CopyBoard(boards[1], initial_position);
12613 DisplayMessage("", _("Black to play"));
12615 currentMove = forwardMostMove = backwardMostMove = 0;
12616 DisplayMessage("", _("White to play"));
12618 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
12619 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
12620 SendToProgram("force\n", &first);
12621 SendBoard(&first, forwardMostMove);
12623 if (appData.debugMode) {
12625 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
12626 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
12627 fprintf(debugFP, "Load Position\n");
12630 if (positionNumber > 1) {
12631 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
12632 DisplayTitle(line);
12634 DisplayTitle(title);
12636 gameMode = EditGame;
12639 timeRemaining[0][1] = whiteTimeRemaining;
12640 timeRemaining[1][1] = blackTimeRemaining;
12641 DrawPosition(FALSE, boards[currentMove]);
12648 CopyPlayerNameIntoFileName (char **dest, char *src)
12650 while (*src != NULLCHAR && *src != ',') {
12655 *(*dest)++ = *src++;
12661 DefaultFileName (char *ext)
12663 static char def[MSG_SIZ];
12666 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
12668 CopyPlayerNameIntoFileName(&p, gameInfo.white);
12670 CopyPlayerNameIntoFileName(&p, gameInfo.black);
12672 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
12679 /* Save the current game to the given file */
12681 SaveGameToFile (char *filename, int append)
12685 int result, i, t,tot=0;
12687 if (strcmp(filename, "-") == 0) {
12688 return SaveGame(stdout, 0, NULL);
12690 for(i=0; i<10; i++) { // upto 10 tries
12691 f = fopen(filename, append ? "a" : "w");
12692 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
12693 if(f || errno != 13) break;
12694 DoSleep(t = 5 + random()%11); // wait 5-15 msec
12698 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12699 DisplayError(buf, errno);
12702 safeStrCpy(buf, lastMsg, MSG_SIZ);
12703 DisplayMessage(_("Waiting for access to save file"), "");
12704 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
12705 DisplayMessage(_("Saving game"), "");
12706 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
12707 result = SaveGame(f, 0, NULL);
12708 DisplayMessage(buf, "");
12715 SavePart (char *str)
12717 static char buf[MSG_SIZ];
12720 p = strchr(str, ' ');
12721 if (p == NULL) return str;
12722 strncpy(buf, str, p - str);
12723 buf[p - str] = NULLCHAR;
12727 #define PGN_MAX_LINE 75
12729 #define PGN_SIDE_WHITE 0
12730 #define PGN_SIDE_BLACK 1
12733 FindFirstMoveOutOfBook (int side)
12737 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
12738 int index = backwardMostMove;
12739 int has_book_hit = 0;
12741 if( (index % 2) != side ) {
12745 while( index < forwardMostMove ) {
12746 /* Check to see if engine is in book */
12747 int depth = pvInfoList[index].depth;
12748 int score = pvInfoList[index].score;
12754 else if( score == 0 && depth == 63 ) {
12755 in_book = 1; /* Zappa */
12757 else if( score == 2 && depth == 99 ) {
12758 in_book = 1; /* Abrok */
12761 has_book_hit += in_book;
12777 GetOutOfBookInfo (char * buf)
12781 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12783 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
12784 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
12788 if( oob[0] >= 0 || oob[1] >= 0 ) {
12789 for( i=0; i<2; i++ ) {
12793 if( i > 0 && oob[0] >= 0 ) {
12794 strcat( buf, " " );
12797 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
12798 sprintf( buf+strlen(buf), "%s%.2f",
12799 pvInfoList[idx].score >= 0 ? "+" : "",
12800 pvInfoList[idx].score / 100.0 );
12806 /* Save game in PGN style and close the file */
12808 SaveGamePGN (FILE *f)
12810 int i, offset, linelen, newblock;
12813 int movelen, numlen, blank;
12814 char move_buffer[100]; /* [AS] Buffer for move+PV info */
12816 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12818 PrintPGNTags(f, &gameInfo);
12820 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
12822 if (backwardMostMove > 0 || startedFromSetupPosition) {
12823 char *fen = PositionToFEN(backwardMostMove, NULL);
12824 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
12825 fprintf(f, "\n{--------------\n");
12826 PrintPosition(f, backwardMostMove);
12827 fprintf(f, "--------------}\n");
12831 /* [AS] Out of book annotation */
12832 if( appData.saveOutOfBookInfo ) {
12835 GetOutOfBookInfo( buf );
12837 if( buf[0] != '\0' ) {
12838 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
12845 i = backwardMostMove;
12849 while (i < forwardMostMove) {
12850 /* Print comments preceding this move */
12851 if (commentList[i] != NULL) {
12852 if (linelen > 0) fprintf(f, "\n");
12853 fprintf(f, "%s", commentList[i]);
12858 /* Format move number */
12860 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
12863 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
12865 numtext[0] = NULLCHAR;
12867 numlen = strlen(numtext);
12870 /* Print move number */
12871 blank = linelen > 0 && numlen > 0;
12872 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
12881 fprintf(f, "%s", numtext);
12885 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
12886 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
12889 blank = linelen > 0 && movelen > 0;
12890 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12899 fprintf(f, "%s", move_buffer);
12900 linelen += movelen;
12902 /* [AS] Add PV info if present */
12903 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
12904 /* [HGM] add time */
12905 char buf[MSG_SIZ]; int seconds;
12907 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
12913 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
12916 seconds = (seconds + 4)/10; // round to full seconds
12918 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
12920 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
12923 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
12924 pvInfoList[i].score >= 0 ? "+" : "",
12925 pvInfoList[i].score / 100.0,
12926 pvInfoList[i].depth,
12929 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
12931 /* Print score/depth */
12932 blank = linelen > 0 && movelen > 0;
12933 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12942 fprintf(f, "%s", move_buffer);
12943 linelen += movelen;
12949 /* Start a new line */
12950 if (linelen > 0) fprintf(f, "\n");
12952 /* Print comments after last move */
12953 if (commentList[i] != NULL) {
12954 fprintf(f, "%s\n", commentList[i]);
12958 if (gameInfo.resultDetails != NULL &&
12959 gameInfo.resultDetails[0] != NULLCHAR) {
12960 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
12961 PGNResult(gameInfo.result));
12963 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12967 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12971 /* Save game in old style and close the file */
12973 SaveGameOldStyle (FILE *f)
12978 tm = time((time_t *) NULL);
12980 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
12983 if (backwardMostMove > 0 || startedFromSetupPosition) {
12984 fprintf(f, "\n[--------------\n");
12985 PrintPosition(f, backwardMostMove);
12986 fprintf(f, "--------------]\n");
12991 i = backwardMostMove;
12992 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12994 while (i < forwardMostMove) {
12995 if (commentList[i] != NULL) {
12996 fprintf(f, "[%s]\n", commentList[i]);
12999 if ((i % 2) == 1) {
13000 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
13003 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
13005 if (commentList[i] != NULL) {
13009 if (i >= forwardMostMove) {
13013 fprintf(f, "%s\n", parseList[i]);
13018 if (commentList[i] != NULL) {
13019 fprintf(f, "[%s]\n", commentList[i]);
13022 /* This isn't really the old style, but it's close enough */
13023 if (gameInfo.resultDetails != NULL &&
13024 gameInfo.resultDetails[0] != NULLCHAR) {
13025 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
13026 gameInfo.resultDetails);
13028 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13035 /* Save the current game to open file f and close the file */
13037 SaveGame (FILE *f, int dummy, char *dummy2)
13039 if (gameMode == EditPosition) EditPositionDone(TRUE);
13040 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13041 if (appData.oldSaveStyle)
13042 return SaveGameOldStyle(f);
13044 return SaveGamePGN(f);
13047 /* Save the current position to the given file */
13049 SavePositionToFile (char *filename)
13054 if (strcmp(filename, "-") == 0) {
13055 return SavePosition(stdout, 0, NULL);
13057 f = fopen(filename, "a");
13059 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13060 DisplayError(buf, errno);
13063 safeStrCpy(buf, lastMsg, MSG_SIZ);
13064 DisplayMessage(_("Waiting for access to save file"), "");
13065 flock(fileno(f), LOCK_EX); // [HGM] lock
13066 DisplayMessage(_("Saving position"), "");
13067 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
13068 SavePosition(f, 0, NULL);
13069 DisplayMessage(buf, "");
13075 /* Save the current position to the given open file and close the file */
13077 SavePosition (FILE *f, int dummy, char *dummy2)
13082 if (gameMode == EditPosition) EditPositionDone(TRUE);
13083 if (appData.oldSaveStyle) {
13084 tm = time((time_t *) NULL);
13086 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
13088 fprintf(f, "[--------------\n");
13089 PrintPosition(f, currentMove);
13090 fprintf(f, "--------------]\n");
13092 fen = PositionToFEN(currentMove, NULL);
13093 fprintf(f, "%s\n", fen);
13101 ReloadCmailMsgEvent (int unregister)
13104 static char *inFilename = NULL;
13105 static char *outFilename;
13107 struct stat inbuf, outbuf;
13110 /* Any registered moves are unregistered if unregister is set, */
13111 /* i.e. invoked by the signal handler */
13113 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13114 cmailMoveRegistered[i] = FALSE;
13115 if (cmailCommentList[i] != NULL) {
13116 free(cmailCommentList[i]);
13117 cmailCommentList[i] = NULL;
13120 nCmailMovesRegistered = 0;
13123 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13124 cmailResult[i] = CMAIL_NOT_RESULT;
13128 if (inFilename == NULL) {
13129 /* Because the filenames are static they only get malloced once */
13130 /* and they never get freed */
13131 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
13132 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
13134 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
13135 sprintf(outFilename, "%s.out", appData.cmailGameName);
13138 status = stat(outFilename, &outbuf);
13140 cmailMailedMove = FALSE;
13142 status = stat(inFilename, &inbuf);
13143 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
13146 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
13147 counts the games, notes how each one terminated, etc.
13149 It would be nice to remove this kludge and instead gather all
13150 the information while building the game list. (And to keep it
13151 in the game list nodes instead of having a bunch of fixed-size
13152 parallel arrays.) Note this will require getting each game's
13153 termination from the PGN tags, as the game list builder does
13154 not process the game moves. --mann
13156 cmailMsgLoaded = TRUE;
13157 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
13159 /* Load first game in the file or popup game menu */
13160 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
13162 #endif /* !WIN32 */
13170 char string[MSG_SIZ];
13172 if ( cmailMailedMove
13173 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
13174 return TRUE; /* Allow free viewing */
13177 /* Unregister move to ensure that we don't leave RegisterMove */
13178 /* with the move registered when the conditions for registering no */
13180 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
13181 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
13182 nCmailMovesRegistered --;
13184 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
13186 free(cmailCommentList[lastLoadGameNumber - 1]);
13187 cmailCommentList[lastLoadGameNumber - 1] = NULL;
13191 if (cmailOldMove == -1) {
13192 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
13196 if (currentMove > cmailOldMove + 1) {
13197 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
13201 if (currentMove < cmailOldMove) {
13202 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
13206 if (forwardMostMove > currentMove) {
13207 /* Silently truncate extra moves */
13211 if ( (currentMove == cmailOldMove + 1)
13212 || ( (currentMove == cmailOldMove)
13213 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
13214 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
13215 if (gameInfo.result != GameUnfinished) {
13216 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
13219 if (commentList[currentMove] != NULL) {
13220 cmailCommentList[lastLoadGameNumber - 1]
13221 = StrSave(commentList[currentMove]);
13223 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
13225 if (appData.debugMode)
13226 fprintf(debugFP, "Saving %s for game %d\n",
13227 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
13229 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
13231 f = fopen(string, "w");
13232 if (appData.oldSaveStyle) {
13233 SaveGameOldStyle(f); /* also closes the file */
13235 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
13236 f = fopen(string, "w");
13237 SavePosition(f, 0, NULL); /* also closes the file */
13239 fprintf(f, "{--------------\n");
13240 PrintPosition(f, currentMove);
13241 fprintf(f, "--------------}\n\n");
13243 SaveGame(f, 0, NULL); /* also closes the file*/
13246 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
13247 nCmailMovesRegistered ++;
13248 } else if (nCmailGames == 1) {
13249 DisplayError(_("You have not made a move yet"), 0);
13260 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
13261 FILE *commandOutput;
13262 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
13263 int nBytes = 0; /* Suppress warnings on uninitialized variables */
13269 if (! cmailMsgLoaded) {
13270 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
13274 if (nCmailGames == nCmailResults) {
13275 DisplayError(_("No unfinished games"), 0);
13279 #if CMAIL_PROHIBIT_REMAIL
13280 if (cmailMailedMove) {
13281 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);
13282 DisplayError(msg, 0);
13287 if (! (cmailMailedMove || RegisterMove())) return;
13289 if ( cmailMailedMove
13290 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
13291 snprintf(string, MSG_SIZ, partCommandString,
13292 appData.debugMode ? " -v" : "", appData.cmailGameName);
13293 commandOutput = popen(string, "r");
13295 if (commandOutput == NULL) {
13296 DisplayError(_("Failed to invoke cmail"), 0);
13298 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
13299 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
13301 if (nBuffers > 1) {
13302 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
13303 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
13304 nBytes = MSG_SIZ - 1;
13306 (void) memcpy(msg, buffer, nBytes);
13308 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
13310 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
13311 cmailMailedMove = TRUE; /* Prevent >1 moves */
13314 for (i = 0; i < nCmailGames; i ++) {
13315 if (cmailResult[i] == CMAIL_NOT_RESULT) {
13320 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
13322 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
13324 appData.cmailGameName,
13326 LoadGameFromFile(buffer, 1, buffer, FALSE);
13327 cmailMsgLoaded = FALSE;
13331 DisplayInformation(msg);
13332 pclose(commandOutput);
13335 if ((*cmailMsg) != '\0') {
13336 DisplayInformation(cmailMsg);
13341 #endif /* !WIN32 */
13350 int prependComma = 0;
13352 char string[MSG_SIZ]; /* Space for game-list */
13355 if (!cmailMsgLoaded) return "";
13357 if (cmailMailedMove) {
13358 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
13360 /* Create a list of games left */
13361 snprintf(string, MSG_SIZ, "[");
13362 for (i = 0; i < nCmailGames; i ++) {
13363 if (! ( cmailMoveRegistered[i]
13364 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
13365 if (prependComma) {
13366 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
13368 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
13372 strcat(string, number);
13375 strcat(string, "]");
13377 if (nCmailMovesRegistered + nCmailResults == 0) {
13378 switch (nCmailGames) {
13380 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
13384 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
13388 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
13393 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
13395 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
13400 if (nCmailResults == nCmailGames) {
13401 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
13403 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
13408 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
13420 if (gameMode == Training)
13421 SetTrainingModeOff();
13424 cmailMsgLoaded = FALSE;
13425 if (appData.icsActive) {
13426 SendToICS(ics_prefix);
13427 SendToICS("refresh\n");
13432 ExitEvent (int status)
13436 /* Give up on clean exit */
13440 /* Keep trying for clean exit */
13444 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
13446 if (telnetISR != NULL) {
13447 RemoveInputSource(telnetISR);
13449 if (icsPR != NoProc) {
13450 DestroyChildProcess(icsPR, TRUE);
13453 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
13454 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
13456 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
13457 /* make sure this other one finishes before killing it! */
13458 if(endingGame) { int count = 0;
13459 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
13460 while(endingGame && count++ < 10) DoSleep(1);
13461 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
13464 /* Kill off chess programs */
13465 if (first.pr != NoProc) {
13468 DoSleep( appData.delayBeforeQuit );
13469 SendToProgram("quit\n", &first);
13470 DoSleep( appData.delayAfterQuit );
13471 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
13473 if (second.pr != NoProc) {
13474 DoSleep( appData.delayBeforeQuit );
13475 SendToProgram("quit\n", &second);
13476 DoSleep( appData.delayAfterQuit );
13477 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
13479 if (first.isr != NULL) {
13480 RemoveInputSource(first.isr);
13482 if (second.isr != NULL) {
13483 RemoveInputSource(second.isr);
13486 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
13487 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
13489 ShutDownFrontEnd();
13494 PauseEngine (ChessProgramState *cps)
13496 SendToProgram("pause\n", cps);
13501 UnPauseEngine (ChessProgramState *cps)
13503 SendToProgram("resume\n", cps);
13510 if (appData.debugMode)
13511 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
13515 if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
13517 if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
13518 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
13519 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
13521 if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
13522 HandleMachineMove(stashedInputMove, stalledEngine);
13523 stalledEngine = NULL;
13526 if (gameMode == MachinePlaysWhite ||
13527 gameMode == TwoMachinesPlay ||
13528 gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
13529 if(first.pause) UnPauseEngine(&first);
13530 else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
13531 if(second.pause) UnPauseEngine(&second);
13532 else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
13535 DisplayBothClocks();
13537 if (gameMode == PlayFromGameFile) {
13538 if (appData.timeDelay >= 0)
13539 AutoPlayGameLoop();
13540 } else if (gameMode == IcsExamining && pauseExamInvalid) {
13541 Reset(FALSE, TRUE);
13542 SendToICS(ics_prefix);
13543 SendToICS("refresh\n");
13544 } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
13545 ForwardInner(forwardMostMove);
13547 pauseExamInvalid = FALSE;
13549 switch (gameMode) {
13553 pauseExamForwardMostMove = forwardMostMove;
13554 pauseExamInvalid = FALSE;
13557 case IcsPlayingWhite:
13558 case IcsPlayingBlack:
13562 case PlayFromGameFile:
13563 (void) StopLoadGameTimer();
13567 case BeginningOfGame:
13568 if (appData.icsActive) return;
13569 /* else fall through */
13570 case MachinePlaysWhite:
13571 case MachinePlaysBlack:
13572 case TwoMachinesPlay:
13573 if (forwardMostMove == 0)
13574 return; /* don't pause if no one has moved */
13575 if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
13576 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
13577 if(onMove->pause) { // thinking engine can be paused
13578 PauseEngine(onMove); // do it
13579 if(onMove->other->pause) // pondering opponent can always be paused immediately
13580 PauseEngine(onMove->other);
13582 SendToProgram("easy\n", onMove->other);
13584 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
13585 } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
13587 PauseEngine(&first);
13589 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
13590 } else { // human on move, pause pondering by either method
13592 PauseEngine(&first);
13593 else if(appData.ponderNextMove)
13594 SendToProgram("easy\n", &first);
13597 // if no immediate pausing is possible, wait for engine to move, and stop clocks then
13607 EditCommentEvent ()
13609 char title[MSG_SIZ];
13611 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
13612 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
13614 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
13615 WhiteOnMove(currentMove - 1) ? " " : ".. ",
13616 parseList[currentMove - 1]);
13619 EditCommentPopUp(currentMove, title, commentList[currentMove]);
13626 char *tags = PGNTags(&gameInfo);
13628 EditTagsPopUp(tags, NULL);
13635 if(second.analyzing) {
13636 SendToProgram("exit\n", &second);
13637 second.analyzing = FALSE;
13639 if (second.pr == NoProc) StartChessProgram(&second);
13640 InitChessProgram(&second, FALSE);
13641 FeedMovesToProgram(&second, currentMove);
13643 SendToProgram("analyze\n", &second);
13644 second.analyzing = TRUE;
13648 /* Toggle ShowThinking */
13650 ToggleShowThinking()
13652 appData.showThinking = !appData.showThinking;
13653 ShowThinkingEvent();
13657 AnalyzeModeEvent ()
13661 if (!first.analysisSupport) {
13662 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
13663 DisplayError(buf, 0);
13666 /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
13667 if (appData.icsActive) {
13668 if (gameMode != IcsObserving) {
13669 snprintf(buf, MSG_SIZ, _("You are not observing a game"));
13670 DisplayError(buf, 0);
13672 if (appData.icsEngineAnalyze) {
13673 if (appData.debugMode)
13674 fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
13680 /* if enable, user wants to disable icsEngineAnalyze */
13681 if (appData.icsEngineAnalyze) {
13686 appData.icsEngineAnalyze = TRUE;
13687 if (appData.debugMode)
13688 fprintf(debugFP, "ICS engine analyze starting... \n");
13691 if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
13692 if (appData.noChessProgram || gameMode == AnalyzeMode)
13695 if (gameMode != AnalyzeFile) {
13696 if (!appData.icsEngineAnalyze) {
13698 if (gameMode != EditGame) return 0;
13700 if (!appData.showThinking) ToggleShowThinking();
13701 ResurrectChessProgram();
13702 SendToProgram("analyze\n", &first);
13703 first.analyzing = TRUE;
13704 /*first.maybeThinking = TRUE;*/
13705 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13706 EngineOutputPopUp();
13708 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
13713 StartAnalysisClock();
13714 GetTimeMark(&lastNodeCountTime);
13720 AnalyzeFileEvent ()
13722 if (appData.noChessProgram || gameMode == AnalyzeFile)
13725 if (!first.analysisSupport) {
13727 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
13728 DisplayError(buf, 0);
13732 if (gameMode != AnalyzeMode) {
13733 keepInfo = 1; // mere annotating should not alter PGN tags
13736 if (gameMode != EditGame) return;
13737 if (!appData.showThinking) ToggleShowThinking();
13738 ResurrectChessProgram();
13739 SendToProgram("analyze\n", &first);
13740 first.analyzing = TRUE;
13741 /*first.maybeThinking = TRUE;*/
13742 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13743 EngineOutputPopUp();
13745 gameMode = AnalyzeFile;
13749 StartAnalysisClock();
13750 GetTimeMark(&lastNodeCountTime);
13752 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
13753 AnalysisPeriodicEvent(1);
13757 MachineWhiteEvent ()
13760 char *bookHit = NULL;
13762 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
13766 if (gameMode == PlayFromGameFile ||
13767 gameMode == TwoMachinesPlay ||
13768 gameMode == Training ||
13769 gameMode == AnalyzeMode ||
13770 gameMode == EndOfGame)
13773 if (gameMode == EditPosition)
13774 EditPositionDone(TRUE);
13776 if (!WhiteOnMove(currentMove)) {
13777 DisplayError(_("It is not White's turn"), 0);
13781 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13784 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13785 gameMode == AnalyzeFile)
13788 ResurrectChessProgram(); /* in case it isn't running */
13789 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
13790 gameMode = MachinePlaysWhite;
13793 gameMode = MachinePlaysWhite;
13797 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13799 if (first.sendName) {
13800 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
13801 SendToProgram(buf, &first);
13803 if (first.sendTime) {
13804 if (first.useColors) {
13805 SendToProgram("black\n", &first); /*gnu kludge*/
13807 SendTimeRemaining(&first, TRUE);
13809 if (first.useColors) {
13810 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
13812 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13813 SetMachineThinkingEnables();
13814 first.maybeThinking = TRUE;
13818 if (appData.autoFlipView && !flipView) {
13819 flipView = !flipView;
13820 DrawPosition(FALSE, NULL);
13821 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13824 if(bookHit) { // [HGM] book: simulate book reply
13825 static char bookMove[MSG_SIZ]; // a bit generous?
13827 programStats.nodes = programStats.depth = programStats.time =
13828 programStats.score = programStats.got_only_move = 0;
13829 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13831 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13832 strcat(bookMove, bookHit);
13833 HandleMachineMove(bookMove, &first);
13838 MachineBlackEvent ()
13841 char *bookHit = NULL;
13843 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
13847 if (gameMode == PlayFromGameFile ||
13848 gameMode == TwoMachinesPlay ||
13849 gameMode == Training ||
13850 gameMode == AnalyzeMode ||
13851 gameMode == EndOfGame)
13854 if (gameMode == EditPosition)
13855 EditPositionDone(TRUE);
13857 if (WhiteOnMove(currentMove)) {
13858 DisplayError(_("It is not Black's turn"), 0);
13862 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13865 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13866 gameMode == AnalyzeFile)
13869 ResurrectChessProgram(); /* in case it isn't running */
13870 gameMode = MachinePlaysBlack;
13874 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13876 if (first.sendName) {
13877 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
13878 SendToProgram(buf, &first);
13880 if (first.sendTime) {
13881 if (first.useColors) {
13882 SendToProgram("white\n", &first); /*gnu kludge*/
13884 SendTimeRemaining(&first, FALSE);
13886 if (first.useColors) {
13887 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
13889 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13890 SetMachineThinkingEnables();
13891 first.maybeThinking = TRUE;
13894 if (appData.autoFlipView && flipView) {
13895 flipView = !flipView;
13896 DrawPosition(FALSE, NULL);
13897 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13899 if(bookHit) { // [HGM] book: simulate book reply
13900 static char bookMove[MSG_SIZ]; // a bit generous?
13902 programStats.nodes = programStats.depth = programStats.time =
13903 programStats.score = programStats.got_only_move = 0;
13904 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13906 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13907 strcat(bookMove, bookHit);
13908 HandleMachineMove(bookMove, &first);
13914 DisplayTwoMachinesTitle ()
13917 if (appData.matchGames > 0) {
13918 if(appData.tourneyFile[0]) {
13919 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
13920 gameInfo.white, _("vs."), gameInfo.black,
13921 nextGame+1, appData.matchGames+1,
13922 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
13924 if (first.twoMachinesColor[0] == 'w') {
13925 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13926 gameInfo.white, _("vs."), gameInfo.black,
13927 first.matchWins, second.matchWins,
13928 matchGame - 1 - (first.matchWins + second.matchWins));
13930 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13931 gameInfo.white, _("vs."), gameInfo.black,
13932 second.matchWins, first.matchWins,
13933 matchGame - 1 - (first.matchWins + second.matchWins));
13936 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13942 SettingsMenuIfReady ()
13944 if (second.lastPing != second.lastPong) {
13945 DisplayMessage("", _("Waiting for second chess program"));
13946 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
13950 DisplayMessage("", "");
13951 SettingsPopUp(&second);
13955 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
13958 if (cps->pr == NoProc) {
13959 StartChessProgram(cps);
13960 if (cps->protocolVersion == 1) {
13962 ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
13964 /* kludge: allow timeout for initial "feature" command */
13965 if(retry != TwoMachinesEventIfReady) FreezeUI();
13966 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
13967 DisplayMessage("", buf);
13968 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
13976 TwoMachinesEvent P((void))
13980 ChessProgramState *onmove;
13981 char *bookHit = NULL;
13982 static int stalling = 0;
13986 if (appData.noChessProgram) return;
13988 switch (gameMode) {
13989 case TwoMachinesPlay:
13991 case MachinePlaysWhite:
13992 case MachinePlaysBlack:
13993 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13994 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13998 case BeginningOfGame:
13999 case PlayFromGameFile:
14002 if (gameMode != EditGame) return;
14005 EditPositionDone(TRUE);
14016 // forwardMostMove = currentMove;
14017 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
14018 startingEngine = TRUE;
14020 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
14022 if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
14023 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
14024 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14027 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
14029 if(second.protocolVersion >= 2 && !strstr(second.variants, VariantName(gameInfo.variant))) {
14030 startingEngine = FALSE;
14031 DisplayError("second engine does not play this", 0);
14036 InitChessProgram(&second, FALSE); // unbalances ping of second engine
14037 SendToProgram("force\n", &second);
14039 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14042 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
14043 if(appData.matchPause>10000 || appData.matchPause<10)
14044 appData.matchPause = 10000; /* [HGM] make pause adjustable */
14045 wait = SubtractTimeMarks(&now, &pauseStart);
14046 if(wait < appData.matchPause) {
14047 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
14050 // we are now committed to starting the game
14052 DisplayMessage("", "");
14053 if (startedFromSetupPosition) {
14054 SendBoard(&second, backwardMostMove);
14055 if (appData.debugMode) {
14056 fprintf(debugFP, "Two Machines\n");
14059 for (i = backwardMostMove; i < forwardMostMove; i++) {
14060 SendMoveToProgram(i, &second);
14063 gameMode = TwoMachinesPlay;
14064 pausing = startingEngine = FALSE;
14065 ModeHighlight(); // [HGM] logo: this triggers display update of logos
14067 DisplayTwoMachinesTitle();
14069 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
14074 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
14075 SendToProgram(first.computerString, &first);
14076 if (first.sendName) {
14077 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
14078 SendToProgram(buf, &first);
14080 SendToProgram(second.computerString, &second);
14081 if (second.sendName) {
14082 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
14083 SendToProgram(buf, &second);
14087 if (!first.sendTime || !second.sendTime) {
14088 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14089 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14091 if (onmove->sendTime) {
14092 if (onmove->useColors) {
14093 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
14095 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
14097 if (onmove->useColors) {
14098 SendToProgram(onmove->twoMachinesColor, onmove);
14100 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
14101 // SendToProgram("go\n", onmove);
14102 onmove->maybeThinking = TRUE;
14103 SetMachineThinkingEnables();
14107 if(bookHit) { // [HGM] book: simulate book reply
14108 static char bookMove[MSG_SIZ]; // a bit generous?
14110 programStats.nodes = programStats.depth = programStats.time =
14111 programStats.score = programStats.got_only_move = 0;
14112 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14114 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14115 strcat(bookMove, bookHit);
14116 savedMessage = bookMove; // args for deferred call
14117 savedState = onmove;
14118 ScheduleDelayedEvent(DeferredBookMove, 1);
14125 if (gameMode == Training) {
14126 SetTrainingModeOff();
14127 gameMode = PlayFromGameFile;
14128 DisplayMessage("", _("Training mode off"));
14130 gameMode = Training;
14131 animateTraining = appData.animate;
14133 /* make sure we are not already at the end of the game */
14134 if (currentMove < forwardMostMove) {
14135 SetTrainingModeOn();
14136 DisplayMessage("", _("Training mode on"));
14138 gameMode = PlayFromGameFile;
14139 DisplayError(_("Already at end of game"), 0);
14148 if (!appData.icsActive) return;
14149 switch (gameMode) {
14150 case IcsPlayingWhite:
14151 case IcsPlayingBlack:
14154 case BeginningOfGame:
14162 EditPositionDone(TRUE);
14175 gameMode = IcsIdle;
14185 switch (gameMode) {
14187 SetTrainingModeOff();
14189 case MachinePlaysWhite:
14190 case MachinePlaysBlack:
14191 case BeginningOfGame:
14192 SendToProgram("force\n", &first);
14193 SetUserThinkingEnables();
14195 case PlayFromGameFile:
14196 (void) StopLoadGameTimer();
14197 if (gameFileFP != NULL) {
14202 EditPositionDone(TRUE);
14207 SendToProgram("force\n", &first);
14209 case TwoMachinesPlay:
14210 GameEnds(EndOfFile, NULL, GE_PLAYER);
14211 ResurrectChessProgram();
14212 SetUserThinkingEnables();
14215 ResurrectChessProgram();
14217 case IcsPlayingBlack:
14218 case IcsPlayingWhite:
14219 DisplayError(_("Warning: You are still playing a game"), 0);
14222 DisplayError(_("Warning: You are still observing a game"), 0);
14225 DisplayError(_("Warning: You are still examining a game"), 0);
14236 first.offeredDraw = second.offeredDraw = 0;
14238 if (gameMode == PlayFromGameFile) {
14239 whiteTimeRemaining = timeRemaining[0][currentMove];
14240 blackTimeRemaining = timeRemaining[1][currentMove];
14244 if (gameMode == MachinePlaysWhite ||
14245 gameMode == MachinePlaysBlack ||
14246 gameMode == TwoMachinesPlay ||
14247 gameMode == EndOfGame) {
14248 i = forwardMostMove;
14249 while (i > currentMove) {
14250 SendToProgram("undo\n", &first);
14253 if(!adjustedClock) {
14254 whiteTimeRemaining = timeRemaining[0][currentMove];
14255 blackTimeRemaining = timeRemaining[1][currentMove];
14256 DisplayBothClocks();
14258 if (whiteFlag || blackFlag) {
14259 whiteFlag = blackFlag = 0;
14264 gameMode = EditGame;
14271 EditPositionEvent ()
14273 if (gameMode == EditPosition) {
14279 if (gameMode != EditGame) return;
14281 gameMode = EditPosition;
14284 if (currentMove > 0)
14285 CopyBoard(boards[0], boards[currentMove]);
14287 blackPlaysFirst = !WhiteOnMove(currentMove);
14289 currentMove = forwardMostMove = backwardMostMove = 0;
14290 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14292 if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
14298 /* [DM] icsEngineAnalyze - possible call from other functions */
14299 if (appData.icsEngineAnalyze) {
14300 appData.icsEngineAnalyze = FALSE;
14302 DisplayMessage("",_("Close ICS engine analyze..."));
14304 if (first.analysisSupport && first.analyzing) {
14305 SendToBoth("exit\n");
14306 first.analyzing = second.analyzing = FALSE;
14308 thinkOutput[0] = NULLCHAR;
14312 EditPositionDone (Boolean fakeRights)
14314 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
14316 startedFromSetupPosition = TRUE;
14317 InitChessProgram(&first, FALSE);
14318 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
14319 boards[0][EP_STATUS] = EP_NONE;
14320 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
14321 if(boards[0][0][BOARD_WIDTH>>1] == king) {
14322 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? BOARD_LEFT : NoRights;
14323 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
14324 } else boards[0][CASTLING][2] = NoRights;
14325 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
14326 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? BOARD_LEFT : NoRights;
14327 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
14328 } else boards[0][CASTLING][5] = NoRights;
14329 if(gameInfo.variant == VariantSChess) {
14331 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // pieces in their original position are assumed virgin
14332 boards[0][VIRGIN][i] = 0;
14333 if(boards[0][0][i] == FIDEArray[0][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_W;
14334 if(boards[0][BOARD_HEIGHT-1][i] == FIDEArray[1][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_B;
14338 SendToProgram("force\n", &first);
14339 if (blackPlaysFirst) {
14340 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
14341 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
14342 currentMove = forwardMostMove = backwardMostMove = 1;
14343 CopyBoard(boards[1], boards[0]);
14345 currentMove = forwardMostMove = backwardMostMove = 0;
14347 SendBoard(&first, forwardMostMove);
14348 if (appData.debugMode) {
14349 fprintf(debugFP, "EditPosDone\n");
14352 DisplayMessage("", "");
14353 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14354 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14355 gameMode = EditGame;
14357 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14358 ClearHighlights(); /* [AS] */
14361 /* Pause for `ms' milliseconds */
14362 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14364 TimeDelay (long ms)
14371 } while (SubtractTimeMarks(&m2, &m1) < ms);
14374 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14376 SendMultiLineToICS (char *buf)
14378 char temp[MSG_SIZ+1], *p;
14385 strncpy(temp, buf, len);
14390 if (*p == '\n' || *p == '\r')
14395 strcat(temp, "\n");
14397 SendToPlayer(temp, strlen(temp));
14401 SetWhiteToPlayEvent ()
14403 if (gameMode == EditPosition) {
14404 blackPlaysFirst = FALSE;
14405 DisplayBothClocks(); /* works because currentMove is 0 */
14406 } else if (gameMode == IcsExamining) {
14407 SendToICS(ics_prefix);
14408 SendToICS("tomove white\n");
14413 SetBlackToPlayEvent ()
14415 if (gameMode == EditPosition) {
14416 blackPlaysFirst = TRUE;
14417 currentMove = 1; /* kludge */
14418 DisplayBothClocks();
14420 } else if (gameMode == IcsExamining) {
14421 SendToICS(ics_prefix);
14422 SendToICS("tomove black\n");
14427 EditPositionMenuEvent (ChessSquare selection, int x, int y)
14430 ChessSquare piece = boards[0][y][x];
14432 if (gameMode != EditPosition && gameMode != IcsExamining) return;
14434 switch (selection) {
14436 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
14437 SendToICS(ics_prefix);
14438 SendToICS("bsetup clear\n");
14439 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
14440 SendToICS(ics_prefix);
14441 SendToICS("clearboard\n");
14443 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
14444 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
14445 for (y = 0; y < BOARD_HEIGHT; y++) {
14446 if (gameMode == IcsExamining) {
14447 if (boards[currentMove][y][x] != EmptySquare) {
14448 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
14453 boards[0][y][x] = p;
14458 if (gameMode == EditPosition) {
14459 DrawPosition(FALSE, boards[0]);
14464 SetWhiteToPlayEvent();
14468 SetBlackToPlayEvent();
14472 if (gameMode == IcsExamining) {
14473 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14474 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
14477 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14478 if(x == BOARD_LEFT-2) {
14479 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
14480 boards[0][y][1] = 0;
14482 if(x == BOARD_RGHT+1) {
14483 if(y >= gameInfo.holdingsSize) break;
14484 boards[0][y][BOARD_WIDTH-2] = 0;
14487 boards[0][y][x] = EmptySquare;
14488 DrawPosition(FALSE, boards[0]);
14493 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
14494 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
14495 selection = (ChessSquare) (PROMOTED piece);
14496 } else if(piece == EmptySquare) selection = WhiteSilver;
14497 else selection = (ChessSquare)((int)piece - 1);
14501 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
14502 piece > (int)BlackMan && piece <= (int)BlackKing ) {
14503 selection = (ChessSquare) (DEMOTED piece);
14504 } else if(piece == EmptySquare) selection = BlackSilver;
14505 else selection = (ChessSquare)((int)piece + 1);
14510 if(gameInfo.variant == VariantShatranj ||
14511 gameInfo.variant == VariantXiangqi ||
14512 gameInfo.variant == VariantCourier ||
14513 gameInfo.variant == VariantMakruk )
14514 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
14519 if(gameInfo.variant == VariantXiangqi)
14520 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
14521 if(gameInfo.variant == VariantKnightmate)
14522 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
14525 if (gameMode == IcsExamining) {
14526 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14527 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
14528 PieceToChar(selection), AAA + x, ONE + y);
14531 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14533 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
14534 n = PieceToNumber(selection - BlackPawn);
14535 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
14536 boards[0][BOARD_HEIGHT-1-n][0] = selection;
14537 boards[0][BOARD_HEIGHT-1-n][1]++;
14539 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
14540 n = PieceToNumber(selection);
14541 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
14542 boards[0][n][BOARD_WIDTH-1] = selection;
14543 boards[0][n][BOARD_WIDTH-2]++;
14546 boards[0][y][x] = selection;
14547 DrawPosition(TRUE, boards[0]);
14549 fromX = fromY = -1;
14557 DropMenuEvent (ChessSquare selection, int x, int y)
14559 ChessMove moveType;
14561 switch (gameMode) {
14562 case IcsPlayingWhite:
14563 case MachinePlaysBlack:
14564 if (!WhiteOnMove(currentMove)) {
14565 DisplayMoveError(_("It is Black's turn"));
14568 moveType = WhiteDrop;
14570 case IcsPlayingBlack:
14571 case MachinePlaysWhite:
14572 if (WhiteOnMove(currentMove)) {
14573 DisplayMoveError(_("It is White's turn"));
14576 moveType = BlackDrop;
14579 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
14585 if (moveType == BlackDrop && selection < BlackPawn) {
14586 selection = (ChessSquare) ((int) selection
14587 + (int) BlackPawn - (int) WhitePawn);
14589 if (boards[currentMove][y][x] != EmptySquare) {
14590 DisplayMoveError(_("That square is occupied"));
14594 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
14600 /* Accept a pending offer of any kind from opponent */
14602 if (appData.icsActive) {
14603 SendToICS(ics_prefix);
14604 SendToICS("accept\n");
14605 } else if (cmailMsgLoaded) {
14606 if (currentMove == cmailOldMove &&
14607 commentList[cmailOldMove] != NULL &&
14608 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14609 "Black offers a draw" : "White offers a draw")) {
14611 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14612 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14614 DisplayError(_("There is no pending offer on this move"), 0);
14615 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14618 /* Not used for offers from chess program */
14625 /* Decline a pending offer of any kind from opponent */
14627 if (appData.icsActive) {
14628 SendToICS(ics_prefix);
14629 SendToICS("decline\n");
14630 } else if (cmailMsgLoaded) {
14631 if (currentMove == cmailOldMove &&
14632 commentList[cmailOldMove] != NULL &&
14633 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14634 "Black offers a draw" : "White offers a draw")) {
14636 AppendComment(cmailOldMove, "Draw declined", TRUE);
14637 DisplayComment(cmailOldMove - 1, "Draw declined");
14640 DisplayError(_("There is no pending offer on this move"), 0);
14643 /* Not used for offers from chess program */
14650 /* Issue ICS rematch command */
14651 if (appData.icsActive) {
14652 SendToICS(ics_prefix);
14653 SendToICS("rematch\n");
14660 /* Call your opponent's flag (claim a win on time) */
14661 if (appData.icsActive) {
14662 SendToICS(ics_prefix);
14663 SendToICS("flag\n");
14665 switch (gameMode) {
14668 case MachinePlaysWhite:
14671 GameEnds(GameIsDrawn, "Both players ran out of time",
14674 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
14676 DisplayError(_("Your opponent is not out of time"), 0);
14679 case MachinePlaysBlack:
14682 GameEnds(GameIsDrawn, "Both players ran out of time",
14685 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
14687 DisplayError(_("Your opponent is not out of time"), 0);
14695 ClockClick (int which)
14696 { // [HGM] code moved to back-end from winboard.c
14697 if(which) { // black clock
14698 if (gameMode == EditPosition || gameMode == IcsExamining) {
14699 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14700 SetBlackToPlayEvent();
14701 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !blackFlag && WhiteOnMove(currentMove)) {
14702 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
14703 } else if (shiftKey) {
14704 AdjustClock(which, -1);
14705 } else if (gameMode == IcsPlayingWhite ||
14706 gameMode == MachinePlaysBlack) {
14709 } else { // white clock
14710 if (gameMode == EditPosition || gameMode == IcsExamining) {
14711 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14712 SetWhiteToPlayEvent();
14713 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !whiteFlag && !WhiteOnMove(currentMove)) {
14714 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
14715 } else if (shiftKey) {
14716 AdjustClock(which, -1);
14717 } else if (gameMode == IcsPlayingBlack ||
14718 gameMode == MachinePlaysWhite) {
14727 /* Offer draw or accept pending draw offer from opponent */
14729 if (appData.icsActive) {
14730 /* Note: tournament rules require draw offers to be
14731 made after you make your move but before you punch
14732 your clock. Currently ICS doesn't let you do that;
14733 instead, you immediately punch your clock after making
14734 a move, but you can offer a draw at any time. */
14736 SendToICS(ics_prefix);
14737 SendToICS("draw\n");
14738 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
14739 } else if (cmailMsgLoaded) {
14740 if (currentMove == cmailOldMove &&
14741 commentList[cmailOldMove] != NULL &&
14742 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14743 "Black offers a draw" : "White offers a draw")) {
14744 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14745 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14746 } else if (currentMove == cmailOldMove + 1) {
14747 char *offer = WhiteOnMove(cmailOldMove) ?
14748 "White offers a draw" : "Black offers a draw";
14749 AppendComment(currentMove, offer, TRUE);
14750 DisplayComment(currentMove - 1, offer);
14751 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
14753 DisplayError(_("You must make your move before offering a draw"), 0);
14754 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14756 } else if (first.offeredDraw) {
14757 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
14759 if (first.sendDrawOffers) {
14760 SendToProgram("draw\n", &first);
14761 userOfferedDraw = TRUE;
14769 /* Offer Adjourn or accept pending Adjourn offer from opponent */
14771 if (appData.icsActive) {
14772 SendToICS(ics_prefix);
14773 SendToICS("adjourn\n");
14775 /* Currently GNU Chess doesn't offer or accept Adjourns */
14783 /* Offer Abort or accept pending Abort offer from opponent */
14785 if (appData.icsActive) {
14786 SendToICS(ics_prefix);
14787 SendToICS("abort\n");
14789 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
14796 /* Resign. You can do this even if it's not your turn. */
14798 if (appData.icsActive) {
14799 SendToICS(ics_prefix);
14800 SendToICS("resign\n");
14802 switch (gameMode) {
14803 case MachinePlaysWhite:
14804 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14806 case MachinePlaysBlack:
14807 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14810 if (cmailMsgLoaded) {
14812 if (WhiteOnMove(cmailOldMove)) {
14813 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14815 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14817 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
14828 StopObservingEvent ()
14830 /* Stop observing current games */
14831 SendToICS(ics_prefix);
14832 SendToICS("unobserve\n");
14836 StopExaminingEvent ()
14838 /* Stop observing current game */
14839 SendToICS(ics_prefix);
14840 SendToICS("unexamine\n");
14844 ForwardInner (int target)
14846 int limit; int oldSeekGraphUp = seekGraphUp;
14848 if (appData.debugMode)
14849 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
14850 target, currentMove, forwardMostMove);
14852 if (gameMode == EditPosition)
14855 seekGraphUp = FALSE;
14856 MarkTargetSquares(1);
14858 if (gameMode == PlayFromGameFile && !pausing)
14861 if (gameMode == IcsExamining && pausing)
14862 limit = pauseExamForwardMostMove;
14864 limit = forwardMostMove;
14866 if (target > limit) target = limit;
14868 if (target > 0 && moveList[target - 1][0]) {
14869 int fromX, fromY, toX, toY;
14870 toX = moveList[target - 1][2] - AAA;
14871 toY = moveList[target - 1][3] - ONE;
14872 if (moveList[target - 1][1] == '@') {
14873 if (appData.highlightLastMove) {
14874 SetHighlights(-1, -1, toX, toY);
14877 fromX = moveList[target - 1][0] - AAA;
14878 fromY = moveList[target - 1][1] - ONE;
14879 if (target == currentMove + 1) {
14880 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
14882 if (appData.highlightLastMove) {
14883 SetHighlights(fromX, fromY, toX, toY);
14887 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14888 gameMode == Training || gameMode == PlayFromGameFile ||
14889 gameMode == AnalyzeFile) {
14890 while (currentMove < target) {
14891 if(second.analyzing) SendMoveToProgram(currentMove, &second);
14892 SendMoveToProgram(currentMove++, &first);
14895 currentMove = target;
14898 if (gameMode == EditGame || gameMode == EndOfGame) {
14899 whiteTimeRemaining = timeRemaining[0][currentMove];
14900 blackTimeRemaining = timeRemaining[1][currentMove];
14902 DisplayBothClocks();
14903 DisplayMove(currentMove - 1);
14904 DrawPosition(oldSeekGraphUp, boards[currentMove]);
14905 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14906 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
14907 DisplayComment(currentMove - 1, commentList[currentMove]);
14909 ClearMap(); // [HGM] exclude: invalidate map
14916 if (gameMode == IcsExamining && !pausing) {
14917 SendToICS(ics_prefix);
14918 SendToICS("forward\n");
14920 ForwardInner(currentMove + 1);
14927 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14928 /* to optimze, we temporarily turn off analysis mode while we feed
14929 * the remaining moves to the engine. Otherwise we get analysis output
14932 if (first.analysisSupport) {
14933 SendToProgram("exit\nforce\n", &first);
14934 first.analyzing = FALSE;
14938 if (gameMode == IcsExamining && !pausing) {
14939 SendToICS(ics_prefix);
14940 SendToICS("forward 999999\n");
14942 ForwardInner(forwardMostMove);
14945 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14946 /* we have fed all the moves, so reactivate analysis mode */
14947 SendToProgram("analyze\n", &first);
14948 first.analyzing = TRUE;
14949 /*first.maybeThinking = TRUE;*/
14950 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14955 BackwardInner (int target)
14957 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
14959 if (appData.debugMode)
14960 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
14961 target, currentMove, forwardMostMove);
14963 if (gameMode == EditPosition) return;
14964 seekGraphUp = FALSE;
14965 MarkTargetSquares(1);
14966 if (currentMove <= backwardMostMove) {
14968 DrawPosition(full_redraw, boards[currentMove]);
14971 if (gameMode == PlayFromGameFile && !pausing)
14974 if (moveList[target][0]) {
14975 int fromX, fromY, toX, toY;
14976 toX = moveList[target][2] - AAA;
14977 toY = moveList[target][3] - ONE;
14978 if (moveList[target][1] == '@') {
14979 if (appData.highlightLastMove) {
14980 SetHighlights(-1, -1, toX, toY);
14983 fromX = moveList[target][0] - AAA;
14984 fromY = moveList[target][1] - ONE;
14985 if (target == currentMove - 1) {
14986 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
14988 if (appData.highlightLastMove) {
14989 SetHighlights(fromX, fromY, toX, toY);
14993 if (gameMode == EditGame || gameMode==AnalyzeMode ||
14994 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
14995 while (currentMove > target) {
14996 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
14997 // null move cannot be undone. Reload program with move history before it.
14999 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
15000 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
15002 SendBoard(&first, i);
15003 if(second.analyzing) SendBoard(&second, i);
15004 for(currentMove=i; currentMove<target; currentMove++) {
15005 SendMoveToProgram(currentMove, &first);
15006 if(second.analyzing) SendMoveToProgram(currentMove, &second);
15010 SendToBoth("undo\n");
15014 currentMove = target;
15017 if (gameMode == EditGame || gameMode == EndOfGame) {
15018 whiteTimeRemaining = timeRemaining[0][currentMove];
15019 blackTimeRemaining = timeRemaining[1][currentMove];
15021 DisplayBothClocks();
15022 DisplayMove(currentMove - 1);
15023 DrawPosition(full_redraw, boards[currentMove]);
15024 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15025 // [HGM] PV info: routine tests if comment empty
15026 DisplayComment(currentMove - 1, commentList[currentMove]);
15027 ClearMap(); // [HGM] exclude: invalidate map
15033 if (gameMode == IcsExamining && !pausing) {
15034 SendToICS(ics_prefix);
15035 SendToICS("backward\n");
15037 BackwardInner(currentMove - 1);
15044 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15045 /* to optimize, we temporarily turn off analysis mode while we undo
15046 * all the moves. Otherwise we get analysis output after each undo.
15048 if (first.analysisSupport) {
15049 SendToProgram("exit\nforce\n", &first);
15050 first.analyzing = FALSE;
15054 if (gameMode == IcsExamining && !pausing) {
15055 SendToICS(ics_prefix);
15056 SendToICS("backward 999999\n");
15058 BackwardInner(backwardMostMove);
15061 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15062 /* we have fed all the moves, so reactivate analysis mode */
15063 SendToProgram("analyze\n", &first);
15064 first.analyzing = TRUE;
15065 /*first.maybeThinking = TRUE;*/
15066 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15073 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
15074 if (to >= forwardMostMove) to = forwardMostMove;
15075 if (to <= backwardMostMove) to = backwardMostMove;
15076 if (to < currentMove) {
15084 RevertEvent (Boolean annotate)
15086 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
15089 if (gameMode != IcsExamining) {
15090 DisplayError(_("You are not examining a game"), 0);
15094 DisplayError(_("You can't revert while pausing"), 0);
15097 SendToICS(ics_prefix);
15098 SendToICS("revert\n");
15102 RetractMoveEvent ()
15104 switch (gameMode) {
15105 case MachinePlaysWhite:
15106 case MachinePlaysBlack:
15107 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15108 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
15111 if (forwardMostMove < 2) return;
15112 currentMove = forwardMostMove = forwardMostMove - 2;
15113 whiteTimeRemaining = timeRemaining[0][currentMove];
15114 blackTimeRemaining = timeRemaining[1][currentMove];
15115 DisplayBothClocks();
15116 DisplayMove(currentMove - 1);
15117 ClearHighlights();/*!! could figure this out*/
15118 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
15119 SendToProgram("remove\n", &first);
15120 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
15123 case BeginningOfGame:
15127 case IcsPlayingWhite:
15128 case IcsPlayingBlack:
15129 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
15130 SendToICS(ics_prefix);
15131 SendToICS("takeback 2\n");
15133 SendToICS(ics_prefix);
15134 SendToICS("takeback 1\n");
15143 ChessProgramState *cps;
15145 switch (gameMode) {
15146 case MachinePlaysWhite:
15147 if (!WhiteOnMove(forwardMostMove)) {
15148 DisplayError(_("It is your turn"), 0);
15153 case MachinePlaysBlack:
15154 if (WhiteOnMove(forwardMostMove)) {
15155 DisplayError(_("It is your turn"), 0);
15160 case TwoMachinesPlay:
15161 if (WhiteOnMove(forwardMostMove) ==
15162 (first.twoMachinesColor[0] == 'w')) {
15168 case BeginningOfGame:
15172 SendToProgram("?\n", cps);
15176 TruncateGameEvent ()
15179 if (gameMode != EditGame) return;
15186 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
15187 if (forwardMostMove > currentMove) {
15188 if (gameInfo.resultDetails != NULL) {
15189 free(gameInfo.resultDetails);
15190 gameInfo.resultDetails = NULL;
15191 gameInfo.result = GameUnfinished;
15193 forwardMostMove = currentMove;
15194 HistorySet(parseList, backwardMostMove, forwardMostMove,
15202 if (appData.noChessProgram) return;
15203 switch (gameMode) {
15204 case MachinePlaysWhite:
15205 if (WhiteOnMove(forwardMostMove)) {
15206 DisplayError(_("Wait until your turn"), 0);
15210 case BeginningOfGame:
15211 case MachinePlaysBlack:
15212 if (!WhiteOnMove(forwardMostMove)) {
15213 DisplayError(_("Wait until your turn"), 0);
15218 DisplayError(_("No hint available"), 0);
15221 SendToProgram("hint\n", &first);
15222 hintRequested = TRUE;
15228 ListGame * lg = (ListGame *) gameList.head;
15231 static int secondTime = FALSE;
15233 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15234 DisplayError(_("Game list not loaded or empty"), 0);
15238 if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
15241 DisplayNote(_("Book file exists! Try again for overwrite."));
15245 creatingBook = TRUE;
15246 secondTime = FALSE;
15248 /* Get list size */
15249 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
15250 LoadGame(f, nItem, "", TRUE);
15251 AddGameToBook(TRUE);
15252 lg = (ListGame *) lg->node.succ;
15255 creatingBook = FALSE;
15262 if (appData.noChessProgram) return;
15263 switch (gameMode) {
15264 case MachinePlaysWhite:
15265 if (WhiteOnMove(forwardMostMove)) {
15266 DisplayError(_("Wait until your turn"), 0);
15270 case BeginningOfGame:
15271 case MachinePlaysBlack:
15272 if (!WhiteOnMove(forwardMostMove)) {
15273 DisplayError(_("Wait until your turn"), 0);
15278 EditPositionDone(TRUE);
15280 case TwoMachinesPlay:
15285 SendToProgram("bk\n", &first);
15286 bookOutput[0] = NULLCHAR;
15287 bookRequested = TRUE;
15293 char *tags = PGNTags(&gameInfo);
15294 TagsPopUp(tags, CmailMsg());
15298 /* end button procedures */
15301 PrintPosition (FILE *fp, int move)
15305 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15306 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15307 char c = PieceToChar(boards[move][i][j]);
15308 fputc(c == 'x' ? '.' : c, fp);
15309 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
15312 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
15313 fprintf(fp, "white to play\n");
15315 fprintf(fp, "black to play\n");
15319 PrintOpponents (FILE *fp)
15321 if (gameInfo.white != NULL) {
15322 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
15328 /* Find last component of program's own name, using some heuristics */
15330 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
15333 int local = (strcmp(host, "localhost") == 0);
15334 while (!local && (p = strchr(prog, ';')) != NULL) {
15336 while (*p == ' ') p++;
15339 if (*prog == '"' || *prog == '\'') {
15340 q = strchr(prog + 1, *prog);
15342 q = strchr(prog, ' ');
15344 if (q == NULL) q = prog + strlen(prog);
15346 while (p >= prog && *p != '/' && *p != '\\') p--;
15348 if(p == prog && *p == '"') p++;
15350 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
15351 memcpy(buf, p, q - p);
15352 buf[q - p] = NULLCHAR;
15360 TimeControlTagValue ()
15363 if (!appData.clockMode) {
15364 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
15365 } else if (movesPerSession > 0) {
15366 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
15367 } else if (timeIncrement == 0) {
15368 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
15370 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
15372 return StrSave(buf);
15378 /* This routine is used only for certain modes */
15379 VariantClass v = gameInfo.variant;
15380 ChessMove r = GameUnfinished;
15383 if(keepInfo) return;
15385 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
15386 r = gameInfo.result;
15387 p = gameInfo.resultDetails;
15388 gameInfo.resultDetails = NULL;
15390 ClearGameInfo(&gameInfo);
15391 gameInfo.variant = v;
15393 switch (gameMode) {
15394 case MachinePlaysWhite:
15395 gameInfo.event = StrSave( appData.pgnEventHeader );
15396 gameInfo.site = StrSave(HostName());
15397 gameInfo.date = PGNDate();
15398 gameInfo.round = StrSave("-");
15399 gameInfo.white = StrSave(first.tidy);
15400 gameInfo.black = StrSave(UserName());
15401 gameInfo.timeControl = TimeControlTagValue();
15404 case MachinePlaysBlack:
15405 gameInfo.event = StrSave( appData.pgnEventHeader );
15406 gameInfo.site = StrSave(HostName());
15407 gameInfo.date = PGNDate();
15408 gameInfo.round = StrSave("-");
15409 gameInfo.white = StrSave(UserName());
15410 gameInfo.black = StrSave(first.tidy);
15411 gameInfo.timeControl = TimeControlTagValue();
15414 case TwoMachinesPlay:
15415 gameInfo.event = StrSave( appData.pgnEventHeader );
15416 gameInfo.site = StrSave(HostName());
15417 gameInfo.date = PGNDate();
15420 snprintf(buf, MSG_SIZ, "%d", roundNr);
15421 gameInfo.round = StrSave(buf);
15423 gameInfo.round = StrSave("-");
15425 if (first.twoMachinesColor[0] == 'w') {
15426 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15427 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15429 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15430 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15432 gameInfo.timeControl = TimeControlTagValue();
15436 gameInfo.event = StrSave("Edited game");
15437 gameInfo.site = StrSave(HostName());
15438 gameInfo.date = PGNDate();
15439 gameInfo.round = StrSave("-");
15440 gameInfo.white = StrSave("-");
15441 gameInfo.black = StrSave("-");
15442 gameInfo.result = r;
15443 gameInfo.resultDetails = p;
15447 gameInfo.event = StrSave("Edited position");
15448 gameInfo.site = StrSave(HostName());
15449 gameInfo.date = PGNDate();
15450 gameInfo.round = StrSave("-");
15451 gameInfo.white = StrSave("-");
15452 gameInfo.black = StrSave("-");
15455 case IcsPlayingWhite:
15456 case IcsPlayingBlack:
15461 case PlayFromGameFile:
15462 gameInfo.event = StrSave("Game from non-PGN file");
15463 gameInfo.site = StrSave(HostName());
15464 gameInfo.date = PGNDate();
15465 gameInfo.round = StrSave("-");
15466 gameInfo.white = StrSave("?");
15467 gameInfo.black = StrSave("?");
15476 ReplaceComment (int index, char *text)
15482 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
15483 pvInfoList[index-1].depth == len &&
15484 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
15485 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
15486 while (*text == '\n') text++;
15487 len = strlen(text);
15488 while (len > 0 && text[len - 1] == '\n') len--;
15490 if (commentList[index] != NULL)
15491 free(commentList[index]);
15494 commentList[index] = NULL;
15497 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
15498 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
15499 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
15500 commentList[index] = (char *) malloc(len + 2);
15501 strncpy(commentList[index], text, len);
15502 commentList[index][len] = '\n';
15503 commentList[index][len + 1] = NULLCHAR;
15505 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
15507 commentList[index] = (char *) malloc(len + 7);
15508 safeStrCpy(commentList[index], "{\n", 3);
15509 safeStrCpy(commentList[index]+2, text, len+1);
15510 commentList[index][len+2] = NULLCHAR;
15511 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
15512 strcat(commentList[index], "\n}\n");
15517 CrushCRs (char *text)
15525 if (ch == '\r') continue;
15527 } while (ch != '\0');
15531 AppendComment (int index, char *text, Boolean addBraces)
15532 /* addBraces tells if we should add {} */
15537 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
15538 if(addBraces == 3) addBraces = 0; else // force appending literally
15539 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
15542 while (*text == '\n') text++;
15543 len = strlen(text);
15544 while (len > 0 && text[len - 1] == '\n') len--;
15545 text[len] = NULLCHAR;
15547 if (len == 0) return;
15549 if (commentList[index] != NULL) {
15550 Boolean addClosingBrace = addBraces;
15551 old = commentList[index];
15552 oldlen = strlen(old);
15553 while(commentList[index][oldlen-1] == '\n')
15554 commentList[index][--oldlen] = NULLCHAR;
15555 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
15556 safeStrCpy(commentList[index], old, oldlen + len + 6);
15558 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
15559 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
15560 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
15561 while (*text == '\n') { text++; len--; }
15562 commentList[index][--oldlen] = NULLCHAR;
15564 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
15565 else strcat(commentList[index], "\n");
15566 strcat(commentList[index], text);
15567 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
15568 else strcat(commentList[index], "\n");
15570 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
15572 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
15573 else commentList[index][0] = NULLCHAR;
15574 strcat(commentList[index], text);
15575 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
15576 if(addBraces == TRUE) strcat(commentList[index], "}\n");
15581 FindStr (char * text, char * sub_text)
15583 char * result = strstr( text, sub_text );
15585 if( result != NULL ) {
15586 result += strlen( sub_text );
15592 /* [AS] Try to extract PV info from PGN comment */
15593 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
15595 GetInfoFromComment (int index, char * text)
15597 char * sep = text, *p;
15599 if( text != NULL && index > 0 ) {
15602 int time = -1, sec = 0, deci;
15603 char * s_eval = FindStr( text, "[%eval " );
15604 char * s_emt = FindStr( text, "[%emt " );
15606 if( s_eval != NULL || s_emt != NULL ) {
15608 if(0) { // [HGM] this code is not finished, and could actually be detrimental
15613 if( s_eval != NULL ) {
15614 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
15618 if( delim != ']' ) {
15623 if( s_emt != NULL ) {
15628 /* We expect something like: [+|-]nnn.nn/dd */
15631 if(*text != '{') return text; // [HGM] braces: must be normal comment
15633 sep = strchr( text, '/' );
15634 if( sep == NULL || sep < (text+4) ) {
15639 if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
15640 if(p[1] == '(') { // comment starts with PV
15641 p = strchr(p, ')'); // locate end of PV
15642 if(p == NULL || sep < p+5) return text;
15643 // at this point we have something like "{(.*) +0.23/6 ..."
15644 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
15645 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
15646 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
15648 time = -1; sec = -1; deci = -1;
15649 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
15650 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
15651 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
15652 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
15656 if( score_lo < 0 || score_lo >= 100 ) {
15660 if(sec >= 0) time = 600*time + 10*sec; else
15661 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
15663 score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
15665 /* [HGM] PV time: now locate end of PV info */
15666 while( *++sep >= '0' && *sep <= '9'); // strip depth
15668 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
15670 while( *++sep >= '0' && *sep <= '9'); // strip seconds
15672 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
15673 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
15684 pvInfoList[index-1].depth = depth;
15685 pvInfoList[index-1].score = score;
15686 pvInfoList[index-1].time = 10*time; // centi-sec
15687 if(*sep == '}') *sep = 0; else *--sep = '{';
15688 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
15694 SendToProgram (char *message, ChessProgramState *cps)
15696 int count, outCount, error;
15699 if (cps->pr == NoProc) return;
15702 if (appData.debugMode) {
15705 fprintf(debugFP, "%ld >%-6s: %s",
15706 SubtractTimeMarks(&now, &programStartTime),
15707 cps->which, message);
15709 fprintf(serverFP, "%ld >%-6s: %s",
15710 SubtractTimeMarks(&now, &programStartTime),
15711 cps->which, message), fflush(serverFP);
15714 count = strlen(message);
15715 outCount = OutputToProcess(cps->pr, message, count, &error);
15716 if (outCount < count && !exiting
15717 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
15718 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
15719 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
15720 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15721 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15722 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15723 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15724 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15726 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15727 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15728 gameInfo.result = res;
15730 gameInfo.resultDetails = StrSave(buf);
15732 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15733 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15738 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
15742 ChessProgramState *cps = (ChessProgramState *)closure;
15744 if (isr != cps->isr) return; /* Killed intentionally */
15747 RemoveInputSource(cps->isr);
15748 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
15749 _(cps->which), cps->program);
15750 if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
15751 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15752 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15753 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15754 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15755 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15757 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15758 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15759 gameInfo.result = res;
15761 gameInfo.resultDetails = StrSave(buf);
15763 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15764 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
15766 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
15767 _(cps->which), cps->program);
15768 RemoveInputSource(cps->isr);
15770 /* [AS] Program is misbehaving badly... kill it */
15771 if( count == -2 ) {
15772 DestroyChildProcess( cps->pr, 9 );
15776 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15781 if ((end_str = strchr(message, '\r')) != NULL)
15782 *end_str = NULLCHAR;
15783 if ((end_str = strchr(message, '\n')) != NULL)
15784 *end_str = NULLCHAR;
15786 if (appData.debugMode) {
15787 TimeMark now; int print = 1;
15788 char *quote = ""; char c; int i;
15790 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
15791 char start = message[0];
15792 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
15793 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
15794 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
15795 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
15796 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
15797 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
15798 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
15799 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
15800 sscanf(message, "hint: %c", &c)!=1 &&
15801 sscanf(message, "pong %c", &c)!=1 && start != '#') {
15802 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
15803 print = (appData.engineComments >= 2);
15805 message[0] = start; // restore original message
15809 fprintf(debugFP, "%ld <%-6s: %s%s\n",
15810 SubtractTimeMarks(&now, &programStartTime), cps->which,
15814 fprintf(serverFP, "%ld <%-6s: %s%s\n",
15815 SubtractTimeMarks(&now, &programStartTime), cps->which,
15817 message), fflush(serverFP);
15821 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
15822 if (appData.icsEngineAnalyze) {
15823 if (strstr(message, "whisper") != NULL ||
15824 strstr(message, "kibitz") != NULL ||
15825 strstr(message, "tellics") != NULL) return;
15828 HandleMachineMove(message, cps);
15833 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
15838 if( timeControl_2 > 0 ) {
15839 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
15840 tc = timeControl_2;
15843 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
15844 inc /= cps->timeOdds;
15845 st /= cps->timeOdds;
15847 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
15850 /* Set exact time per move, normally using st command */
15851 if (cps->stKludge) {
15852 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
15854 if (seconds == 0) {
15855 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
15857 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
15860 snprintf(buf, MSG_SIZ, "st %d\n", st);
15863 /* Set conventional or incremental time control, using level command */
15864 if (seconds == 0) {
15865 /* Note old gnuchess bug -- minutes:seconds used to not work.
15866 Fixed in later versions, but still avoid :seconds
15867 when seconds is 0. */
15868 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
15870 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
15871 seconds, inc/1000.);
15874 SendToProgram(buf, cps);
15876 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
15877 /* Orthogonally, limit search to given depth */
15879 if (cps->sdKludge) {
15880 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
15882 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
15884 SendToProgram(buf, cps);
15887 if(cps->nps >= 0) { /* [HGM] nps */
15888 if(cps->supportsNPS == FALSE)
15889 cps->nps = -1; // don't use if engine explicitly says not supported!
15891 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
15892 SendToProgram(buf, cps);
15897 ChessProgramState *
15899 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
15901 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
15902 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
15908 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
15910 char message[MSG_SIZ];
15913 /* Note: this routine must be called when the clocks are stopped
15914 or when they have *just* been set or switched; otherwise
15915 it will be off by the time since the current tick started.
15917 if (machineWhite) {
15918 time = whiteTimeRemaining / 10;
15919 otime = blackTimeRemaining / 10;
15921 time = blackTimeRemaining / 10;
15922 otime = whiteTimeRemaining / 10;
15924 /* [HGM] translate opponent's time by time-odds factor */
15925 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
15927 if (time <= 0) time = 1;
15928 if (otime <= 0) otime = 1;
15930 snprintf(message, MSG_SIZ, "time %ld\n", time);
15931 SendToProgram(message, cps);
15933 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
15934 SendToProgram(message, cps);
15938 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15941 int len = strlen(name);
15944 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15946 sscanf(*p, "%d", &val);
15948 while (**p && **p != ' ')
15950 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15951 SendToProgram(buf, cps);
15958 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15961 int len = strlen(name);
15962 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15964 sscanf(*p, "%d", loc);
15965 while (**p && **p != ' ') (*p)++;
15966 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15967 SendToProgram(buf, cps);
15974 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
15977 int len = strlen(name);
15978 if (strncmp((*p), name, len) == 0
15979 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
15981 ASSIGN(*loc, *p); // kludge alert: assign rest of line just to be sure allocation is large enough so that sscanf below always fits
15982 sscanf(*p, "%[^\"]", *loc);
15983 while (**p && **p != '\"') (*p)++;
15984 if (**p == '\"') (*p)++;
15985 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15986 SendToProgram(buf, cps);
15993 ParseOption (Option *opt, ChessProgramState *cps)
15994 // [HGM] options: process the string that defines an engine option, and determine
15995 // name, type, default value, and allowed value range
15997 char *p, *q, buf[MSG_SIZ];
15998 int n, min = (-1)<<31, max = 1<<31, def;
16000 if(p = strstr(opt->name, " -spin ")) {
16001 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16002 if(max < min) max = min; // enforce consistency
16003 if(def < min) def = min;
16004 if(def > max) def = max;
16009 } else if((p = strstr(opt->name, " -slider "))) {
16010 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
16011 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16012 if(max < min) max = min; // enforce consistency
16013 if(def < min) def = min;
16014 if(def > max) def = max;
16018 opt->type = Spin; // Slider;
16019 } else if((p = strstr(opt->name, " -string "))) {
16020 opt->textValue = p+9;
16021 opt->type = TextBox;
16022 } else if((p = strstr(opt->name, " -file "))) {
16023 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16024 opt->textValue = p+7;
16025 opt->type = FileName; // FileName;
16026 } else if((p = strstr(opt->name, " -path "))) {
16027 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16028 opt->textValue = p+7;
16029 opt->type = PathName; // PathName;
16030 } else if(p = strstr(opt->name, " -check ")) {
16031 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
16032 opt->value = (def != 0);
16033 opt->type = CheckBox;
16034 } else if(p = strstr(opt->name, " -combo ")) {
16035 opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
16036 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
16037 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
16038 opt->value = n = 0;
16039 while(q = StrStr(q, " /// ")) {
16040 n++; *q = 0; // count choices, and null-terminate each of them
16042 if(*q == '*') { // remember default, which is marked with * prefix
16046 cps->comboList[cps->comboCnt++] = q;
16048 cps->comboList[cps->comboCnt++] = NULL;
16050 opt->type = ComboBox;
16051 } else if(p = strstr(opt->name, " -button")) {
16052 opt->type = Button;
16053 } else if(p = strstr(opt->name, " -save")) {
16054 opt->type = SaveButton;
16055 } else return FALSE;
16056 *p = 0; // terminate option name
16057 // now look if the command-line options define a setting for this engine option.
16058 if(cps->optionSettings && cps->optionSettings[0])
16059 p = strstr(cps->optionSettings, opt->name); else p = NULL;
16060 if(p && (p == cps->optionSettings || p[-1] == ',')) {
16061 snprintf(buf, MSG_SIZ, "option %s", p);
16062 if(p = strstr(buf, ",")) *p = 0;
16063 if(q = strchr(buf, '=')) switch(opt->type) {
16065 for(n=0; n<opt->max; n++)
16066 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
16069 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
16073 opt->value = atoi(q+1);
16078 SendToProgram(buf, cps);
16084 FeatureDone (ChessProgramState *cps, int val)
16086 DelayedEventCallback cb = GetDelayedEvent();
16087 if ((cb == InitBackEnd3 && cps == &first) ||
16088 (cb == SettingsMenuIfReady && cps == &second) ||
16089 (cb == LoadEngine) ||
16090 (cb == TwoMachinesEventIfReady)) {
16091 CancelDelayedEvent();
16092 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
16094 cps->initDone = val;
16095 if(val) cps->reload = FALSE;
16098 /* Parse feature command from engine */
16100 ParseFeatures (char *args, ChessProgramState *cps)
16108 while (*p == ' ') p++;
16109 if (*p == NULLCHAR) return;
16111 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
16112 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
16113 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
16114 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
16115 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
16116 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
16117 if (BoolFeature(&p, "reuse", &val, cps)) {
16118 /* Engine can disable reuse, but can't enable it if user said no */
16119 if (!val) cps->reuse = FALSE;
16122 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
16123 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
16124 if (gameMode == TwoMachinesPlay) {
16125 DisplayTwoMachinesTitle();
16131 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
16132 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
16133 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
16134 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
16135 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
16136 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
16137 if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
16138 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
16139 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
16140 if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
16141 if (IntFeature(&p, "done", &val, cps)) {
16142 FeatureDone(cps, val);
16145 /* Added by Tord: */
16146 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
16147 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
16148 /* End of additions by Tord */
16150 /* [HGM] added features: */
16151 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
16152 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
16153 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
16154 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
16155 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
16156 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
16157 if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
16158 if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
16159 FREE(cps->option[cps->nrOptions].name);
16160 cps->option[cps->nrOptions].name = q; q = NULL;
16161 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
16162 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
16163 SendToProgram(buf, cps);
16166 if(cps->nrOptions >= MAX_OPTIONS) {
16168 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
16169 DisplayError(buf, 0);
16173 /* End of additions by HGM */
16175 /* unknown feature: complain and skip */
16177 while (*q && *q != '=') q++;
16178 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
16179 SendToProgram(buf, cps);
16185 while (*p && *p != '\"') p++;
16186 if (*p == '\"') p++;
16188 while (*p && *p != ' ') p++;
16196 PeriodicUpdatesEvent (int newState)
16198 if (newState == appData.periodicUpdates)
16201 appData.periodicUpdates=newState;
16203 /* Display type changes, so update it now */
16204 // DisplayAnalysis();
16206 /* Get the ball rolling again... */
16208 AnalysisPeriodicEvent(1);
16209 StartAnalysisClock();
16214 PonderNextMoveEvent (int newState)
16216 if (newState == appData.ponderNextMove) return;
16217 if (gameMode == EditPosition) EditPositionDone(TRUE);
16219 SendToProgram("hard\n", &first);
16220 if (gameMode == TwoMachinesPlay) {
16221 SendToProgram("hard\n", &second);
16224 SendToProgram("easy\n", &first);
16225 thinkOutput[0] = NULLCHAR;
16226 if (gameMode == TwoMachinesPlay) {
16227 SendToProgram("easy\n", &second);
16230 appData.ponderNextMove = newState;
16234 NewSettingEvent (int option, int *feature, char *command, int value)
16238 if (gameMode == EditPosition) EditPositionDone(TRUE);
16239 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
16240 if(feature == NULL || *feature) SendToProgram(buf, &first);
16241 if (gameMode == TwoMachinesPlay) {
16242 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
16247 ShowThinkingEvent ()
16248 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
16250 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
16251 int newState = appData.showThinking
16252 // [HGM] thinking: other features now need thinking output as well
16253 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
16255 if (oldState == newState) return;
16256 oldState = newState;
16257 if (gameMode == EditPosition) EditPositionDone(TRUE);
16259 SendToProgram("post\n", &first);
16260 if (gameMode == TwoMachinesPlay) {
16261 SendToProgram("post\n", &second);
16264 SendToProgram("nopost\n", &first);
16265 thinkOutput[0] = NULLCHAR;
16266 if (gameMode == TwoMachinesPlay) {
16267 SendToProgram("nopost\n", &second);
16270 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
16274 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
16276 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
16277 if (pr == NoProc) return;
16278 AskQuestion(title, question, replyPrefix, pr);
16282 TypeInEvent (char firstChar)
16284 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
16285 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
16286 gameMode == AnalyzeMode || gameMode == EditGame ||
16287 gameMode == EditPosition || gameMode == IcsExamining ||
16288 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
16289 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
16290 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
16291 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
16292 gameMode == Training) PopUpMoveDialog(firstChar);
16296 TypeInDoneEvent (char *move)
16299 int n, fromX, fromY, toX, toY;
16301 ChessMove moveType;
16304 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
16305 EditPositionPasteFEN(move);
16308 // [HGM] movenum: allow move number to be typed in any mode
16309 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
16313 // undocumented kludge: allow command-line option to be typed in!
16314 // (potentially fatal, and does not implement the effect of the option.)
16315 // should only be used for options that are values on which future decisions will be made,
16316 // and definitely not on options that would be used during initialization.
16317 if(strstr(move, "!!! -") == move) {
16318 ParseArgsFromString(move+4);
16322 if (gameMode != EditGame && currentMove != forwardMostMove &&
16323 gameMode != Training) {
16324 DisplayMoveError(_("Displayed move is not current"));
16326 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16327 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
16328 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
16329 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16330 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
16331 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
16333 DisplayMoveError(_("Could not parse move"));
16339 DisplayMove (int moveNumber)
16341 char message[MSG_SIZ];
16343 char cpThinkOutput[MSG_SIZ];
16345 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
16347 if (moveNumber == forwardMostMove - 1 ||
16348 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16350 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
16352 if (strchr(cpThinkOutput, '\n')) {
16353 *strchr(cpThinkOutput, '\n') = NULLCHAR;
16356 *cpThinkOutput = NULLCHAR;
16359 /* [AS] Hide thinking from human user */
16360 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
16361 *cpThinkOutput = NULLCHAR;
16362 if( thinkOutput[0] != NULLCHAR ) {
16365 for( i=0; i<=hiddenThinkOutputState; i++ ) {
16366 cpThinkOutput[i] = '.';
16368 cpThinkOutput[i] = NULLCHAR;
16369 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
16373 if (moveNumber == forwardMostMove - 1 &&
16374 gameInfo.resultDetails != NULL) {
16375 if (gameInfo.resultDetails[0] == NULLCHAR) {
16376 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
16378 snprintf(res, MSG_SIZ, " {%s} %s",
16379 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
16385 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16386 DisplayMessage(res, cpThinkOutput);
16388 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
16389 WhiteOnMove(moveNumber) ? " " : ".. ",
16390 parseList[moveNumber], res);
16391 DisplayMessage(message, cpThinkOutput);
16396 DisplayComment (int moveNumber, char *text)
16398 char title[MSG_SIZ];
16400 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16401 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
16403 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
16404 WhiteOnMove(moveNumber) ? " " : ".. ",
16405 parseList[moveNumber]);
16407 if (text != NULL && (appData.autoDisplayComment || commentUp))
16408 CommentPopUp(title, text);
16411 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
16412 * might be busy thinking or pondering. It can be omitted if your
16413 * gnuchess is configured to stop thinking immediately on any user
16414 * input. However, that gnuchess feature depends on the FIONREAD
16415 * ioctl, which does not work properly on some flavors of Unix.
16418 Attention (ChessProgramState *cps)
16421 if (!cps->useSigint) return;
16422 if (appData.noChessProgram || (cps->pr == NoProc)) return;
16423 switch (gameMode) {
16424 case MachinePlaysWhite:
16425 case MachinePlaysBlack:
16426 case TwoMachinesPlay:
16427 case IcsPlayingWhite:
16428 case IcsPlayingBlack:
16431 /* Skip if we know it isn't thinking */
16432 if (!cps->maybeThinking) return;
16433 if (appData.debugMode)
16434 fprintf(debugFP, "Interrupting %s\n", cps->which);
16435 InterruptChildProcess(cps->pr);
16436 cps->maybeThinking = FALSE;
16441 #endif /*ATTENTION*/
16447 if (whiteTimeRemaining <= 0) {
16450 if (appData.icsActive) {
16451 if (appData.autoCallFlag &&
16452 gameMode == IcsPlayingBlack && !blackFlag) {
16453 SendToICS(ics_prefix);
16454 SendToICS("flag\n");
16458 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16460 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
16461 if (appData.autoCallFlag) {
16462 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
16469 if (blackTimeRemaining <= 0) {
16472 if (appData.icsActive) {
16473 if (appData.autoCallFlag &&
16474 gameMode == IcsPlayingWhite && !whiteFlag) {
16475 SendToICS(ics_prefix);
16476 SendToICS("flag\n");
16480 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16482 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
16483 if (appData.autoCallFlag) {
16484 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
16495 CheckTimeControl ()
16497 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
16498 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
16501 * add time to clocks when time control is achieved ([HGM] now also used for increment)
16503 if ( !WhiteOnMove(forwardMostMove) ) {
16504 /* White made time control */
16505 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
16506 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
16507 /* [HGM] time odds: correct new time quota for time odds! */
16508 / WhitePlayer()->timeOdds;
16509 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
16511 lastBlack -= blackTimeRemaining;
16512 /* Black made time control */
16513 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
16514 / WhitePlayer()->other->timeOdds;
16515 lastWhite = whiteTimeRemaining;
16520 DisplayBothClocks ()
16522 int wom = gameMode == EditPosition ?
16523 !blackPlaysFirst : WhiteOnMove(currentMove);
16524 DisplayWhiteClock(whiteTimeRemaining, wom);
16525 DisplayBlackClock(blackTimeRemaining, !wom);
16529 /* Timekeeping seems to be a portability nightmare. I think everyone
16530 has ftime(), but I'm really not sure, so I'm including some ifdefs
16531 to use other calls if you don't. Clocks will be less accurate if
16532 you have neither ftime nor gettimeofday.
16535 /* VS 2008 requires the #include outside of the function */
16536 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
16537 #include <sys/timeb.h>
16540 /* Get the current time as a TimeMark */
16542 GetTimeMark (TimeMark *tm)
16544 #if HAVE_GETTIMEOFDAY
16546 struct timeval timeVal;
16547 struct timezone timeZone;
16549 gettimeofday(&timeVal, &timeZone);
16550 tm->sec = (long) timeVal.tv_sec;
16551 tm->ms = (int) (timeVal.tv_usec / 1000L);
16553 #else /*!HAVE_GETTIMEOFDAY*/
16556 // include <sys/timeb.h> / moved to just above start of function
16557 struct timeb timeB;
16560 tm->sec = (long) timeB.time;
16561 tm->ms = (int) timeB.millitm;
16563 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
16564 tm->sec = (long) time(NULL);
16570 /* Return the difference in milliseconds between two
16571 time marks. We assume the difference will fit in a long!
16574 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
16576 return 1000L*(tm2->sec - tm1->sec) +
16577 (long) (tm2->ms - tm1->ms);
16582 * Code to manage the game clocks.
16584 * In tournament play, black starts the clock and then white makes a move.
16585 * We give the human user a slight advantage if he is playing white---the
16586 * clocks don't run until he makes his first move, so it takes zero time.
16587 * Also, we don't account for network lag, so we could get out of sync
16588 * with GNU Chess's clock -- but then, referees are always right.
16591 static TimeMark tickStartTM;
16592 static long intendedTickLength;
16595 NextTickLength (long timeRemaining)
16597 long nominalTickLength, nextTickLength;
16599 if (timeRemaining > 0L && timeRemaining <= 10000L)
16600 nominalTickLength = 100L;
16602 nominalTickLength = 1000L;
16603 nextTickLength = timeRemaining % nominalTickLength;
16604 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
16606 return nextTickLength;
16609 /* Adjust clock one minute up or down */
16611 AdjustClock (Boolean which, int dir)
16613 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
16614 if(which) blackTimeRemaining += 60000*dir;
16615 else whiteTimeRemaining += 60000*dir;
16616 DisplayBothClocks();
16617 adjustedClock = TRUE;
16620 /* Stop clocks and reset to a fresh time control */
16624 (void) StopClockTimer();
16625 if (appData.icsActive) {
16626 whiteTimeRemaining = blackTimeRemaining = 0;
16627 } else if (searchTime) {
16628 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16629 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16630 } else { /* [HGM] correct new time quote for time odds */
16631 whiteTC = blackTC = fullTimeControlString;
16632 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
16633 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
16635 if (whiteFlag || blackFlag) {
16637 whiteFlag = blackFlag = FALSE;
16639 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
16640 DisplayBothClocks();
16641 adjustedClock = FALSE;
16644 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
16646 /* Decrement running clock by amount of time that has passed */
16650 long timeRemaining;
16651 long lastTickLength, fudge;
16654 if (!appData.clockMode) return;
16655 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
16659 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16661 /* Fudge if we woke up a little too soon */
16662 fudge = intendedTickLength - lastTickLength;
16663 if (fudge < 0 || fudge > FUDGE) fudge = 0;
16665 if (WhiteOnMove(forwardMostMove)) {
16666 if(whiteNPS >= 0) lastTickLength = 0;
16667 timeRemaining = whiteTimeRemaining -= lastTickLength;
16668 if(timeRemaining < 0 && !appData.icsActive) {
16669 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
16670 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
16671 whiteStartMove = forwardMostMove; whiteTC = nextSession;
16672 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
16675 DisplayWhiteClock(whiteTimeRemaining - fudge,
16676 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16678 if(blackNPS >= 0) lastTickLength = 0;
16679 timeRemaining = blackTimeRemaining -= lastTickLength;
16680 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
16681 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
16683 blackStartMove = forwardMostMove;
16684 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
16687 DisplayBlackClock(blackTimeRemaining - fudge,
16688 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16690 if (CheckFlags()) return;
16692 if(twoBoards) { // count down secondary board's clocks as well
16693 activePartnerTime -= lastTickLength;
16695 if(activePartner == 'W')
16696 DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
16698 DisplayBlackClock(activePartnerTime, TRUE);
16703 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
16704 StartClockTimer(intendedTickLength);
16706 /* if the time remaining has fallen below the alarm threshold, sound the
16707 * alarm. if the alarm has sounded and (due to a takeback or time control
16708 * with increment) the time remaining has increased to a level above the
16709 * threshold, reset the alarm so it can sound again.
16712 if (appData.icsActive && appData.icsAlarm) {
16714 /* make sure we are dealing with the user's clock */
16715 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
16716 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
16719 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
16720 alarmSounded = FALSE;
16721 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
16723 alarmSounded = TRUE;
16729 /* A player has just moved, so stop the previously running
16730 clock and (if in clock mode) start the other one.
16731 We redisplay both clocks in case we're in ICS mode, because
16732 ICS gives us an update to both clocks after every move.
16733 Note that this routine is called *after* forwardMostMove
16734 is updated, so the last fractional tick must be subtracted
16735 from the color that is *not* on move now.
16738 SwitchClocks (int newMoveNr)
16740 long lastTickLength;
16742 int flagged = FALSE;
16746 if (StopClockTimer() && appData.clockMode) {
16747 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16748 if (!WhiteOnMove(forwardMostMove)) {
16749 if(blackNPS >= 0) lastTickLength = 0;
16750 blackTimeRemaining -= lastTickLength;
16751 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16752 // if(pvInfoList[forwardMostMove].time == -1)
16753 pvInfoList[forwardMostMove].time = // use GUI time
16754 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
16756 if(whiteNPS >= 0) lastTickLength = 0;
16757 whiteTimeRemaining -= lastTickLength;
16758 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16759 // if(pvInfoList[forwardMostMove].time == -1)
16760 pvInfoList[forwardMostMove].time =
16761 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
16763 flagged = CheckFlags();
16765 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
16766 CheckTimeControl();
16768 if (flagged || !appData.clockMode) return;
16770 switch (gameMode) {
16771 case MachinePlaysBlack:
16772 case MachinePlaysWhite:
16773 case BeginningOfGame:
16774 if (pausing) return;
16778 case PlayFromGameFile:
16786 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
16787 if(WhiteOnMove(forwardMostMove))
16788 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16789 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16793 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16794 whiteTimeRemaining : blackTimeRemaining);
16795 StartClockTimer(intendedTickLength);
16799 /* Stop both clocks */
16803 long lastTickLength;
16806 if (!StopClockTimer()) return;
16807 if (!appData.clockMode) return;
16811 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16812 if (WhiteOnMove(forwardMostMove)) {
16813 if(whiteNPS >= 0) lastTickLength = 0;
16814 whiteTimeRemaining -= lastTickLength;
16815 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
16817 if(blackNPS >= 0) lastTickLength = 0;
16818 blackTimeRemaining -= lastTickLength;
16819 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
16824 /* Start clock of player on move. Time may have been reset, so
16825 if clock is already running, stop and restart it. */
16829 (void) StopClockTimer(); /* in case it was running already */
16830 DisplayBothClocks();
16831 if (CheckFlags()) return;
16833 if (!appData.clockMode) return;
16834 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
16836 GetTimeMark(&tickStartTM);
16837 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16838 whiteTimeRemaining : blackTimeRemaining);
16840 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
16841 whiteNPS = blackNPS = -1;
16842 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
16843 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
16844 whiteNPS = first.nps;
16845 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
16846 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
16847 blackNPS = first.nps;
16848 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
16849 whiteNPS = second.nps;
16850 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
16851 blackNPS = second.nps;
16852 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
16854 StartClockTimer(intendedTickLength);
16858 TimeString (long ms)
16860 long second, minute, hour, day;
16862 static char buf[32];
16864 if (ms > 0 && ms <= 9900) {
16865 /* convert milliseconds to tenths, rounding up */
16866 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
16868 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
16872 /* convert milliseconds to seconds, rounding up */
16873 /* use floating point to avoid strangeness of integer division
16874 with negative dividends on many machines */
16875 second = (long) floor(((double) (ms + 999L)) / 1000.0);
16882 day = second / (60 * 60 * 24);
16883 second = second % (60 * 60 * 24);
16884 hour = second / (60 * 60);
16885 second = second % (60 * 60);
16886 minute = second / 60;
16887 second = second % 60;
16890 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
16891 sign, day, hour, minute, second);
16893 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
16895 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
16902 * This is necessary because some C libraries aren't ANSI C compliant yet.
16905 StrStr (char *string, char *match)
16909 length = strlen(match);
16911 for (i = strlen(string) - length; i >= 0; i--, string++)
16912 if (!strncmp(match, string, length))
16919 StrCaseStr (char *string, char *match)
16923 length = strlen(match);
16925 for (i = strlen(string) - length; i >= 0; i--, string++) {
16926 for (j = 0; j < length; j++) {
16927 if (ToLower(match[j]) != ToLower(string[j]))
16930 if (j == length) return string;
16938 StrCaseCmp (char *s1, char *s2)
16943 c1 = ToLower(*s1++);
16944 c2 = ToLower(*s2++);
16945 if (c1 > c2) return 1;
16946 if (c1 < c2) return -1;
16947 if (c1 == NULLCHAR) return 0;
16955 return isupper(c) ? tolower(c) : c;
16962 return islower(c) ? toupper(c) : c;
16964 #endif /* !_amigados */
16971 if ((ret = (char *) malloc(strlen(s) + 1)))
16973 safeStrCpy(ret, s, strlen(s)+1);
16979 StrSavePtr (char *s, char **savePtr)
16984 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
16985 safeStrCpy(*savePtr, s, strlen(s)+1);
16997 clock = time((time_t *)NULL);
16998 tm = localtime(&clock);
16999 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
17000 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
17001 return StrSave(buf);
17006 PositionToFEN (int move, char *overrideCastling)
17008 int i, j, fromX, fromY, toX, toY;
17015 whiteToPlay = (gameMode == EditPosition) ?
17016 !blackPlaysFirst : (move % 2 == 0);
17019 /* Piece placement data */
17020 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17021 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
17023 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
17024 if (boards[move][i][j] == EmptySquare) {
17026 } else { ChessSquare piece = boards[move][i][j];
17027 if (emptycount > 0) {
17028 if(emptycount<10) /* [HGM] can be >= 10 */
17029 *p++ = '0' + emptycount;
17030 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17033 if(PieceToChar(piece) == '+') {
17034 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
17036 piece = (ChessSquare)(DEMOTED piece);
17038 *p++ = PieceToChar(piece);
17040 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
17041 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
17046 if (emptycount > 0) {
17047 if(emptycount<10) /* [HGM] can be >= 10 */
17048 *p++ = '0' + emptycount;
17049 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17056 /* [HGM] print Crazyhouse or Shogi holdings */
17057 if( gameInfo.holdingsWidth ) {
17058 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
17060 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
17061 piece = boards[move][i][BOARD_WIDTH-1];
17062 if( piece != EmptySquare )
17063 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
17064 *p++ = PieceToChar(piece);
17066 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
17067 piece = boards[move][BOARD_HEIGHT-i-1][0];
17068 if( piece != EmptySquare )
17069 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
17070 *p++ = PieceToChar(piece);
17073 if( q == p ) *p++ = '-';
17079 *p++ = whiteToPlay ? 'w' : 'b';
17082 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
17083 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
17085 if(nrCastlingRights) {
17087 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
17088 /* [HGM] write directly from rights */
17089 if(boards[move][CASTLING][2] != NoRights &&
17090 boards[move][CASTLING][0] != NoRights )
17091 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
17092 if(boards[move][CASTLING][2] != NoRights &&
17093 boards[move][CASTLING][1] != NoRights )
17094 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
17095 if(boards[move][CASTLING][5] != NoRights &&
17096 boards[move][CASTLING][3] != NoRights )
17097 *p++ = boards[move][CASTLING][3] + AAA;
17098 if(boards[move][CASTLING][5] != NoRights &&
17099 boards[move][CASTLING][4] != NoRights )
17100 *p++ = boards[move][CASTLING][4] + AAA;
17103 /* [HGM] write true castling rights */
17104 if( nrCastlingRights == 6 ) {
17106 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
17107 boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
17108 q = (boards[move][CASTLING][1] == BOARD_LEFT &&
17109 boards[move][CASTLING][2] != NoRights );
17110 if(gameInfo.variant == VariantSChess) { // for S-Chess, indicate all vrgin backrank pieces
17111 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_RGHT]; // count white held pieces
17112 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17113 if((boards[move][0][i] != WhiteKing || k+q == 0) &&
17114 boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
17118 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
17119 boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
17120 q = (boards[move][CASTLING][4] == BOARD_LEFT &&
17121 boards[move][CASTLING][5] != NoRights );
17122 if(gameInfo.variant == VariantSChess) {
17123 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_LEFT-1]; // count black held pieces
17124 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
17125 if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
17126 boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
17131 if (q == p) *p++ = '-'; /* No castling rights */
17135 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
17136 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
17137 /* En passant target square */
17138 if (move > backwardMostMove) {
17139 fromX = moveList[move - 1][0] - AAA;
17140 fromY = moveList[move - 1][1] - ONE;
17141 toX = moveList[move - 1][2] - AAA;
17142 toY = moveList[move - 1][3] - ONE;
17143 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
17144 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
17145 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
17147 /* 2-square pawn move just happened */
17149 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17153 } else if(move == backwardMostMove) {
17154 // [HGM] perhaps we should always do it like this, and forget the above?
17155 if((signed char)boards[move][EP_STATUS] >= 0) {
17156 *p++ = boards[move][EP_STATUS] + AAA;
17157 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17168 /* [HGM] find reversible plies */
17169 { int i = 0, j=move;
17171 if (appData.debugMode) { int k;
17172 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
17173 for(k=backwardMostMove; k<=forwardMostMove; k++)
17174 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
17178 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
17179 if( j == backwardMostMove ) i += initialRulePlies;
17180 sprintf(p, "%d ", i);
17181 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
17183 /* Fullmove number */
17184 sprintf(p, "%d", (move / 2) + 1);
17186 return StrSave(buf);
17190 ParseFEN (Board board, int *blackPlaysFirst, char *fen)
17194 int emptycount, virgin[BOARD_FILES];
17199 /* [HGM] by default clear Crazyhouse holdings, if present */
17200 if(gameInfo.holdingsWidth) {
17201 for(i=0; i<BOARD_HEIGHT; i++) {
17202 board[i][0] = EmptySquare; /* black holdings */
17203 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
17204 board[i][1] = (ChessSquare) 0; /* black counts */
17205 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
17209 /* Piece placement data */
17210 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17213 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
17214 if (*p == '/') p++;
17215 emptycount = gameInfo.boardWidth - j;
17216 while (emptycount--)
17217 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17219 #if(BOARD_FILES >= 10)
17220 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
17221 p++; emptycount=10;
17222 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17223 while (emptycount--)
17224 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17226 } else if (isdigit(*p)) {
17227 emptycount = *p++ - '0';
17228 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
17229 if (j + emptycount > gameInfo.boardWidth) return FALSE;
17230 while (emptycount--)
17231 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
17232 } else if (*p == '+' || isalpha(*p)) {
17233 if (j >= gameInfo.boardWidth) return FALSE;
17235 piece = CharToPiece(*++p);
17236 if(piece == EmptySquare) return FALSE; /* unknown piece */
17237 piece = (ChessSquare) (PROMOTED piece ); p++;
17238 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
17239 } else piece = CharToPiece(*p++);
17241 if(piece==EmptySquare) return FALSE; /* unknown piece */
17242 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
17243 piece = (ChessSquare) (PROMOTED piece);
17244 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
17247 board[i][(j++)+gameInfo.holdingsWidth] = piece;
17253 while (*p == '/' || *p == ' ') p++;
17255 /* [HGM] look for Crazyhouse holdings here */
17256 while(*p==' ') p++;
17257 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
17259 if(*p == '-' ) p++; /* empty holdings */ else {
17260 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
17261 /* if we would allow FEN reading to set board size, we would */
17262 /* have to add holdings and shift the board read so far here */
17263 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
17265 if((int) piece >= (int) BlackPawn ) {
17266 i = (int)piece - (int)BlackPawn;
17267 i = PieceToNumber((ChessSquare)i);
17268 if( i >= gameInfo.holdingsSize ) return FALSE;
17269 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
17270 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
17272 i = (int)piece - (int)WhitePawn;
17273 i = PieceToNumber((ChessSquare)i);
17274 if( i >= gameInfo.holdingsSize ) return FALSE;
17275 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
17276 board[i][BOARD_WIDTH-2]++; /* black holdings */
17283 while(*p == ' ') p++;
17287 if(appData.colorNickNames) {
17288 if( c == appData.colorNickNames[0] ) c = 'w'; else
17289 if( c == appData.colorNickNames[1] ) c = 'b';
17293 *blackPlaysFirst = FALSE;
17296 *blackPlaysFirst = TRUE;
17302 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
17303 /* return the extra info in global variiables */
17305 /* set defaults in case FEN is incomplete */
17306 board[EP_STATUS] = EP_UNKNOWN;
17307 for(i=0; i<nrCastlingRights; i++ ) {
17308 board[CASTLING][i] =
17309 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
17310 } /* assume possible unless obviously impossible */
17311 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
17312 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
17313 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
17314 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
17315 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
17316 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
17317 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
17318 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
17321 while(*p==' ') p++;
17322 if(nrCastlingRights) {
17323 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
17324 if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
17325 /* castling indicator present, so default becomes no castlings */
17326 for(i=0; i<nrCastlingRights; i++ ) {
17327 board[CASTLING][i] = NoRights;
17330 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
17331 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess) &&
17332 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
17333 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
17334 int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
17336 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
17337 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
17338 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
17340 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
17341 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
17342 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
17343 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
17344 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
17345 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
17348 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
17349 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
17350 board[CASTLING][2] = whiteKingFile;
17351 if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
17352 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17355 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
17356 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
17357 board[CASTLING][2] = whiteKingFile;
17358 if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
17359 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17362 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
17363 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
17364 board[CASTLING][5] = blackKingFile;
17365 if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
17366 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17369 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
17370 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
17371 board[CASTLING][5] = blackKingFile;
17372 if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
17373 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17376 default: /* FRC castlings */
17377 if(c >= 'a') { /* black rights */
17378 if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
17379 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17380 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
17381 if(i == BOARD_RGHT) break;
17382 board[CASTLING][5] = i;
17384 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
17385 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
17387 board[CASTLING][3] = c;
17389 board[CASTLING][4] = c;
17390 } else { /* white rights */
17391 if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
17392 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17393 if(board[0][i] == WhiteKing) break;
17394 if(i == BOARD_RGHT) break;
17395 board[CASTLING][2] = i;
17396 c -= AAA - 'a' + 'A';
17397 if(board[0][c] >= WhiteKing) break;
17399 board[CASTLING][0] = c;
17401 board[CASTLING][1] = c;
17405 for(i=0; i<nrCastlingRights; i++)
17406 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
17407 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = virgin[i];
17408 if (appData.debugMode) {
17409 fprintf(debugFP, "FEN castling rights:");
17410 for(i=0; i<nrCastlingRights; i++)
17411 fprintf(debugFP, " %d", board[CASTLING][i]);
17412 fprintf(debugFP, "\n");
17415 while(*p==' ') p++;
17418 /* read e.p. field in games that know e.p. capture */
17419 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
17420 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
17422 p++; board[EP_STATUS] = EP_NONE;
17424 char c = *p++ - AAA;
17426 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
17427 if(*p >= '0' && *p <='9') p++;
17428 board[EP_STATUS] = c;
17433 if(sscanf(p, "%d", &i) == 1) {
17434 FENrulePlies = i; /* 50-move ply counter */
17435 /* (The move number is still ignored) */
17442 EditPositionPasteFEN (char *fen)
17445 Board initial_position;
17447 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
17448 DisplayError(_("Bad FEN position in clipboard"), 0);
17451 int savedBlackPlaysFirst = blackPlaysFirst;
17452 EditPositionEvent();
17453 blackPlaysFirst = savedBlackPlaysFirst;
17454 CopyBoard(boards[0], initial_position);
17455 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
17456 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
17457 DisplayBothClocks();
17458 DrawPosition(FALSE, boards[currentMove]);
17463 static char cseq[12] = "\\ ";
17466 set_cont_sequence (char *new_seq)
17471 // handle bad attempts to set the sequence
17473 return 0; // acceptable error - no debug
17475 len = strlen(new_seq);
17476 ret = (len > 0) && (len < sizeof(cseq));
17478 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
17479 else if (appData.debugMode)
17480 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
17485 reformat a source message so words don't cross the width boundary. internal
17486 newlines are not removed. returns the wrapped size (no null character unless
17487 included in source message). If dest is NULL, only calculate the size required
17488 for the dest buffer. lp argument indicats line position upon entry, and it's
17489 passed back upon exit.
17492 wrap (char *dest, char *src, int count, int width, int *lp)
17494 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
17496 cseq_len = strlen(cseq);
17497 old_line = line = *lp;
17498 ansi = len = clen = 0;
17500 for (i=0; i < count; i++)
17502 if (src[i] == '\033')
17505 // if we hit the width, back up
17506 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
17508 // store i & len in case the word is too long
17509 old_i = i, old_len = len;
17511 // find the end of the last word
17512 while (i && src[i] != ' ' && src[i] != '\n')
17518 // word too long? restore i & len before splitting it
17519 if ((old_i-i+clen) >= width)
17526 if (i && src[i-1] == ' ')
17529 if (src[i] != ' ' && src[i] != '\n')
17536 // now append the newline and continuation sequence
17541 strncpy(dest+len, cseq, cseq_len);
17549 dest[len] = src[i];
17553 if (src[i] == '\n')
17558 if (dest && appData.debugMode)
17560 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
17561 count, width, line, len, *lp);
17562 show_bytes(debugFP, src, count);
17563 fprintf(debugFP, "\ndest: ");
17564 show_bytes(debugFP, dest, len);
17565 fprintf(debugFP, "\n");
17567 *lp = dest ? line : old_line;
17572 // [HGM] vari: routines for shelving variations
17573 Boolean modeRestore = FALSE;
17576 PushInner (int firstMove, int lastMove)
17578 int i, j, nrMoves = lastMove - firstMove;
17580 // push current tail of game on stack
17581 savedResult[storedGames] = gameInfo.result;
17582 savedDetails[storedGames] = gameInfo.resultDetails;
17583 gameInfo.resultDetails = NULL;
17584 savedFirst[storedGames] = firstMove;
17585 savedLast [storedGames] = lastMove;
17586 savedFramePtr[storedGames] = framePtr;
17587 framePtr -= nrMoves; // reserve space for the boards
17588 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
17589 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
17590 for(j=0; j<MOVE_LEN; j++)
17591 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
17592 for(j=0; j<2*MOVE_LEN; j++)
17593 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
17594 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
17595 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
17596 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
17597 pvInfoList[firstMove+i-1].depth = 0;
17598 commentList[framePtr+i] = commentList[firstMove+i];
17599 commentList[firstMove+i] = NULL;
17603 forwardMostMove = firstMove; // truncate game so we can start variation
17607 PushTail (int firstMove, int lastMove)
17609 if(appData.icsActive) { // only in local mode
17610 forwardMostMove = currentMove; // mimic old ICS behavior
17613 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
17615 PushInner(firstMove, lastMove);
17616 if(storedGames == 1) GreyRevert(FALSE);
17617 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
17621 PopInner (Boolean annotate)
17624 char buf[8000], moveBuf[20];
17626 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
17627 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
17628 nrMoves = savedLast[storedGames] - currentMove;
17631 if(!WhiteOnMove(currentMove))
17632 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
17633 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
17634 for(i=currentMove; i<forwardMostMove; i++) {
17636 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
17637 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
17638 strcat(buf, moveBuf);
17639 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
17640 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
17644 for(i=1; i<=nrMoves; i++) { // copy last variation back
17645 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
17646 for(j=0; j<MOVE_LEN; j++)
17647 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
17648 for(j=0; j<2*MOVE_LEN; j++)
17649 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
17650 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
17651 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
17652 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
17653 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
17654 commentList[currentMove+i] = commentList[framePtr+i];
17655 commentList[framePtr+i] = NULL;
17657 if(annotate) AppendComment(currentMove+1, buf, FALSE);
17658 framePtr = savedFramePtr[storedGames];
17659 gameInfo.result = savedResult[storedGames];
17660 if(gameInfo.resultDetails != NULL) {
17661 free(gameInfo.resultDetails);
17663 gameInfo.resultDetails = savedDetails[storedGames];
17664 forwardMostMove = currentMove + nrMoves;
17668 PopTail (Boolean annotate)
17670 if(appData.icsActive) return FALSE; // only in local mode
17671 if(!storedGames) return FALSE; // sanity
17672 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
17674 PopInner(annotate);
17675 if(currentMove < forwardMostMove) ForwardEvent(); else
17676 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
17678 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
17684 { // remove all shelved variations
17686 for(i=0; i<storedGames; i++) {
17687 if(savedDetails[i])
17688 free(savedDetails[i]);
17689 savedDetails[i] = NULL;
17691 for(i=framePtr; i<MAX_MOVES; i++) {
17692 if(commentList[i]) free(commentList[i]);
17693 commentList[i] = NULL;
17695 framePtr = MAX_MOVES-1;
17700 LoadVariation (int index, char *text)
17701 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
17702 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
17703 int level = 0, move;
17705 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
17706 // first find outermost bracketing variation
17707 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
17708 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
17709 if(*p == '{') wait = '}'; else
17710 if(*p == '[') wait = ']'; else
17711 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
17712 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
17714 if(*p == wait) wait = NULLCHAR; // closing ]} found
17717 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
17718 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
17719 end[1] = NULLCHAR; // clip off comment beyond variation
17720 ToNrEvent(currentMove-1);
17721 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
17722 // kludge: use ParsePV() to append variation to game
17723 move = currentMove;
17724 ParsePV(start, TRUE, TRUE);
17725 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
17726 ClearPremoveHighlights();
17728 ToNrEvent(currentMove+1);
17734 char *p, *q, buf[MSG_SIZ];
17735 if(engineLine && engineLine[0]) { // a theme was selected from the listbox
17736 snprintf(buf, MSG_SIZ, "-theme %s", engineLine);
17737 ParseArgsFromString(buf);
17738 ActivateTheme(TRUE); // also redo colors
17742 if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
17745 q = appData.themeNames;
17746 snprintf(buf, MSG_SIZ, "\"%s\"", nickName);
17747 if(appData.useBitmaps) {
17748 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt true -lbtf \"%s\" -dbtf \"%s\" -lbtm %d -dbtm %d",
17749 appData.liteBackTextureFile, appData.darkBackTextureFile,
17750 appData.liteBackTextureMode,
17751 appData.darkBackTextureMode );
17753 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt false -lsc %s -dsc %s",
17754 Col2Text(2), // lightSquareColor
17755 Col2Text(3) ); // darkSquareColor
17757 if(appData.useBorder) {
17758 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub true -border \"%s\"",
17761 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub false");
17763 if(appData.useFont) {
17764 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
17765 appData.renderPiecesWithFont,
17766 appData.fontToPieceTable,
17767 Col2Text(9), // appData.fontBackColorWhite
17768 Col2Text(10) ); // appData.fontForeColorBlack
17770 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf false -pid \"%s\"",
17771 appData.pieceDirectory);
17772 if(!appData.pieceDirectory[0])
17773 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -wpc %s -bpc %s",
17774 Col2Text(0), // whitePieceColor
17775 Col2Text(1) ); // blackPieceColor
17777 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -hsc %s -phc %s\n",
17778 Col2Text(4), // highlightSquareColor
17779 Col2Text(5) ); // premoveHighlightColor
17780 appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
17781 if(insert != q) insert[-1] = NULLCHAR;
17782 snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
17785 ActivateTheme(FALSE);