2 * backend.c -- Common back end for X and Windows NT versions of
4 * Copyright 1991 by Digital Equipment Corporation, Maynard,
7 * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8 * 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
10 * Enhancements Copyright 2005 Alessandro Scotti
12 * The following terms apply to Digital Equipment Corporation's copyright
14 * ------------------------------------------------------------------------
17 * Permission to use, copy, modify, and distribute this software and its
18 * documentation for any purpose and without fee is hereby granted,
19 * provided that the above copyright notice appear in all copies and that
20 * both that copyright notice and this permission notice appear in
21 * supporting documentation, and that the name of Digital not be
22 * used in advertising or publicity pertaining to distribution of the
23 * software without specific, written prior permission.
25 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32 * ------------------------------------------------------------------------
34 * The following terms apply to the enhanced version of XBoard
35 * distributed by the Free Software Foundation:
36 * ------------------------------------------------------------------------
38 * GNU XBoard is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or (at
41 * your option) any later version.
43 * GNU XBoard is distributed in the hope that it will be useful, but
44 * WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see http://www.gnu.org/licenses/. *
51 *------------------------------------------------------------------------
52 ** See the file ChangeLog for a revision history. */
54 /* [AS] Also useful here for debugging */
58 int flock(int f, int code);
75 #include <sys/types.h>
84 #else /* not STDC_HEADERS */
87 # else /* not HAVE_STRING_H */
89 # endif /* not HAVE_STRING_H */
90 #endif /* not STDC_HEADERS */
93 # include <sys/fcntl.h>
94 #else /* not HAVE_SYS_FCNTL_H */
97 # endif /* HAVE_FCNTL_H */
98 #endif /* not HAVE_SYS_FCNTL_H */
100 #if TIME_WITH_SYS_TIME
101 # include <sys/time.h>
105 # include <sys/time.h>
111 #if defined(_amigados) && !defined(__GNUC__)
116 extern int gettimeofday(struct timeval *, struct timezone *);
124 #include "frontend.h"
131 #include "backendz.h"
135 # define _(s) gettext (s)
136 # define N_(s) gettext_noop (s)
137 # define T_(s) gettext(s)
150 int establish P((void));
151 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
152 char *buf, int count, int error));
153 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
154 char *buf, int count, int error));
155 void ics_printf P((char *format, ...));
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(());
227 extern void ConsoleCreate();
230 ChessProgramState *WhitePlayer();
231 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
232 int VerifyDisplayMode P(());
234 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
235 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
236 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
237 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
238 void ics_update_width P((int new_width));
239 extern char installDir[MSG_SIZ];
240 VariantClass startVariant; /* [HGM] nicks: initial variant */
243 extern int tinyLayout, smallLayout;
244 ChessProgramStats programStats;
245 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
247 static int exiting = 0; /* [HGM] moved to top */
248 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
249 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
250 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
251 int partnerHighlight[2];
252 Boolean partnerBoardValid = 0;
253 char partnerStatus[MSG_SIZ];
255 Boolean originalFlip;
256 Boolean twoBoards = 0;
257 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
258 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
259 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
260 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
261 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
262 int opponentKibitzes;
263 int lastSavedGame; /* [HGM] save: ID of game */
264 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
265 extern int chatCount;
267 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
268 char lastMsg[MSG_SIZ];
269 ChessSquare pieceSweep = EmptySquare;
270 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
271 int promoDefaultAltered;
273 /* States for ics_getting_history */
275 #define H_REQUESTED 1
276 #define H_GOT_REQ_HEADER 2
277 #define H_GOT_UNREQ_HEADER 3
278 #define H_GETTING_MOVES 4
279 #define H_GOT_UNWANTED_HEADER 5
281 /* whosays values for GameEnds */
290 /* Maximum number of games in a cmail message */
291 #define CMAIL_MAX_GAMES 20
293 /* Different types of move when calling RegisterMove */
295 #define CMAIL_RESIGN 1
297 #define CMAIL_ACCEPT 3
299 /* Different types of result to remember for each game */
300 #define CMAIL_NOT_RESULT 0
301 #define CMAIL_OLD_RESULT 1
302 #define CMAIL_NEW_RESULT 2
304 /* Telnet protocol constants */
315 safeStrCpy (char *dst, const char *src, size_t count)
318 assert( dst != NULL );
319 assert( src != NULL );
322 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
323 if( i == count && dst[count-1] != NULLCHAR)
325 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
326 if(appData.debugMode)
327 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
333 /* Some compiler can't cast u64 to double
334 * This function do the job for us:
336 * We use the highest bit for cast, this only
337 * works if the highest bit is not
338 * in use (This should not happen)
340 * We used this for all compiler
343 u64ToDouble (u64 value)
346 u64 tmp = value & u64Const(0x7fffffffffffffff);
347 r = (double)(s64)tmp;
348 if (value & u64Const(0x8000000000000000))
349 r += 9.2233720368547758080e18; /* 2^63 */
353 /* Fake up flags for now, as we aren't keeping track of castling
354 availability yet. [HGM] Change of logic: the flag now only
355 indicates the type of castlings allowed by the rule of the game.
356 The actual rights themselves are maintained in the array
357 castlingRights, as part of the game history, and are not probed
363 int flags = F_ALL_CASTLE_OK;
364 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
365 switch (gameInfo.variant) {
367 flags &= ~F_ALL_CASTLE_OK;
368 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
369 flags |= F_IGNORE_CHECK;
371 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
374 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
376 case VariantKriegspiel:
377 flags |= F_KRIEGSPIEL_CAPTURE;
379 case VariantCapaRandom:
380 case VariantFischeRandom:
381 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
382 case VariantNoCastle:
383 case VariantShatranj:
387 flags &= ~F_ALL_CASTLE_OK;
395 FILE *gameFileFP, *debugFP, *serverFP;
396 char *currentDebugFile; // [HGM] debug split: to remember name
399 [AS] Note: sometimes, the sscanf() function is used to parse the input
400 into a fixed-size buffer. Because of this, we must be prepared to
401 receive strings as long as the size of the input buffer, which is currently
402 set to 4K for Windows and 8K for the rest.
403 So, we must either allocate sufficiently large buffers here, or
404 reduce the size of the input buffer in the input reading part.
407 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
408 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
409 char thinkOutput1[MSG_SIZ*10];
411 ChessProgramState first, second, pairing;
413 /* premove variables */
416 int premoveFromX = 0;
417 int premoveFromY = 0;
418 int premovePromoChar = 0;
420 Boolean alarmSounded;
421 /* end premove variables */
423 char *ics_prefix = "$";
424 int ics_type = ICS_GENERIC;
426 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
427 int pauseExamForwardMostMove = 0;
428 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
429 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
430 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
431 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
432 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
433 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
434 int whiteFlag = FALSE, blackFlag = FALSE;
435 int userOfferedDraw = FALSE;
436 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
437 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
438 int cmailMoveType[CMAIL_MAX_GAMES];
439 long ics_clock_paused = 0;
440 ProcRef icsPR = NoProc, cmailPR = NoProc;
441 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
442 GameMode gameMode = BeginningOfGame;
443 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
444 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
445 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
446 int hiddenThinkOutputState = 0; /* [AS] */
447 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
448 int adjudicateLossPlies = 6;
449 char white_holding[64], black_holding[64];
450 TimeMark lastNodeCountTime;
451 long lastNodeCount=0;
452 int shiftKey; // [HGM] set by mouse handler
454 int have_sent_ICS_logon = 0;
456 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
457 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack;
458 Boolean adjustedClock;
459 long timeControl_2; /* [AS] Allow separate time controls */
460 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC; /* [HGM] secondary TC: merge of MPS, TC and inc */
461 long timeRemaining[2][MAX_MOVES];
462 int matchGame = 0, nextGame = 0, roundNr = 0;
463 Boolean waitingForGame = FALSE;
464 TimeMark programStartTime, pauseStart;
465 char ics_handle[MSG_SIZ];
466 int have_set_title = 0;
468 /* animateTraining preserves the state of appData.animate
469 * when Training mode is activated. This allows the
470 * response to be animated when appData.animate == TRUE and
471 * appData.animateDragging == TRUE.
473 Boolean animateTraining;
479 Board boards[MAX_MOVES];
480 /* [HGM] Following 7 needed for accurate legality tests: */
481 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
482 signed char initialRights[BOARD_FILES];
483 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
484 int initialRulePlies, FENrulePlies;
485 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
487 Boolean shuffleOpenings;
488 int mute; // mute all sounds
490 // [HGM] vari: next 12 to save and restore variations
491 #define MAX_VARIATIONS 10
492 int framePtr = MAX_MOVES-1; // points to free stack entry
494 int savedFirst[MAX_VARIATIONS];
495 int savedLast[MAX_VARIATIONS];
496 int savedFramePtr[MAX_VARIATIONS];
497 char *savedDetails[MAX_VARIATIONS];
498 ChessMove savedResult[MAX_VARIATIONS];
500 void PushTail P((int firstMove, int lastMove));
501 Boolean PopTail P((Boolean annotate));
502 void PushInner P((int firstMove, int lastMove));
503 void PopInner P((Boolean annotate));
504 void CleanupTail P((void));
506 ChessSquare FIDEArray[2][BOARD_FILES] = {
507 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
508 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
509 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
510 BlackKing, BlackBishop, BlackKnight, BlackRook }
513 ChessSquare twoKingsArray[2][BOARD_FILES] = {
514 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
515 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
516 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
517 BlackKing, BlackKing, BlackKnight, BlackRook }
520 ChessSquare KnightmateArray[2][BOARD_FILES] = {
521 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
522 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
523 { BlackRook, BlackMan, BlackBishop, BlackQueen,
524 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
527 ChessSquare SpartanArray[2][BOARD_FILES] = {
528 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
529 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
530 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
531 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
534 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
535 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
536 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
537 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
538 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
541 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
542 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
543 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
544 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
545 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
548 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
549 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
550 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
551 { BlackRook, BlackKnight, BlackMan, BlackFerz,
552 BlackKing, BlackMan, BlackKnight, BlackRook }
556 #if (BOARD_FILES>=10)
557 ChessSquare ShogiArray[2][BOARD_FILES] = {
558 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
559 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
560 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
561 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
564 ChessSquare XiangqiArray[2][BOARD_FILES] = {
565 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
566 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
567 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
568 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
571 ChessSquare CapablancaArray[2][BOARD_FILES] = {
572 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
573 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
574 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
575 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
578 ChessSquare GreatArray[2][BOARD_FILES] = {
579 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
580 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
581 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
582 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
585 ChessSquare JanusArray[2][BOARD_FILES] = {
586 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
587 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
588 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
589 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
592 ChessSquare GrandArray[2][BOARD_FILES] = {
593 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
594 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
595 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
596 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
600 ChessSquare GothicArray[2][BOARD_FILES] = {
601 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
602 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
603 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
604 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
607 #define GothicArray CapablancaArray
611 ChessSquare FalconArray[2][BOARD_FILES] = {
612 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
613 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
614 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
615 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
618 #define FalconArray CapablancaArray
621 #else // !(BOARD_FILES>=10)
622 #define XiangqiPosition FIDEArray
623 #define CapablancaArray FIDEArray
624 #define GothicArray FIDEArray
625 #define GreatArray FIDEArray
626 #endif // !(BOARD_FILES>=10)
628 #if (BOARD_FILES>=12)
629 ChessSquare CourierArray[2][BOARD_FILES] = {
630 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
631 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
632 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
633 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
635 #else // !(BOARD_FILES>=12)
636 #define CourierArray CapablancaArray
637 #endif // !(BOARD_FILES>=12)
640 Board initialPosition;
643 /* Convert str to a rating. Checks for special cases of "----",
645 "++++", etc. Also strips ()'s */
647 string_to_rating (char *str)
649 while(*str && !isdigit(*str)) ++str;
651 return 0; /* One of the special "no rating" cases */
659 /* Init programStats */
660 programStats.movelist[0] = 0;
661 programStats.depth = 0;
662 programStats.nr_moves = 0;
663 programStats.moves_left = 0;
664 programStats.nodes = 0;
665 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
666 programStats.score = 0;
667 programStats.got_only_move = 0;
668 programStats.got_fail = 0;
669 programStats.line_is_book = 0;
674 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
675 if (appData.firstPlaysBlack) {
676 first.twoMachinesColor = "black\n";
677 second.twoMachinesColor = "white\n";
679 first.twoMachinesColor = "white\n";
680 second.twoMachinesColor = "black\n";
683 first.other = &second;
684 second.other = &first;
687 if(appData.timeOddsMode) {
688 norm = appData.timeOdds[0];
689 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
691 first.timeOdds = appData.timeOdds[0]/norm;
692 second.timeOdds = appData.timeOdds[1]/norm;
695 if(programVersion) free(programVersion);
696 if (appData.noChessProgram) {
697 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
698 sprintf(programVersion, "%s", PACKAGE_STRING);
700 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
701 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
702 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
707 UnloadEngine (ChessProgramState *cps)
709 /* Kill off first chess program */
710 if (cps->isr != NULL)
711 RemoveInputSource(cps->isr);
714 if (cps->pr != NoProc) {
716 DoSleep( appData.delayBeforeQuit );
717 SendToProgram("quit\n", cps);
718 DoSleep( appData.delayAfterQuit );
719 DestroyChildProcess(cps->pr, cps->useSigterm);
722 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
726 ClearOptions (ChessProgramState *cps)
729 cps->nrOptions = cps->comboCnt = 0;
730 for(i=0; i<MAX_OPTIONS; i++) {
731 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
732 cps->option[i].textValue = 0;
736 char *engineNames[] = {
737 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
738 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
740 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
741 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
746 InitEngine (ChessProgramState *cps, int n)
747 { // [HGM] all engine initialiation put in a function that does one engine
751 cps->which = engineNames[n];
752 cps->maybeThinking = FALSE;
756 cps->sendDrawOffers = 1;
758 cps->program = appData.chessProgram[n];
759 cps->host = appData.host[n];
760 cps->dir = appData.directory[n];
761 cps->initString = appData.engInitString[n];
762 cps->computerString = appData.computerString[n];
763 cps->useSigint = TRUE;
764 cps->useSigterm = TRUE;
765 cps->reuse = appData.reuse[n];
766 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
767 cps->useSetboard = FALSE;
769 cps->usePing = FALSE;
772 cps->usePlayother = FALSE;
773 cps->useColors = TRUE;
774 cps->useUsermove = FALSE;
775 cps->sendICS = FALSE;
776 cps->sendName = appData.icsActive;
777 cps->sdKludge = FALSE;
778 cps->stKludge = FALSE;
779 TidyProgramName(cps->program, cps->host, cps->tidy);
781 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
782 cps->analysisSupport = 2; /* detect */
783 cps->analyzing = FALSE;
784 cps->initDone = FALSE;
786 /* New features added by Tord: */
787 cps->useFEN960 = FALSE;
788 cps->useOOCastle = TRUE;
789 /* End of new features added by Tord. */
790 cps->fenOverride = appData.fenOverride[n];
792 /* [HGM] time odds: set factor for each machine */
793 cps->timeOdds = appData.timeOdds[n];
795 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
796 cps->accumulateTC = appData.accumulateTC[n];
797 cps->maxNrOfSessions = 1;
802 cps->supportsNPS = UNKNOWN;
803 cps->memSize = FALSE;
804 cps->maxCores = FALSE;
805 cps->egtFormats[0] = NULLCHAR;
808 cps->optionSettings = appData.engOptions[n];
810 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
811 cps->isUCI = appData.isUCI[n]; /* [AS] */
812 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
814 if (appData.protocolVersion[n] > PROTOVER
815 || appData.protocolVersion[n] < 1)
820 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
821 appData.protocolVersion[n]);
822 if( (len >= MSG_SIZ) && appData.debugMode )
823 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
825 DisplayFatalError(buf, 0, 2);
829 cps->protocolVersion = appData.protocolVersion[n];
832 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
833 ParseFeatures(appData.featureDefaults, cps);
836 ChessProgramState *savCps;
842 if(WaitForEngine(savCps, LoadEngine)) return;
843 CommonEngineInit(); // recalculate time odds
844 if(gameInfo.variant != StringToVariant(appData.variant)) {
845 // we changed variant when loading the engine; this forces us to reset
846 Reset(TRUE, savCps != &first);
847 EditGameEvent(); // for consistency with other path, as Reset changes mode
849 InitChessProgram(savCps, FALSE);
850 SendToProgram("force\n", savCps);
851 DisplayMessage("", "");
852 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
853 for (i = backwardMostMove; i < forwardMostMove; i++) SendMoveToProgram(i, savCps);
859 ReplaceEngine (ChessProgramState *cps, int n)
863 appData.noChessProgram = FALSE;
864 appData.clockMode = TRUE;
867 if(n) return; // only startup first engine immediately; second can wait
868 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
872 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
873 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
875 static char resetOptions[] =
876 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
877 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
878 "-firstOptions \"\" -firstNPS -1 -fn \"\"";
881 FloatToFront(char **list, char *engineLine)
883 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
885 if(appData.recentEngines <= 0) return;
886 TidyProgramName(engineLine, "localhost", tidy+1);
887 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
888 strncpy(buf+1, *list, MSG_SIZ-50);
889 if(p = strstr(buf, tidy)) { // tidy name appears in list
890 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
891 while(*p++ = *++q); // squeeze out
893 strcat(tidy, buf+1); // put list behind tidy name
894 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
895 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
896 ASSIGN(*list, tidy+1);
900 Load (ChessProgramState *cps, int i)
902 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ];
903 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
904 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
905 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
906 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
907 appData.firstProtocolVersion = PROTOVER;
908 ParseArgsFromString(buf);
910 ReplaceEngine(cps, i);
911 FloatToFront(&appData.recentEngineList, engineLine);
915 while(q = strchr(p, SLASH)) p = q+1;
916 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
917 if(engineDir[0] != NULLCHAR)
918 appData.directory[i] = engineDir;
919 else if(p != engineName) { // derive directory from engine path, when not given
921 appData.directory[i] = strdup(engineName);
923 } else appData.directory[i] = ".";
925 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
926 snprintf(command, MSG_SIZ, "%s %s", p, params);
929 appData.chessProgram[i] = strdup(p);
930 appData.isUCI[i] = isUCI;
931 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
932 appData.hasOwnBookUCI[i] = hasBook;
933 if(!nickName[0]) useNick = FALSE;
934 if(useNick) ASSIGN(appData.pgnName[i], nickName);
938 q = firstChessProgramNames;
939 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
940 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
941 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
942 quote, p, quote, appData.directory[i],
943 useNick ? " -fn \"" : "",
944 useNick ? nickName : "",
946 v1 ? " -firstProtocolVersion 1" : "",
947 hasBook ? "" : " -fNoOwnBookUCI",
948 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
949 storeVariant ? " -variant " : "",
950 storeVariant ? VariantName(gameInfo.variant) : "");
951 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
952 snprintf(firstChessProgramNames, len, "%s%s", q, buf);
954 FloatToFront(&appData.recentEngineList, buf);
956 ReplaceEngine(cps, i);
962 int matched, min, sec;
964 * Parse timeControl resource
966 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
967 appData.movesPerSession)) {
969 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
970 DisplayFatalError(buf, 0, 2);
974 * Parse searchTime resource
976 if (*appData.searchTime != NULLCHAR) {
977 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
979 searchTime = min * 60;
980 } else if (matched == 2) {
981 searchTime = min * 60 + sec;
984 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
985 DisplayFatalError(buf, 0, 2);
994 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
995 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
997 GetTimeMark(&programStartTime);
998 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
999 appData.seedBase = random() + (random()<<15);
1000 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1002 ClearProgramStats();
1003 programStats.ok_to_send = 1;
1004 programStats.seen_stat = 0;
1007 * Initialize game list
1013 * Internet chess server status
1015 if (appData.icsActive) {
1016 appData.matchMode = FALSE;
1017 appData.matchGames = 0;
1019 appData.noChessProgram = !appData.zippyPlay;
1021 appData.zippyPlay = FALSE;
1022 appData.zippyTalk = FALSE;
1023 appData.noChessProgram = TRUE;
1025 if (*appData.icsHelper != NULLCHAR) {
1026 appData.useTelnet = TRUE;
1027 appData.telnetProgram = appData.icsHelper;
1030 appData.zippyTalk = appData.zippyPlay = FALSE;
1033 /* [AS] Initialize pv info list [HGM] and game state */
1037 for( i=0; i<=framePtr; i++ ) {
1038 pvInfoList[i].depth = -1;
1039 boards[i][EP_STATUS] = EP_NONE;
1040 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1046 /* [AS] Adjudication threshold */
1047 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1049 InitEngine(&first, 0);
1050 InitEngine(&second, 1);
1053 pairing.which = "pairing"; // pairing engine
1054 pairing.pr = NoProc;
1056 pairing.program = appData.pairingEngine;
1057 pairing.host = "localhost";
1060 if (appData.icsActive) {
1061 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1062 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1063 appData.clockMode = FALSE;
1064 first.sendTime = second.sendTime = 0;
1068 /* Override some settings from environment variables, for backward
1069 compatibility. Unfortunately it's not feasible to have the env
1070 vars just set defaults, at least in xboard. Ugh.
1072 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1077 if (!appData.icsActive) {
1081 /* Check for variants that are supported only in ICS mode,
1082 or not at all. Some that are accepted here nevertheless
1083 have bugs; see comments below.
1085 VariantClass variant = StringToVariant(appData.variant);
1087 case VariantBughouse: /* need four players and two boards */
1088 case VariantKriegspiel: /* need to hide pieces and move details */
1089 /* case VariantFischeRandom: (Fabien: moved below) */
1090 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1091 if( (len >= MSG_SIZ) && appData.debugMode )
1092 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1094 DisplayFatalError(buf, 0, 2);
1097 case VariantUnknown:
1098 case VariantLoadable:
1108 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1109 if( (len >= MSG_SIZ) && appData.debugMode )
1110 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1112 DisplayFatalError(buf, 0, 2);
1115 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1116 case VariantFairy: /* [HGM] TestLegality definitely off! */
1117 case VariantGothic: /* [HGM] should work */
1118 case VariantCapablanca: /* [HGM] should work */
1119 case VariantCourier: /* [HGM] initial forced moves not implemented */
1120 case VariantShogi: /* [HGM] could still mate with pawn drop */
1121 case VariantKnightmate: /* [HGM] should work */
1122 case VariantCylinder: /* [HGM] untested */
1123 case VariantFalcon: /* [HGM] untested */
1124 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1125 offboard interposition not understood */
1126 case VariantNormal: /* definitely works! */
1127 case VariantWildCastle: /* pieces not automatically shuffled */
1128 case VariantNoCastle: /* pieces not automatically shuffled */
1129 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1130 case VariantLosers: /* should work except for win condition,
1131 and doesn't know captures are mandatory */
1132 case VariantSuicide: /* should work except for win condition,
1133 and doesn't know captures are mandatory */
1134 case VariantGiveaway: /* should work except for win condition,
1135 and doesn't know captures are mandatory */
1136 case VariantTwoKings: /* should work */
1137 case VariantAtomic: /* should work except for win condition */
1138 case Variant3Check: /* should work except for win condition */
1139 case VariantShatranj: /* should work except for all win conditions */
1140 case VariantMakruk: /* should work except for draw countdown */
1141 case VariantBerolina: /* might work if TestLegality is off */
1142 case VariantCapaRandom: /* should work */
1143 case VariantJanus: /* should work */
1144 case VariantSuper: /* experimental */
1145 case VariantGreat: /* experimental, requires legality testing to be off */
1146 case VariantSChess: /* S-Chess, should work */
1147 case VariantGrand: /* should work */
1148 case VariantSpartan: /* should work */
1156 NextIntegerFromString (char ** str, long * value)
1161 while( *s == ' ' || *s == '\t' ) {
1167 if( *s >= '0' && *s <= '9' ) {
1168 while( *s >= '0' && *s <= '9' ) {
1169 *value = *value * 10 + (*s - '0');
1182 NextTimeControlFromString (char ** str, long * value)
1185 int result = NextIntegerFromString( str, &temp );
1188 *value = temp * 60; /* Minutes */
1189 if( **str == ':' ) {
1191 result = NextIntegerFromString( str, &temp );
1192 *value += temp; /* Seconds */
1200 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1201 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1202 int result = -1, type = 0; long temp, temp2;
1204 if(**str != ':') return -1; // old params remain in force!
1206 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1207 if( NextIntegerFromString( str, &temp ) ) return -1;
1208 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1211 /* time only: incremental or sudden-death time control */
1212 if(**str == '+') { /* increment follows; read it */
1214 if(**str == '!') type = *(*str)++; // Bronstein TC
1215 if(result = NextIntegerFromString( str, &temp2)) return -1;
1216 *inc = temp2 * 1000;
1217 if(**str == '.') { // read fraction of increment
1218 char *start = ++(*str);
1219 if(result = NextIntegerFromString( str, &temp2)) return -1;
1221 while(start++ < *str) temp2 /= 10;
1225 *moves = 0; *tc = temp * 1000; *incType = type;
1229 (*str)++; /* classical time control */
1230 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1242 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1243 { /* [HGM] get time to add from the multi-session time-control string */
1244 int incType, moves=1; /* kludge to force reading of first session */
1245 long time, increment;
1248 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1250 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1251 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1252 if(movenr == -1) return time; /* last move before new session */
1253 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1254 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1255 if(!moves) return increment; /* current session is incremental */
1256 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1257 } while(movenr >= -1); /* try again for next session */
1259 return 0; // no new time quota on this move
1263 ParseTimeControl (char *tc, float ti, int mps)
1267 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1270 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1271 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1272 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1276 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1278 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1281 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1283 snprintf(buf, MSG_SIZ, ":%s", mytc);
1285 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1287 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1292 /* Parse second time control */
1295 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1303 timeControl_2 = tc2 * 1000;
1313 timeControl = tc1 * 1000;
1316 timeIncrement = ti * 1000; /* convert to ms */
1317 movesPerSession = 0;
1320 movesPerSession = mps;
1328 if (appData.debugMode) {
1329 fprintf(debugFP, "%s\n", programVersion);
1331 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1333 set_cont_sequence(appData.wrapContSeq);
1334 if (appData.matchGames > 0) {
1335 appData.matchMode = TRUE;
1336 } else if (appData.matchMode) {
1337 appData.matchGames = 1;
1339 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1340 appData.matchGames = appData.sameColorGames;
1341 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1342 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1343 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1346 if (appData.noChessProgram || first.protocolVersion == 1) {
1349 /* kludge: allow timeout for initial "feature" commands */
1351 DisplayMessage("", _("Starting chess program"));
1352 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1357 CalculateIndex (int index, int gameNr)
1358 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1360 if(index > 0) return index; // fixed nmber
1361 if(index == 0) return 1;
1362 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1363 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1368 LoadGameOrPosition (int gameNr)
1369 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1370 if (*appData.loadGameFile != NULLCHAR) {
1371 if (!LoadGameFromFile(appData.loadGameFile,
1372 CalculateIndex(appData.loadGameIndex, gameNr),
1373 appData.loadGameFile, FALSE)) {
1374 DisplayFatalError(_("Bad game file"), 0, 1);
1377 } else if (*appData.loadPositionFile != NULLCHAR) {
1378 if (!LoadPositionFromFile(appData.loadPositionFile,
1379 CalculateIndex(appData.loadPositionIndex, gameNr),
1380 appData.loadPositionFile)) {
1381 DisplayFatalError(_("Bad position file"), 0, 1);
1389 ReserveGame (int gameNr, char resChar)
1391 FILE *tf = fopen(appData.tourneyFile, "r+");
1392 char *p, *q, c, buf[MSG_SIZ];
1393 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1394 safeStrCpy(buf, lastMsg, MSG_SIZ);
1395 DisplayMessage(_("Pick new game"), "");
1396 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1397 ParseArgsFromFile(tf);
1398 p = q = appData.results;
1399 if(appData.debugMode) {
1400 char *r = appData.participants;
1401 fprintf(debugFP, "results = '%s'\n", p);
1402 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1403 fprintf(debugFP, "\n");
1405 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1407 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1408 safeStrCpy(q, p, strlen(p) + 2);
1409 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1410 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1411 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1412 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1415 fseek(tf, -(strlen(p)+4), SEEK_END);
1417 if(c != '"') // depending on DOS or Unix line endings we can be one off
1418 fseek(tf, -(strlen(p)+2), SEEK_END);
1419 else fseek(tf, -(strlen(p)+3), SEEK_END);
1420 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1421 DisplayMessage(buf, "");
1422 free(p); appData.results = q;
1423 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1424 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1425 int round = appData.defaultMatchGames * appData.tourneyType;
1426 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1427 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1428 UnloadEngine(&first); // next game belongs to other pairing;
1429 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1431 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1435 MatchEvent (int mode)
1436 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1438 if(matchMode) { // already in match mode: switch it off
1440 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1443 // if(gameMode != BeginningOfGame) {
1444 // DisplayError(_("You can only start a match from the initial position."), 0);
1448 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1449 /* Set up machine vs. machine match */
1451 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1452 if(appData.tourneyFile[0]) {
1454 if(nextGame > appData.matchGames) {
1456 if(strchr(appData.results, '*') == NULL) {
1458 appData.tourneyCycles++;
1459 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1461 NextTourneyGame(-1, &dummy);
1463 if(nextGame <= appData.matchGames) {
1464 DisplayNote(_("You restarted an already completed tourney\nOne more cycle will now be added to it\nGames commence in 10 sec"));
1466 ScheduleDelayedEvent(NextMatchGame, 10000);
1471 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1472 DisplayError(buf, 0);
1473 appData.tourneyFile[0] = 0;
1477 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1478 DisplayFatalError(_("Can't have a match with no chess programs"),
1483 matchGame = roundNr = 1;
1484 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1488 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1491 InitBackEnd3 P((void))
1493 GameMode initialMode;
1497 InitChessProgram(&first, startedFromSetupPosition);
1499 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1500 free(programVersion);
1501 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1502 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1503 FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1506 if (appData.icsActive) {
1508 /* [DM] Make a console window if needed [HGM] merged ifs */
1514 if (*appData.icsCommPort != NULLCHAR)
1515 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1516 appData.icsCommPort);
1518 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1519 appData.icsHost, appData.icsPort);
1521 if( (len >= MSG_SIZ) && appData.debugMode )
1522 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1524 DisplayFatalError(buf, err, 1);
1529 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1531 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1532 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1533 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1534 } else if (appData.noChessProgram) {
1540 if (*appData.cmailGameName != NULLCHAR) {
1542 OpenLoopback(&cmailPR);
1544 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1548 DisplayMessage("", "");
1549 if (StrCaseCmp(appData.initialMode, "") == 0) {
1550 initialMode = BeginningOfGame;
1551 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1552 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1553 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1554 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1557 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1558 initialMode = TwoMachinesPlay;
1559 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1560 initialMode = AnalyzeFile;
1561 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1562 initialMode = AnalyzeMode;
1563 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1564 initialMode = MachinePlaysWhite;
1565 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1566 initialMode = MachinePlaysBlack;
1567 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1568 initialMode = EditGame;
1569 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1570 initialMode = EditPosition;
1571 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1572 initialMode = Training;
1574 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1575 if( (len >= MSG_SIZ) && appData.debugMode )
1576 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1578 DisplayFatalError(buf, 0, 2);
1582 if (appData.matchMode) {
1583 if(appData.tourneyFile[0]) { // start tourney from command line
1585 if(f = fopen(appData.tourneyFile, "r")) {
1586 ParseArgsFromFile(f); // make sure tourney parmeters re known
1588 appData.clockMode = TRUE;
1590 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1593 } else if (*appData.cmailGameName != NULLCHAR) {
1594 /* Set up cmail mode */
1595 ReloadCmailMsgEvent(TRUE);
1597 /* Set up other modes */
1598 if (initialMode == AnalyzeFile) {
1599 if (*appData.loadGameFile == NULLCHAR) {
1600 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1604 if (*appData.loadGameFile != NULLCHAR) {
1605 (void) LoadGameFromFile(appData.loadGameFile,
1606 appData.loadGameIndex,
1607 appData.loadGameFile, TRUE);
1608 } else if (*appData.loadPositionFile != NULLCHAR) {
1609 (void) LoadPositionFromFile(appData.loadPositionFile,
1610 appData.loadPositionIndex,
1611 appData.loadPositionFile);
1612 /* [HGM] try to make self-starting even after FEN load */
1613 /* to allow automatic setup of fairy variants with wtm */
1614 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1615 gameMode = BeginningOfGame;
1616 setboardSpoiledMachineBlack = 1;
1618 /* [HGM] loadPos: make that every new game uses the setup */
1619 /* from file as long as we do not switch variant */
1620 if(!blackPlaysFirst) {
1621 startedFromPositionFile = TRUE;
1622 CopyBoard(filePosition, boards[0]);
1625 if (initialMode == AnalyzeMode) {
1626 if (appData.noChessProgram) {
1627 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1630 if (appData.icsActive) {
1631 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1635 } else if (initialMode == AnalyzeFile) {
1636 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1637 ShowThinkingEvent();
1639 AnalysisPeriodicEvent(1);
1640 } else if (initialMode == MachinePlaysWhite) {
1641 if (appData.noChessProgram) {
1642 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1646 if (appData.icsActive) {
1647 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1651 MachineWhiteEvent();
1652 } else if (initialMode == MachinePlaysBlack) {
1653 if (appData.noChessProgram) {
1654 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1658 if (appData.icsActive) {
1659 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1663 MachineBlackEvent();
1664 } else if (initialMode == TwoMachinesPlay) {
1665 if (appData.noChessProgram) {
1666 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1670 if (appData.icsActive) {
1671 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1676 } else if (initialMode == EditGame) {
1678 } else if (initialMode == EditPosition) {
1679 EditPositionEvent();
1680 } else if (initialMode == Training) {
1681 if (*appData.loadGameFile == NULLCHAR) {
1682 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1691 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1693 DisplayBook(current+1);
1695 MoveHistorySet( movelist, first, last, current, pvInfoList );
1697 EvalGraphSet( first, last, current, pvInfoList );
1699 MakeEngineOutputTitle();
1703 * Establish will establish a contact to a remote host.port.
1704 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1705 * used to talk to the host.
1706 * Returns 0 if okay, error code if not.
1713 if (*appData.icsCommPort != NULLCHAR) {
1714 /* Talk to the host through a serial comm port */
1715 return OpenCommPort(appData.icsCommPort, &icsPR);
1717 } else if (*appData.gateway != NULLCHAR) {
1718 if (*appData.remoteShell == NULLCHAR) {
1719 /* Use the rcmd protocol to run telnet program on a gateway host */
1720 snprintf(buf, sizeof(buf), "%s %s %s",
1721 appData.telnetProgram, appData.icsHost, appData.icsPort);
1722 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1725 /* Use the rsh program to run telnet program on a gateway host */
1726 if (*appData.remoteUser == NULLCHAR) {
1727 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1728 appData.gateway, appData.telnetProgram,
1729 appData.icsHost, appData.icsPort);
1731 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1732 appData.remoteShell, appData.gateway,
1733 appData.remoteUser, appData.telnetProgram,
1734 appData.icsHost, appData.icsPort);
1736 return StartChildProcess(buf, "", &icsPR);
1739 } else if (appData.useTelnet) {
1740 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1743 /* TCP socket interface differs somewhat between
1744 Unix and NT; handle details in the front end.
1746 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1751 EscapeExpand (char *p, char *q)
1752 { // [HGM] initstring: routine to shape up string arguments
1753 while(*p++ = *q++) if(p[-1] == '\\')
1755 case 'n': p[-1] = '\n'; break;
1756 case 'r': p[-1] = '\r'; break;
1757 case 't': p[-1] = '\t'; break;
1758 case '\\': p[-1] = '\\'; break;
1759 case 0: *p = 0; return;
1760 default: p[-1] = q[-1]; break;
1765 show_bytes (FILE *fp, char *buf, int count)
1768 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1769 fprintf(fp, "\\%03o", *buf & 0xff);
1778 /* Returns an errno value */
1780 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1782 char buf[8192], *p, *q, *buflim;
1783 int left, newcount, outcount;
1785 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1786 *appData.gateway != NULLCHAR) {
1787 if (appData.debugMode) {
1788 fprintf(debugFP, ">ICS: ");
1789 show_bytes(debugFP, message, count);
1790 fprintf(debugFP, "\n");
1792 return OutputToProcess(pr, message, count, outError);
1795 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1802 if (appData.debugMode) {
1803 fprintf(debugFP, ">ICS: ");
1804 show_bytes(debugFP, buf, newcount);
1805 fprintf(debugFP, "\n");
1807 outcount = OutputToProcess(pr, buf, newcount, outError);
1808 if (outcount < newcount) return -1; /* to be sure */
1815 } else if (((unsigned char) *p) == TN_IAC) {
1816 *q++ = (char) TN_IAC;
1823 if (appData.debugMode) {
1824 fprintf(debugFP, ">ICS: ");
1825 show_bytes(debugFP, buf, newcount);
1826 fprintf(debugFP, "\n");
1828 outcount = OutputToProcess(pr, buf, newcount, outError);
1829 if (outcount < newcount) return -1; /* to be sure */
1834 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1836 int outError, outCount;
1837 static int gotEof = 0;
1839 /* Pass data read from player on to ICS */
1842 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1843 if (outCount < count) {
1844 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1846 } else if (count < 0) {
1847 RemoveInputSource(isr);
1848 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1849 } else if (gotEof++ > 0) {
1850 RemoveInputSource(isr);
1851 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1857 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1858 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1859 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1860 SendToICS("date\n");
1861 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1864 /* added routine for printf style output to ics */
1866 ics_printf (char *format, ...)
1868 char buffer[MSG_SIZ];
1871 va_start(args, format);
1872 vsnprintf(buffer, sizeof(buffer), format, args);
1873 buffer[sizeof(buffer)-1] = '\0';
1881 int count, outCount, outError;
1883 if (icsPR == NoProc) return;
1886 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1887 if (outCount < count) {
1888 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1892 /* This is used for sending logon scripts to the ICS. Sending
1893 without a delay causes problems when using timestamp on ICC
1894 (at least on my machine). */
1896 SendToICSDelayed (char *s, long msdelay)
1898 int count, outCount, outError;
1900 if (icsPR == NoProc) return;
1903 if (appData.debugMode) {
1904 fprintf(debugFP, ">ICS: ");
1905 show_bytes(debugFP, s, count);
1906 fprintf(debugFP, "\n");
1908 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1910 if (outCount < count) {
1911 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1916 /* Remove all highlighting escape sequences in s
1917 Also deletes any suffix starting with '('
1920 StripHighlightAndTitle (char *s)
1922 static char retbuf[MSG_SIZ];
1925 while (*s != NULLCHAR) {
1926 while (*s == '\033') {
1927 while (*s != NULLCHAR && !isalpha(*s)) s++;
1928 if (*s != NULLCHAR) s++;
1930 while (*s != NULLCHAR && *s != '\033') {
1931 if (*s == '(' || *s == '[') {
1942 /* Remove all highlighting escape sequences in s */
1944 StripHighlight (char *s)
1946 static char retbuf[MSG_SIZ];
1949 while (*s != NULLCHAR) {
1950 while (*s == '\033') {
1951 while (*s != NULLCHAR && !isalpha(*s)) s++;
1952 if (*s != NULLCHAR) s++;
1954 while (*s != NULLCHAR && *s != '\033') {
1962 char *variantNames[] = VARIANT_NAMES;
1964 VariantName (VariantClass v)
1966 return variantNames[v];
1970 /* Identify a variant from the strings the chess servers use or the
1971 PGN Variant tag names we use. */
1973 StringToVariant (char *e)
1977 VariantClass v = VariantNormal;
1978 int i, found = FALSE;
1984 /* [HGM] skip over optional board-size prefixes */
1985 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1986 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1987 while( *e++ != '_');
1990 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1994 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1995 if (StrCaseStr(e, variantNames[i])) {
1996 v = (VariantClass) i;
2003 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2004 || StrCaseStr(e, "wild/fr")
2005 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2006 v = VariantFischeRandom;
2007 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2008 (i = 1, p = StrCaseStr(e, "w"))) {
2010 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2017 case 0: /* FICS only, actually */
2019 /* Castling legal even if K starts on d-file */
2020 v = VariantWildCastle;
2025 /* Castling illegal even if K & R happen to start in
2026 normal positions. */
2027 v = VariantNoCastle;
2040 /* Castling legal iff K & R start in normal positions */
2046 /* Special wilds for position setup; unclear what to do here */
2047 v = VariantLoadable;
2050 /* Bizarre ICC game */
2051 v = VariantTwoKings;
2054 v = VariantKriegspiel;
2060 v = VariantFischeRandom;
2063 v = VariantCrazyhouse;
2066 v = VariantBughouse;
2072 /* Not quite the same as FICS suicide! */
2073 v = VariantGiveaway;
2079 v = VariantShatranj;
2082 /* Temporary names for future ICC types. The name *will* change in
2083 the next xboard/WinBoard release after ICC defines it. */
2121 v = VariantCapablanca;
2124 v = VariantKnightmate;
2130 v = VariantCylinder;
2136 v = VariantCapaRandom;
2139 v = VariantBerolina;
2151 /* Found "wild" or "w" in the string but no number;
2152 must assume it's normal chess. */
2156 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2157 if( (len >= MSG_SIZ) && appData.debugMode )
2158 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2160 DisplayError(buf, 0);
2166 if (appData.debugMode) {
2167 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
2168 e, wnum, VariantName(v));
2173 static int leftover_start = 0, leftover_len = 0;
2174 char star_match[STAR_MATCH_N][MSG_SIZ];
2176 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2177 advance *index beyond it, and set leftover_start to the new value of
2178 *index; else return FALSE. If pattern contains the character '*', it
2179 matches any sequence of characters not containing '\r', '\n', or the
2180 character following the '*' (if any), and the matched sequence(s) are
2181 copied into star_match.
2184 looking_at ( char *buf, int *index, char *pattern)
2186 char *bufp = &buf[*index], *patternp = pattern;
2188 char *matchp = star_match[0];
2191 if (*patternp == NULLCHAR) {
2192 *index = leftover_start = bufp - buf;
2196 if (*bufp == NULLCHAR) return FALSE;
2197 if (*patternp == '*') {
2198 if (*bufp == *(patternp + 1)) {
2200 matchp = star_match[++star_count];
2204 } else if (*bufp == '\n' || *bufp == '\r') {
2206 if (*patternp == NULLCHAR)
2211 *matchp++ = *bufp++;
2215 if (*patternp != *bufp) return FALSE;
2222 SendToPlayer (char *data, int length)
2224 int error, outCount;
2225 outCount = OutputToProcess(NoProc, data, length, &error);
2226 if (outCount < length) {
2227 DisplayFatalError(_("Error writing to display"), error, 1);
2232 PackHolding (char packed[], char *holding)
2242 switch (runlength) {
2253 sprintf(q, "%d", runlength);
2265 /* Telnet protocol requests from the front end */
2267 TelnetRequest (unsigned char ddww, unsigned char option)
2269 unsigned char msg[3];
2270 int outCount, outError;
2272 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2274 if (appData.debugMode) {
2275 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2291 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2300 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2303 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2308 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2310 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2317 if (!appData.icsActive) return;
2318 TelnetRequest(TN_DO, TN_ECHO);
2324 if (!appData.icsActive) return;
2325 TelnetRequest(TN_DONT, TN_ECHO);
2329 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2331 /* put the holdings sent to us by the server on the board holdings area */
2332 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2336 if(gameInfo.holdingsWidth < 2) return;
2337 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2338 return; // prevent overwriting by pre-board holdings
2340 if( (int)lowestPiece >= BlackPawn ) {
2343 holdingsStartRow = BOARD_HEIGHT-1;
2346 holdingsColumn = BOARD_WIDTH-1;
2347 countsColumn = BOARD_WIDTH-2;
2348 holdingsStartRow = 0;
2352 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2353 board[i][holdingsColumn] = EmptySquare;
2354 board[i][countsColumn] = (ChessSquare) 0;
2356 while( (p=*holdings++) != NULLCHAR ) {
2357 piece = CharToPiece( ToUpper(p) );
2358 if(piece == EmptySquare) continue;
2359 /*j = (int) piece - (int) WhitePawn;*/
2360 j = PieceToNumber(piece);
2361 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2362 if(j < 0) continue; /* should not happen */
2363 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2364 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2365 board[holdingsStartRow+j*direction][countsColumn]++;
2371 VariantSwitch (Board board, VariantClass newVariant)
2373 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2374 static Board oldBoard;
2376 startedFromPositionFile = FALSE;
2377 if(gameInfo.variant == newVariant) return;
2379 /* [HGM] This routine is called each time an assignment is made to
2380 * gameInfo.variant during a game, to make sure the board sizes
2381 * are set to match the new variant. If that means adding or deleting
2382 * holdings, we shift the playing board accordingly
2383 * This kludge is needed because in ICS observe mode, we get boards
2384 * of an ongoing game without knowing the variant, and learn about the
2385 * latter only later. This can be because of the move list we requested,
2386 * in which case the game history is refilled from the beginning anyway,
2387 * but also when receiving holdings of a crazyhouse game. In the latter
2388 * case we want to add those holdings to the already received position.
2392 if (appData.debugMode) {
2393 fprintf(debugFP, "Switch board from %s to %s\n",
2394 VariantName(gameInfo.variant), VariantName(newVariant));
2395 setbuf(debugFP, NULL);
2397 shuffleOpenings = 0; /* [HGM] shuffle */
2398 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2402 newWidth = 9; newHeight = 9;
2403 gameInfo.holdingsSize = 7;
2404 case VariantBughouse:
2405 case VariantCrazyhouse:
2406 newHoldingsWidth = 2; break;
2410 newHoldingsWidth = 2;
2411 gameInfo.holdingsSize = 8;
2414 case VariantCapablanca:
2415 case VariantCapaRandom:
2418 newHoldingsWidth = gameInfo.holdingsSize = 0;
2421 if(newWidth != gameInfo.boardWidth ||
2422 newHeight != gameInfo.boardHeight ||
2423 newHoldingsWidth != gameInfo.holdingsWidth ) {
2425 /* shift position to new playing area, if needed */
2426 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2427 for(i=0; i<BOARD_HEIGHT; i++)
2428 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2429 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2431 for(i=0; i<newHeight; i++) {
2432 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2433 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2435 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2436 for(i=0; i<BOARD_HEIGHT; i++)
2437 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2438 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2441 gameInfo.boardWidth = newWidth;
2442 gameInfo.boardHeight = newHeight;
2443 gameInfo.holdingsWidth = newHoldingsWidth;
2444 gameInfo.variant = newVariant;
2445 InitDrawingSizes(-2, 0);
2446 } else gameInfo.variant = newVariant;
2447 CopyBoard(oldBoard, board); // remember correctly formatted board
2448 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2449 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2452 static int loggedOn = FALSE;
2454 /*-- Game start info cache: --*/
2456 char gs_kind[MSG_SIZ];
2457 static char player1Name[128] = "";
2458 static char player2Name[128] = "";
2459 static char cont_seq[] = "\n\\ ";
2460 static int player1Rating = -1;
2461 static int player2Rating = -1;
2462 /*----------------------------*/
2464 ColorClass curColor = ColorNormal;
2465 int suppressKibitz = 0;
2468 Boolean soughtPending = FALSE;
2469 Boolean seekGraphUp;
2470 #define MAX_SEEK_ADS 200
2472 char *seekAdList[MAX_SEEK_ADS];
2473 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2474 float tcList[MAX_SEEK_ADS];
2475 char colorList[MAX_SEEK_ADS];
2476 int nrOfSeekAds = 0;
2477 int minRating = 1010, maxRating = 2800;
2478 int hMargin = 10, vMargin = 20, h, w;
2479 extern int squareSize, lineGap;
2484 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2485 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2486 if(r < minRating+100 && r >=0 ) r = minRating+100;
2487 if(r > maxRating) r = maxRating;
2488 if(tc < 1.) tc = 1.;
2489 if(tc > 95.) tc = 95.;
2490 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2491 y = ((double)r - minRating)/(maxRating - minRating)
2492 * (h-vMargin-squareSize/8-1) + vMargin;
2493 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2494 if(strstr(seekAdList[i], " u ")) color = 1;
2495 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2496 !strstr(seekAdList[i], "bullet") &&
2497 !strstr(seekAdList[i], "blitz") &&
2498 !strstr(seekAdList[i], "standard") ) color = 2;
2499 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2500 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2504 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2506 char buf[MSG_SIZ], *ext = "";
2507 VariantClass v = StringToVariant(type);
2508 if(strstr(type, "wild")) {
2509 ext = type + 4; // append wild number
2510 if(v == VariantFischeRandom) type = "chess960"; else
2511 if(v == VariantLoadable) type = "setup"; else
2512 type = VariantName(v);
2514 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2515 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2516 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2517 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2518 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2519 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2520 seekNrList[nrOfSeekAds] = nr;
2521 zList[nrOfSeekAds] = 0;
2522 seekAdList[nrOfSeekAds++] = StrSave(buf);
2523 if(plot) PlotSeekAd(nrOfSeekAds-1);
2528 EraseSeekDot (int i)
2530 int x = xList[i], y = yList[i], d=squareSize/4, k;
2531 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2532 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2533 // now replot every dot that overlapped
2534 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2535 int xx = xList[k], yy = yList[k];
2536 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2537 DrawSeekDot(xx, yy, colorList[k]);
2542 RemoveSeekAd (int nr)
2545 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2547 if(seekAdList[i]) free(seekAdList[i]);
2548 seekAdList[i] = seekAdList[--nrOfSeekAds];
2549 seekNrList[i] = seekNrList[nrOfSeekAds];
2550 ratingList[i] = ratingList[nrOfSeekAds];
2551 colorList[i] = colorList[nrOfSeekAds];
2552 tcList[i] = tcList[nrOfSeekAds];
2553 xList[i] = xList[nrOfSeekAds];
2554 yList[i] = yList[nrOfSeekAds];
2555 zList[i] = zList[nrOfSeekAds];
2556 seekAdList[nrOfSeekAds] = NULL;
2562 MatchSoughtLine (char *line)
2564 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2565 int nr, base, inc, u=0; char dummy;
2567 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2568 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2570 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2571 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2572 // match: compact and save the line
2573 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2583 if(!seekGraphUp) return FALSE;
2584 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2585 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2587 DrawSeekBackground(0, 0, w, h);
2588 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2589 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2590 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2591 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2593 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2596 snprintf(buf, MSG_SIZ, "%d", i);
2597 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2600 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2601 for(i=1; i<100; i+=(i<10?1:5)) {
2602 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2603 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2604 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2606 snprintf(buf, MSG_SIZ, "%d", i);
2607 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2610 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2615 SeekGraphClick (ClickType click, int x, int y, int moving)
2617 static int lastDown = 0, displayed = 0, lastSecond;
2618 if(y < 0) return FALSE;
2619 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2620 if(click == Release || moving) return FALSE;
2622 soughtPending = TRUE;
2623 SendToICS(ics_prefix);
2624 SendToICS("sought\n"); // should this be "sought all"?
2625 } else { // issue challenge based on clicked ad
2626 int dist = 10000; int i, closest = 0, second = 0;
2627 for(i=0; i<nrOfSeekAds; i++) {
2628 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2629 if(d < dist) { dist = d; closest = i; }
2630 second += (d - zList[i] < 120); // count in-range ads
2631 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2635 second = (second > 1);
2636 if(displayed != closest || second != lastSecond) {
2637 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2638 lastSecond = second; displayed = closest;
2640 if(click == Press) {
2641 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2644 } // on press 'hit', only show info
2645 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2646 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2647 SendToICS(ics_prefix);
2649 return TRUE; // let incoming board of started game pop down the graph
2650 } else if(click == Release) { // release 'miss' is ignored
2651 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2652 if(moving == 2) { // right up-click
2653 nrOfSeekAds = 0; // refresh graph
2654 soughtPending = TRUE;
2655 SendToICS(ics_prefix);
2656 SendToICS("sought\n"); // should this be "sought all"?
2659 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2660 // press miss or release hit 'pop down' seek graph
2661 seekGraphUp = FALSE;
2662 DrawPosition(TRUE, NULL);
2668 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2670 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2671 #define STARTED_NONE 0
2672 #define STARTED_MOVES 1
2673 #define STARTED_BOARD 2
2674 #define STARTED_OBSERVE 3
2675 #define STARTED_HOLDINGS 4
2676 #define STARTED_CHATTER 5
2677 #define STARTED_COMMENT 6
2678 #define STARTED_MOVES_NOHIDE 7
2680 static int started = STARTED_NONE;
2681 static char parse[20000];
2682 static int parse_pos = 0;
2683 static char buf[BUF_SIZE + 1];
2684 static int firstTime = TRUE, intfSet = FALSE;
2685 static ColorClass prevColor = ColorNormal;
2686 static int savingComment = FALSE;
2687 static int cmatch = 0; // continuation sequence match
2694 int backup; /* [DM] For zippy color lines */
2696 char talker[MSG_SIZ]; // [HGM] chat
2699 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2701 if (appData.debugMode) {
2703 fprintf(debugFP, "<ICS: ");
2704 show_bytes(debugFP, data, count);
2705 fprintf(debugFP, "\n");
2709 if (appData.debugMode) { int f = forwardMostMove;
2710 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2711 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2712 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2715 /* If last read ended with a partial line that we couldn't parse,
2716 prepend it to the new read and try again. */
2717 if (leftover_len > 0) {
2718 for (i=0; i<leftover_len; i++)
2719 buf[i] = buf[leftover_start + i];
2722 /* copy new characters into the buffer */
2723 bp = buf + leftover_len;
2724 buf_len=leftover_len;
2725 for (i=0; i<count; i++)
2728 if (data[i] == '\r')
2731 // join lines split by ICS?
2732 if (!appData.noJoin)
2735 Joining just consists of finding matches against the
2736 continuation sequence, and discarding that sequence
2737 if found instead of copying it. So, until a match
2738 fails, there's nothing to do since it might be the
2739 complete sequence, and thus, something we don't want
2742 if (data[i] == cont_seq[cmatch])
2745 if (cmatch == strlen(cont_seq))
2747 cmatch = 0; // complete match. just reset the counter
2750 it's possible for the ICS to not include the space
2751 at the end of the last word, making our [correct]
2752 join operation fuse two separate words. the server
2753 does this when the space occurs at the width setting.
2755 if (!buf_len || buf[buf_len-1] != ' ')
2766 match failed, so we have to copy what matched before
2767 falling through and copying this character. In reality,
2768 this will only ever be just the newline character, but
2769 it doesn't hurt to be precise.
2771 strncpy(bp, cont_seq, cmatch);
2783 buf[buf_len] = NULLCHAR;
2784 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2789 while (i < buf_len) {
2790 /* Deal with part of the TELNET option negotiation
2791 protocol. We refuse to do anything beyond the
2792 defaults, except that we allow the WILL ECHO option,
2793 which ICS uses to turn off password echoing when we are
2794 directly connected to it. We reject this option
2795 if localLineEditing mode is on (always on in xboard)
2796 and we are talking to port 23, which might be a real
2797 telnet server that will try to keep WILL ECHO on permanently.
2799 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2800 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2801 unsigned char option;
2803 switch ((unsigned char) buf[++i]) {
2805 if (appData.debugMode)
2806 fprintf(debugFP, "\n<WILL ");
2807 switch (option = (unsigned char) buf[++i]) {
2809 if (appData.debugMode)
2810 fprintf(debugFP, "ECHO ");
2811 /* Reply only if this is a change, according
2812 to the protocol rules. */
2813 if (remoteEchoOption) break;
2814 if (appData.localLineEditing &&
2815 atoi(appData.icsPort) == TN_PORT) {
2816 TelnetRequest(TN_DONT, TN_ECHO);
2819 TelnetRequest(TN_DO, TN_ECHO);
2820 remoteEchoOption = TRUE;
2824 if (appData.debugMode)
2825 fprintf(debugFP, "%d ", option);
2826 /* Whatever this is, we don't want it. */
2827 TelnetRequest(TN_DONT, option);
2832 if (appData.debugMode)
2833 fprintf(debugFP, "\n<WONT ");
2834 switch (option = (unsigned char) buf[++i]) {
2836 if (appData.debugMode)
2837 fprintf(debugFP, "ECHO ");
2838 /* Reply only if this is a change, according
2839 to the protocol rules. */
2840 if (!remoteEchoOption) break;
2842 TelnetRequest(TN_DONT, TN_ECHO);
2843 remoteEchoOption = FALSE;
2846 if (appData.debugMode)
2847 fprintf(debugFP, "%d ", (unsigned char) option);
2848 /* Whatever this is, it must already be turned
2849 off, because we never agree to turn on
2850 anything non-default, so according to the
2851 protocol rules, we don't reply. */
2856 if (appData.debugMode)
2857 fprintf(debugFP, "\n<DO ");
2858 switch (option = (unsigned char) buf[++i]) {
2860 /* Whatever this is, we refuse to do it. */
2861 if (appData.debugMode)
2862 fprintf(debugFP, "%d ", option);
2863 TelnetRequest(TN_WONT, option);
2868 if (appData.debugMode)
2869 fprintf(debugFP, "\n<DONT ");
2870 switch (option = (unsigned char) buf[++i]) {
2872 if (appData.debugMode)
2873 fprintf(debugFP, "%d ", option);
2874 /* Whatever this is, we are already not doing
2875 it, because we never agree to do anything
2876 non-default, so according to the protocol
2877 rules, we don't reply. */
2882 if (appData.debugMode)
2883 fprintf(debugFP, "\n<IAC ");
2884 /* Doubled IAC; pass it through */
2888 if (appData.debugMode)
2889 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2890 /* Drop all other telnet commands on the floor */
2893 if (oldi > next_out)
2894 SendToPlayer(&buf[next_out], oldi - next_out);
2900 /* OK, this at least will *usually* work */
2901 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2905 if (loggedOn && !intfSet) {
2906 if (ics_type == ICS_ICC) {
2907 snprintf(str, MSG_SIZ,
2908 "/set-quietly interface %s\n/set-quietly style 12\n",
2910 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2911 strcat(str, "/set-2 51 1\n/set seek 1\n");
2912 } else if (ics_type == ICS_CHESSNET) {
2913 snprintf(str, MSG_SIZ, "/style 12\n");
2915 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2916 strcat(str, programVersion);
2917 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2918 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2919 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2921 strcat(str, "$iset nohighlight 1\n");
2923 strcat(str, "$iset lock 1\n$style 12\n");
2926 NotifyFrontendLogin();
2930 if (started == STARTED_COMMENT) {
2931 /* Accumulate characters in comment */
2932 parse[parse_pos++] = buf[i];
2933 if (buf[i] == '\n') {
2934 parse[parse_pos] = NULLCHAR;
2935 if(chattingPartner>=0) {
2937 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2938 OutputChatMessage(chattingPartner, mess);
2939 chattingPartner = -1;
2940 next_out = i+1; // [HGM] suppress printing in ICS window
2942 if(!suppressKibitz) // [HGM] kibitz
2943 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2944 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2945 int nrDigit = 0, nrAlph = 0, j;
2946 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2947 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2948 parse[parse_pos] = NULLCHAR;
2949 // try to be smart: if it does not look like search info, it should go to
2950 // ICS interaction window after all, not to engine-output window.
2951 for(j=0; j<parse_pos; j++) { // count letters and digits
2952 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2953 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2954 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2956 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2957 int depth=0; float score;
2958 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2959 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2960 pvInfoList[forwardMostMove-1].depth = depth;
2961 pvInfoList[forwardMostMove-1].score = 100*score;
2963 OutputKibitz(suppressKibitz, parse);
2966 if(gameMode == IcsObserving) // restore original ICS messages
2967 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
2969 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2970 SendToPlayer(tmp, strlen(tmp));
2972 next_out = i+1; // [HGM] suppress printing in ICS window
2974 started = STARTED_NONE;
2976 /* Don't match patterns against characters in comment */
2981 if (started == STARTED_CHATTER) {
2982 if (buf[i] != '\n') {
2983 /* Don't match patterns against characters in chatter */
2987 started = STARTED_NONE;
2988 if(suppressKibitz) next_out = i+1;
2991 /* Kludge to deal with rcmd protocol */
2992 if (firstTime && looking_at(buf, &i, "\001*")) {
2993 DisplayFatalError(&buf[1], 0, 1);
2999 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3002 if (appData.debugMode)
3003 fprintf(debugFP, "ics_type %d\n", ics_type);
3006 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3007 ics_type = ICS_FICS;
3009 if (appData.debugMode)
3010 fprintf(debugFP, "ics_type %d\n", ics_type);
3013 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3014 ics_type = ICS_CHESSNET;
3016 if (appData.debugMode)
3017 fprintf(debugFP, "ics_type %d\n", ics_type);
3022 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3023 looking_at(buf, &i, "Logging you in as \"*\"") ||
3024 looking_at(buf, &i, "will be \"*\""))) {
3025 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3029 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3031 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3032 DisplayIcsInteractionTitle(buf);
3033 have_set_title = TRUE;
3036 /* skip finger notes */
3037 if (started == STARTED_NONE &&
3038 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3039 (buf[i] == '1' && buf[i+1] == '0')) &&
3040 buf[i+2] == ':' && buf[i+3] == ' ') {
3041 started = STARTED_CHATTER;
3047 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3048 if(appData.seekGraph) {
3049 if(soughtPending && MatchSoughtLine(buf+i)) {
3050 i = strstr(buf+i, "rated") - buf;
3051 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3052 next_out = leftover_start = i;
3053 started = STARTED_CHATTER;
3054 suppressKibitz = TRUE;
3057 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3058 && looking_at(buf, &i, "* ads displayed")) {
3059 soughtPending = FALSE;
3064 if(appData.autoRefresh) {
3065 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3066 int s = (ics_type == ICS_ICC); // ICC format differs
3068 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3069 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3070 looking_at(buf, &i, "*% "); // eat prompt
3071 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3072 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3073 next_out = i; // suppress
3076 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3077 char *p = star_match[0];
3079 if(seekGraphUp) RemoveSeekAd(atoi(p));
3080 while(*p && *p++ != ' '); // next
3082 looking_at(buf, &i, "*% "); // eat prompt
3083 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3090 /* skip formula vars */
3091 if (started == STARTED_NONE &&
3092 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3093 started = STARTED_CHATTER;
3098 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3099 if (appData.autoKibitz && started == STARTED_NONE &&
3100 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3101 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3102 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3103 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3104 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3105 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3106 suppressKibitz = TRUE;
3107 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3109 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3110 && (gameMode == IcsPlayingWhite)) ||
3111 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3112 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3113 started = STARTED_CHATTER; // own kibitz we simply discard
3115 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3116 parse_pos = 0; parse[0] = NULLCHAR;
3117 savingComment = TRUE;
3118 suppressKibitz = gameMode != IcsObserving ? 2 :
3119 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3123 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3124 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3125 && atoi(star_match[0])) {
3126 // suppress the acknowledgements of our own autoKibitz
3128 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3129 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3130 SendToPlayer(star_match[0], strlen(star_match[0]));
3131 if(looking_at(buf, &i, "*% ")) // eat prompt
3132 suppressKibitz = FALSE;
3136 } // [HGM] kibitz: end of patch
3138 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3140 // [HGM] chat: intercept tells by users for which we have an open chat window
3142 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3143 looking_at(buf, &i, "* whispers:") ||
3144 looking_at(buf, &i, "* kibitzes:") ||
3145 looking_at(buf, &i, "* shouts:") ||
3146 looking_at(buf, &i, "* c-shouts:") ||
3147 looking_at(buf, &i, "--> * ") ||
3148 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3149 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3150 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3151 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3153 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3154 chattingPartner = -1;
3156 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3157 for(p=0; p<MAX_CHAT; p++) {
3158 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3159 talker[0] = '['; strcat(talker, "] ");
3160 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
3161 chattingPartner = p; break;
3164 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3165 for(p=0; p<MAX_CHAT; p++) {
3166 if(!strcmp("kibitzes", chatPartner[p])) {
3167 talker[0] = '['; strcat(talker, "] ");
3168 chattingPartner = p; break;
3171 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3172 for(p=0; p<MAX_CHAT; p++) {
3173 if(!strcmp("whispers", chatPartner[p])) {
3174 talker[0] = '['; strcat(talker, "] ");
3175 chattingPartner = p; break;
3178 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3179 if(buf[i-8] == '-' && buf[i-3] == 't')
3180 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3181 if(!strcmp("c-shouts", chatPartner[p])) {
3182 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3183 chattingPartner = p; break;
3186 if(chattingPartner < 0)
3187 for(p=0; p<MAX_CHAT; p++) {
3188 if(!strcmp("shouts", chatPartner[p])) {
3189 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3190 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3191 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3192 chattingPartner = p; break;
3196 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3197 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3198 talker[0] = 0; Colorize(ColorTell, FALSE);
3199 chattingPartner = p; break;
3201 if(chattingPartner<0) i = oldi; else {
3202 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3203 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3204 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3205 started = STARTED_COMMENT;
3206 parse_pos = 0; parse[0] = NULLCHAR;
3207 savingComment = 3 + chattingPartner; // counts as TRUE
3208 suppressKibitz = TRUE;
3211 } // [HGM] chat: end of patch
3214 if (appData.zippyTalk || appData.zippyPlay) {
3215 /* [DM] Backup address for color zippy lines */
3217 if (loggedOn == TRUE)
3218 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3219 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3221 } // [DM] 'else { ' deleted
3223 /* Regular tells and says */
3224 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3225 looking_at(buf, &i, "* (your partner) tells you: ") ||
3226 looking_at(buf, &i, "* says: ") ||
3227 /* Don't color "message" or "messages" output */
3228 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3229 looking_at(buf, &i, "*. * at *:*: ") ||
3230 looking_at(buf, &i, "--* (*:*): ") ||
3231 /* Message notifications (same color as tells) */
3232 looking_at(buf, &i, "* has left a message ") ||
3233 looking_at(buf, &i, "* just sent you a message:\n") ||
3234 /* Whispers and kibitzes */
3235 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3236 looking_at(buf, &i, "* kibitzes: ") ||
3238 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3240 if (tkind == 1 && strchr(star_match[0], ':')) {
3241 /* Avoid "tells you:" spoofs in channels */
3244 if (star_match[0][0] == NULLCHAR ||
3245 strchr(star_match[0], ' ') ||
3246 (tkind == 3 && strchr(star_match[1], ' '))) {
3247 /* Reject bogus matches */
3250 if (appData.colorize) {
3251 if (oldi > next_out) {
3252 SendToPlayer(&buf[next_out], oldi - next_out);
3257 Colorize(ColorTell, FALSE);
3258 curColor = ColorTell;
3261 Colorize(ColorKibitz, FALSE);
3262 curColor = ColorKibitz;
3265 p = strrchr(star_match[1], '(');
3272 Colorize(ColorChannel1, FALSE);
3273 curColor = ColorChannel1;
3275 Colorize(ColorChannel, FALSE);
3276 curColor = ColorChannel;
3280 curColor = ColorNormal;
3284 if (started == STARTED_NONE && appData.autoComment &&
3285 (gameMode == IcsObserving ||
3286 gameMode == IcsPlayingWhite ||
3287 gameMode == IcsPlayingBlack)) {
3288 parse_pos = i - oldi;
3289 memcpy(parse, &buf[oldi], parse_pos);
3290 parse[parse_pos] = NULLCHAR;
3291 started = STARTED_COMMENT;
3292 savingComment = TRUE;
3294 started = STARTED_CHATTER;
3295 savingComment = FALSE;
3302 if (looking_at(buf, &i, "* s-shouts: ") ||
3303 looking_at(buf, &i, "* c-shouts: ")) {
3304 if (appData.colorize) {
3305 if (oldi > next_out) {
3306 SendToPlayer(&buf[next_out], oldi - next_out);
3309 Colorize(ColorSShout, FALSE);
3310 curColor = ColorSShout;
3313 started = STARTED_CHATTER;
3317 if (looking_at(buf, &i, "--->")) {
3322 if (looking_at(buf, &i, "* shouts: ") ||
3323 looking_at(buf, &i, "--> ")) {
3324 if (appData.colorize) {
3325 if (oldi > next_out) {
3326 SendToPlayer(&buf[next_out], oldi - next_out);
3329 Colorize(ColorShout, FALSE);
3330 curColor = ColorShout;
3333 started = STARTED_CHATTER;
3337 if (looking_at( buf, &i, "Challenge:")) {
3338 if (appData.colorize) {
3339 if (oldi > next_out) {
3340 SendToPlayer(&buf[next_out], oldi - next_out);
3343 Colorize(ColorChallenge, FALSE);
3344 curColor = ColorChallenge;
3350 if (looking_at(buf, &i, "* offers you") ||
3351 looking_at(buf, &i, "* offers to be") ||
3352 looking_at(buf, &i, "* would like to") ||
3353 looking_at(buf, &i, "* requests to") ||
3354 looking_at(buf, &i, "Your opponent offers") ||
3355 looking_at(buf, &i, "Your opponent requests")) {
3357 if (appData.colorize) {
3358 if (oldi > next_out) {
3359 SendToPlayer(&buf[next_out], oldi - next_out);
3362 Colorize(ColorRequest, FALSE);
3363 curColor = ColorRequest;
3368 if (looking_at(buf, &i, "* (*) seeking")) {
3369 if (appData.colorize) {
3370 if (oldi > next_out) {
3371 SendToPlayer(&buf[next_out], oldi - next_out);
3374 Colorize(ColorSeek, FALSE);
3375 curColor = ColorSeek;
3380 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3382 if (looking_at(buf, &i, "\\ ")) {
3383 if (prevColor != ColorNormal) {
3384 if (oldi > next_out) {
3385 SendToPlayer(&buf[next_out], oldi - next_out);
3388 Colorize(prevColor, TRUE);
3389 curColor = prevColor;
3391 if (savingComment) {
3392 parse_pos = i - oldi;
3393 memcpy(parse, &buf[oldi], parse_pos);
3394 parse[parse_pos] = NULLCHAR;
3395 started = STARTED_COMMENT;
3396 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3397 chattingPartner = savingComment - 3; // kludge to remember the box
3399 started = STARTED_CHATTER;
3404 if (looking_at(buf, &i, "Black Strength :") ||
3405 looking_at(buf, &i, "<<< style 10 board >>>") ||
3406 looking_at(buf, &i, "<10>") ||
3407 looking_at(buf, &i, "#@#")) {
3408 /* Wrong board style */
3410 SendToICS(ics_prefix);
3411 SendToICS("set style 12\n");
3412 SendToICS(ics_prefix);
3413 SendToICS("refresh\n");
3417 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3419 have_sent_ICS_logon = 1;
3423 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3424 (looking_at(buf, &i, "\n<12> ") ||
3425 looking_at(buf, &i, "<12> "))) {
3427 if (oldi > next_out) {
3428 SendToPlayer(&buf[next_out], oldi - next_out);
3431 started = STARTED_BOARD;
3436 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3437 looking_at(buf, &i, "<b1> ")) {
3438 if (oldi > next_out) {
3439 SendToPlayer(&buf[next_out], oldi - next_out);
3442 started = STARTED_HOLDINGS;
3447 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3449 /* Header for a move list -- first line */
3451 switch (ics_getting_history) {
3455 case BeginningOfGame:
3456 /* User typed "moves" or "oldmoves" while we
3457 were idle. Pretend we asked for these
3458 moves and soak them up so user can step
3459 through them and/or save them.
3462 gameMode = IcsObserving;
3465 ics_getting_history = H_GOT_UNREQ_HEADER;
3467 case EditGame: /*?*/
3468 case EditPosition: /*?*/
3469 /* Should above feature work in these modes too? */
3470 /* For now it doesn't */
3471 ics_getting_history = H_GOT_UNWANTED_HEADER;
3474 ics_getting_history = H_GOT_UNWANTED_HEADER;
3479 /* Is this the right one? */
3480 if (gameInfo.white && gameInfo.black &&
3481 strcmp(gameInfo.white, star_match[0]) == 0 &&
3482 strcmp(gameInfo.black, star_match[2]) == 0) {
3484 ics_getting_history = H_GOT_REQ_HEADER;
3487 case H_GOT_REQ_HEADER:
3488 case H_GOT_UNREQ_HEADER:
3489 case H_GOT_UNWANTED_HEADER:
3490 case H_GETTING_MOVES:
3491 /* Should not happen */
3492 DisplayError(_("Error gathering move list: two headers"), 0);
3493 ics_getting_history = H_FALSE;
3497 /* Save player ratings into gameInfo if needed */
3498 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3499 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3500 (gameInfo.whiteRating == -1 ||
3501 gameInfo.blackRating == -1)) {
3503 gameInfo.whiteRating = string_to_rating(star_match[1]);
3504 gameInfo.blackRating = string_to_rating(star_match[3]);
3505 if (appData.debugMode)
3506 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3507 gameInfo.whiteRating, gameInfo.blackRating);
3512 if (looking_at(buf, &i,
3513 "* * match, initial time: * minute*, increment: * second")) {
3514 /* Header for a move list -- second line */
3515 /* Initial board will follow if this is a wild game */
3516 if (gameInfo.event != NULL) free(gameInfo.event);
3517 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3518 gameInfo.event = StrSave(str);
3519 /* [HGM] we switched variant. Translate boards if needed. */
3520 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3524 if (looking_at(buf, &i, "Move ")) {
3525 /* Beginning of a move list */
3526 switch (ics_getting_history) {
3528 /* Normally should not happen */
3529 /* Maybe user hit reset while we were parsing */
3532 /* Happens if we are ignoring a move list that is not
3533 * the one we just requested. Common if the user
3534 * tries to observe two games without turning off
3537 case H_GETTING_MOVES:
3538 /* Should not happen */
3539 DisplayError(_("Error gathering move list: nested"), 0);
3540 ics_getting_history = H_FALSE;
3542 case H_GOT_REQ_HEADER:
3543 ics_getting_history = H_GETTING_MOVES;
3544 started = STARTED_MOVES;
3546 if (oldi > next_out) {
3547 SendToPlayer(&buf[next_out], oldi - next_out);
3550 case H_GOT_UNREQ_HEADER:
3551 ics_getting_history = H_GETTING_MOVES;
3552 started = STARTED_MOVES_NOHIDE;
3555 case H_GOT_UNWANTED_HEADER:
3556 ics_getting_history = H_FALSE;
3562 if (looking_at(buf, &i, "% ") ||
3563 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3564 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3565 if(soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3566 soughtPending = FALSE;
3570 if(suppressKibitz) next_out = i;
3571 savingComment = FALSE;
3575 case STARTED_MOVES_NOHIDE:
3576 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3577 parse[parse_pos + i - oldi] = NULLCHAR;
3578 ParseGameHistory(parse);
3580 if (appData.zippyPlay && first.initDone) {
3581 FeedMovesToProgram(&first, forwardMostMove);
3582 if (gameMode == IcsPlayingWhite) {
3583 if (WhiteOnMove(forwardMostMove)) {
3584 if (first.sendTime) {
3585 if (first.useColors) {
3586 SendToProgram("black\n", &first);
3588 SendTimeRemaining(&first, TRUE);
3590 if (first.useColors) {
3591 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3593 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3594 first.maybeThinking = TRUE;
3596 if (first.usePlayother) {
3597 if (first.sendTime) {
3598 SendTimeRemaining(&first, TRUE);
3600 SendToProgram("playother\n", &first);
3606 } else if (gameMode == IcsPlayingBlack) {
3607 if (!WhiteOnMove(forwardMostMove)) {
3608 if (first.sendTime) {
3609 if (first.useColors) {
3610 SendToProgram("white\n", &first);
3612 SendTimeRemaining(&first, FALSE);
3614 if (first.useColors) {
3615 SendToProgram("black\n", &first);
3617 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3618 first.maybeThinking = TRUE;
3620 if (first.usePlayother) {
3621 if (first.sendTime) {
3622 SendTimeRemaining(&first, FALSE);
3624 SendToProgram("playother\n", &first);
3633 if (gameMode == IcsObserving && ics_gamenum == -1) {
3634 /* Moves came from oldmoves or moves command
3635 while we weren't doing anything else.
3637 currentMove = forwardMostMove;
3638 ClearHighlights();/*!!could figure this out*/
3639 flipView = appData.flipView;
3640 DrawPosition(TRUE, boards[currentMove]);
3641 DisplayBothClocks();
3642 snprintf(str, MSG_SIZ, "%s %s %s",
3643 gameInfo.white, _("vs."), gameInfo.black);
3647 /* Moves were history of an active game */
3648 if (gameInfo.resultDetails != NULL) {
3649 free(gameInfo.resultDetails);
3650 gameInfo.resultDetails = NULL;
3653 HistorySet(parseList, backwardMostMove,
3654 forwardMostMove, currentMove-1);
3655 DisplayMove(currentMove - 1);
3656 if (started == STARTED_MOVES) next_out = i;
3657 started = STARTED_NONE;
3658 ics_getting_history = H_FALSE;
3661 case STARTED_OBSERVE:
3662 started = STARTED_NONE;
3663 SendToICS(ics_prefix);
3664 SendToICS("refresh\n");
3670 if(bookHit) { // [HGM] book: simulate book reply
3671 static char bookMove[MSG_SIZ]; // a bit generous?
3673 programStats.nodes = programStats.depth = programStats.time =
3674 programStats.score = programStats.got_only_move = 0;
3675 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3677 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3678 strcat(bookMove, bookHit);
3679 HandleMachineMove(bookMove, &first);
3684 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3685 started == STARTED_HOLDINGS ||
3686 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3687 /* Accumulate characters in move list or board */
3688 parse[parse_pos++] = buf[i];
3691 /* Start of game messages. Mostly we detect start of game
3692 when the first board image arrives. On some versions
3693 of the ICS, though, we need to do a "refresh" after starting
3694 to observe in order to get the current board right away. */
3695 if (looking_at(buf, &i, "Adding game * to observation list")) {
3696 started = STARTED_OBSERVE;
3700 /* Handle auto-observe */
3701 if (appData.autoObserve &&
3702 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3703 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3705 /* Choose the player that was highlighted, if any. */
3706 if (star_match[0][0] == '\033' ||
3707 star_match[1][0] != '\033') {
3708 player = star_match[0];
3710 player = star_match[2];
3712 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3713 ics_prefix, StripHighlightAndTitle(player));
3716 /* Save ratings from notify string */
3717 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3718 player1Rating = string_to_rating(star_match[1]);
3719 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3720 player2Rating = string_to_rating(star_match[3]);
3722 if (appData.debugMode)
3724 "Ratings from 'Game notification:' %s %d, %s %d\n",
3725 player1Name, player1Rating,
3726 player2Name, player2Rating);
3731 /* Deal with automatic examine mode after a game,
3732 and with IcsObserving -> IcsExamining transition */
3733 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3734 looking_at(buf, &i, "has made you an examiner of game *")) {
3736 int gamenum = atoi(star_match[0]);
3737 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3738 gamenum == ics_gamenum) {
3739 /* We were already playing or observing this game;
3740 no need to refetch history */
3741 gameMode = IcsExamining;
3743 pauseExamForwardMostMove = forwardMostMove;
3744 } else if (currentMove < forwardMostMove) {
3745 ForwardInner(forwardMostMove);
3748 /* I don't think this case really can happen */
3749 SendToICS(ics_prefix);
3750 SendToICS("refresh\n");
3755 /* Error messages */
3756 // if (ics_user_moved) {
3757 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3758 if (looking_at(buf, &i, "Illegal move") ||
3759 looking_at(buf, &i, "Not a legal move") ||
3760 looking_at(buf, &i, "Your king is in check") ||
3761 looking_at(buf, &i, "It isn't your turn") ||
3762 looking_at(buf, &i, "It is not your move")) {
3764 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3765 currentMove = forwardMostMove-1;
3766 DisplayMove(currentMove - 1); /* before DMError */
3767 DrawPosition(FALSE, boards[currentMove]);
3768 SwitchClocks(forwardMostMove-1); // [HGM] race
3769 DisplayBothClocks();
3771 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3777 if (looking_at(buf, &i, "still have time") ||
3778 looking_at(buf, &i, "not out of time") ||
3779 looking_at(buf, &i, "either player is out of time") ||
3780 looking_at(buf, &i, "has timeseal; checking")) {
3781 /* We must have called his flag a little too soon */
3782 whiteFlag = blackFlag = FALSE;
3786 if (looking_at(buf, &i, "added * seconds to") ||
3787 looking_at(buf, &i, "seconds were added to")) {
3788 /* Update the clocks */
3789 SendToICS(ics_prefix);
3790 SendToICS("refresh\n");
3794 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3795 ics_clock_paused = TRUE;
3800 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3801 ics_clock_paused = FALSE;
3806 /* Grab player ratings from the Creating: message.
3807 Note we have to check for the special case when
3808 the ICS inserts things like [white] or [black]. */
3809 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3810 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3812 0 player 1 name (not necessarily white)
3814 2 empty, white, or black (IGNORED)
3815 3 player 2 name (not necessarily black)
3818 The names/ratings are sorted out when the game
3819 actually starts (below).
3821 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3822 player1Rating = string_to_rating(star_match[1]);
3823 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3824 player2Rating = string_to_rating(star_match[4]);
3826 if (appData.debugMode)
3828 "Ratings from 'Creating:' %s %d, %s %d\n",
3829 player1Name, player1Rating,
3830 player2Name, player2Rating);
3835 /* Improved generic start/end-of-game messages */
3836 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3837 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3838 /* If tkind == 0: */
3839 /* star_match[0] is the game number */
3840 /* [1] is the white player's name */
3841 /* [2] is the black player's name */
3842 /* For end-of-game: */
3843 /* [3] is the reason for the game end */
3844 /* [4] is a PGN end game-token, preceded by " " */
3845 /* For start-of-game: */
3846 /* [3] begins with "Creating" or "Continuing" */
3847 /* [4] is " *" or empty (don't care). */
3848 int gamenum = atoi(star_match[0]);
3849 char *whitename, *blackname, *why, *endtoken;
3850 ChessMove endtype = EndOfFile;
3853 whitename = star_match[1];
3854 blackname = star_match[2];
3855 why = star_match[3];
3856 endtoken = star_match[4];
3858 whitename = star_match[1];
3859 blackname = star_match[3];
3860 why = star_match[5];
3861 endtoken = star_match[6];
3864 /* Game start messages */
3865 if (strncmp(why, "Creating ", 9) == 0 ||
3866 strncmp(why, "Continuing ", 11) == 0) {
3867 gs_gamenum = gamenum;
3868 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3869 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
3870 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3872 if (appData.zippyPlay) {
3873 ZippyGameStart(whitename, blackname);
3876 partnerBoardValid = FALSE; // [HGM] bughouse
3880 /* Game end messages */
3881 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3882 ics_gamenum != gamenum) {
3885 while (endtoken[0] == ' ') endtoken++;
3886 switch (endtoken[0]) {
3889 endtype = GameUnfinished;
3892 endtype = BlackWins;
3895 if (endtoken[1] == '/')
3896 endtype = GameIsDrawn;
3898 endtype = WhiteWins;
3901 GameEnds(endtype, why, GE_ICS);
3903 if (appData.zippyPlay && first.initDone) {
3904 ZippyGameEnd(endtype, why);
3905 if (first.pr == NoProc) {
3906 /* Start the next process early so that we'll
3907 be ready for the next challenge */
3908 StartChessProgram(&first);
3910 /* Send "new" early, in case this command takes
3911 a long time to finish, so that we'll be ready
3912 for the next challenge. */
3913 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3917 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3921 if (looking_at(buf, &i, "Removing game * from observation") ||
3922 looking_at(buf, &i, "no longer observing game *") ||
3923 looking_at(buf, &i, "Game * (*) has no examiners")) {
3924 if (gameMode == IcsObserving &&
3925 atoi(star_match[0]) == ics_gamenum)
3927 /* icsEngineAnalyze */
3928 if (appData.icsEngineAnalyze) {
3935 ics_user_moved = FALSE;
3940 if (looking_at(buf, &i, "no longer examining game *")) {
3941 if (gameMode == IcsExamining &&
3942 atoi(star_match[0]) == ics_gamenum)
3946 ics_user_moved = FALSE;
3951 /* Advance leftover_start past any newlines we find,
3952 so only partial lines can get reparsed */
3953 if (looking_at(buf, &i, "\n")) {
3954 prevColor = curColor;
3955 if (curColor != ColorNormal) {
3956 if (oldi > next_out) {
3957 SendToPlayer(&buf[next_out], oldi - next_out);
3960 Colorize(ColorNormal, FALSE);
3961 curColor = ColorNormal;
3963 if (started == STARTED_BOARD) {
3964 started = STARTED_NONE;
3965 parse[parse_pos] = NULLCHAR;
3966 ParseBoard12(parse);
3969 /* Send premove here */
3970 if (appData.premove) {
3972 if (currentMove == 0 &&
3973 gameMode == IcsPlayingWhite &&
3974 appData.premoveWhite) {
3975 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3976 if (appData.debugMode)
3977 fprintf(debugFP, "Sending premove:\n");
3979 } else if (currentMove == 1 &&
3980 gameMode == IcsPlayingBlack &&
3981 appData.premoveBlack) {
3982 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3983 if (appData.debugMode)
3984 fprintf(debugFP, "Sending premove:\n");
3986 } else if (gotPremove) {
3988 ClearPremoveHighlights();
3989 if (appData.debugMode)
3990 fprintf(debugFP, "Sending premove:\n");
3991 UserMoveEvent(premoveFromX, premoveFromY,
3992 premoveToX, premoveToY,
3997 /* Usually suppress following prompt */
3998 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3999 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4000 if (looking_at(buf, &i, "*% ")) {
4001 savingComment = FALSE;
4006 } else if (started == STARTED_HOLDINGS) {
4008 char new_piece[MSG_SIZ];
4009 started = STARTED_NONE;
4010 parse[parse_pos] = NULLCHAR;
4011 if (appData.debugMode)
4012 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4013 parse, currentMove);
4014 if (sscanf(parse, " game %d", &gamenum) == 1) {
4015 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4016 if (gameInfo.variant == VariantNormal) {
4017 /* [HGM] We seem to switch variant during a game!
4018 * Presumably no holdings were displayed, so we have
4019 * to move the position two files to the right to
4020 * create room for them!
4022 VariantClass newVariant;
4023 switch(gameInfo.boardWidth) { // base guess on board width
4024 case 9: newVariant = VariantShogi; break;
4025 case 10: newVariant = VariantGreat; break;
4026 default: newVariant = VariantCrazyhouse; break;
4028 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4029 /* Get a move list just to see the header, which
4030 will tell us whether this is really bug or zh */
4031 if (ics_getting_history == H_FALSE) {
4032 ics_getting_history = H_REQUESTED;
4033 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4037 new_piece[0] = NULLCHAR;
4038 sscanf(parse, "game %d white [%s black [%s <- %s",
4039 &gamenum, white_holding, black_holding,
4041 white_holding[strlen(white_holding)-1] = NULLCHAR;
4042 black_holding[strlen(black_holding)-1] = NULLCHAR;
4043 /* [HGM] copy holdings to board holdings area */
4044 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4045 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4046 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4048 if (appData.zippyPlay && first.initDone) {
4049 ZippyHoldings(white_holding, black_holding,
4053 if (tinyLayout || smallLayout) {
4054 char wh[16], bh[16];
4055 PackHolding(wh, white_holding);
4056 PackHolding(bh, black_holding);
4057 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4058 gameInfo.white, gameInfo.black);
4060 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4061 gameInfo.white, white_holding, _("vs."),
4062 gameInfo.black, black_holding);
4064 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4065 DrawPosition(FALSE, boards[currentMove]);
4067 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4068 sscanf(parse, "game %d white [%s black [%s <- %s",
4069 &gamenum, white_holding, black_holding,
4071 white_holding[strlen(white_holding)-1] = NULLCHAR;
4072 black_holding[strlen(black_holding)-1] = NULLCHAR;
4073 /* [HGM] copy holdings to partner-board holdings area */
4074 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4075 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4076 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4077 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4078 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4081 /* Suppress following prompt */
4082 if (looking_at(buf, &i, "*% ")) {
4083 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4084 savingComment = FALSE;
4092 i++; /* skip unparsed character and loop back */
4095 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4096 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4097 // SendToPlayer(&buf[next_out], i - next_out);
4098 started != STARTED_HOLDINGS && leftover_start > next_out) {
4099 SendToPlayer(&buf[next_out], leftover_start - next_out);
4103 leftover_len = buf_len - leftover_start;
4104 /* if buffer ends with something we couldn't parse,
4105 reparse it after appending the next read */
4107 } else if (count == 0) {
4108 RemoveInputSource(isr);
4109 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4111 DisplayFatalError(_("Error reading from ICS"), error, 1);
4116 /* Board style 12 looks like this:
4118 <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
4120 * The "<12> " is stripped before it gets to this routine. The two
4121 * trailing 0's (flip state and clock ticking) are later addition, and
4122 * some chess servers may not have them, or may have only the first.
4123 * Additional trailing fields may be added in the future.
4126 #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"
4128 #define RELATION_OBSERVING_PLAYED 0
4129 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4130 #define RELATION_PLAYING_MYMOVE 1
4131 #define RELATION_PLAYING_NOTMYMOVE -1
4132 #define RELATION_EXAMINING 2
4133 #define RELATION_ISOLATED_BOARD -3
4134 #define RELATION_STARTING_POSITION -4 /* FICS only */
4137 ParseBoard12 (char *string)
4139 GameMode newGameMode;
4140 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
4141 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
4142 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4143 char to_play, board_chars[200];
4144 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4145 char black[32], white[32];
4147 int prevMove = currentMove;
4150 int fromX, fromY, toX, toY;
4152 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4153 char *bookHit = NULL; // [HGM] book
4154 Boolean weird = FALSE, reqFlag = FALSE;
4156 fromX = fromY = toX = toY = -1;
4160 if (appData.debugMode)
4161 fprintf(debugFP, _("Parsing board: %s\n"), string);
4163 move_str[0] = NULLCHAR;
4164 elapsed_time[0] = NULLCHAR;
4165 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4167 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4168 if(string[i] == ' ') { ranks++; files = 0; }
4170 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4173 for(j = 0; j <i; j++) board_chars[j] = string[j];
4174 board_chars[i] = '\0';
4177 n = sscanf(string, PATTERN, &to_play, &double_push,
4178 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4179 &gamenum, white, black, &relation, &basetime, &increment,
4180 &white_stren, &black_stren, &white_time, &black_time,
4181 &moveNum, str, elapsed_time, move_str, &ics_flip,
4185 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4186 DisplayError(str, 0);
4190 /* Convert the move number to internal form */
4191 moveNum = (moveNum - 1) * 2;
4192 if (to_play == 'B') moveNum++;
4193 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4194 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4200 case RELATION_OBSERVING_PLAYED:
4201 case RELATION_OBSERVING_STATIC:
4202 if (gamenum == -1) {
4203 /* Old ICC buglet */
4204 relation = RELATION_OBSERVING_STATIC;
4206 newGameMode = IcsObserving;
4208 case RELATION_PLAYING_MYMOVE:
4209 case RELATION_PLAYING_NOTMYMOVE:
4211 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4212 IcsPlayingWhite : IcsPlayingBlack;
4214 case RELATION_EXAMINING:
4215 newGameMode = IcsExamining;
4217 case RELATION_ISOLATED_BOARD:
4219 /* Just display this board. If user was doing something else,
4220 we will forget about it until the next board comes. */
4221 newGameMode = IcsIdle;
4223 case RELATION_STARTING_POSITION:
4224 newGameMode = gameMode;
4228 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
4229 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4230 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4232 for (k = 0; k < ranks; k++) {
4233 for (j = 0; j < files; j++)
4234 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4235 if(gameInfo.holdingsWidth > 1) {
4236 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4237 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4240 CopyBoard(partnerBoard, board);
4241 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4242 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4243 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4244 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4245 if(toSqr = strchr(str, '-')) {
4246 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4247 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4248 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4249 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4250 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4251 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4252 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
4253 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
4254 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
4255 DisplayMessage(partnerStatus, "");
4256 partnerBoardValid = TRUE;
4260 /* Modify behavior for initial board display on move listing
4263 switch (ics_getting_history) {
4267 case H_GOT_REQ_HEADER:
4268 case H_GOT_UNREQ_HEADER:
4269 /* This is the initial position of the current game */
4270 gamenum = ics_gamenum;
4271 moveNum = 0; /* old ICS bug workaround */
4272 if (to_play == 'B') {
4273 startedFromSetupPosition = TRUE;
4274 blackPlaysFirst = TRUE;
4276 if (forwardMostMove == 0) forwardMostMove = 1;
4277 if (backwardMostMove == 0) backwardMostMove = 1;
4278 if (currentMove == 0) currentMove = 1;
4280 newGameMode = gameMode;
4281 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4283 case H_GOT_UNWANTED_HEADER:
4284 /* This is an initial board that we don't want */
4286 case H_GETTING_MOVES:
4287 /* Should not happen */
4288 DisplayError(_("Error gathering move list: extra board"), 0);
4289 ics_getting_history = H_FALSE;
4293 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4294 weird && (int)gameInfo.variant < (int)VariantShogi) {
4295 /* [HGM] We seem to have switched variant unexpectedly
4296 * Try to guess new variant from board size
4298 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4299 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4300 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4301 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4302 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4303 if(!weird) newVariant = VariantNormal;
4304 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4305 /* Get a move list just to see the header, which
4306 will tell us whether this is really bug or zh */
4307 if (ics_getting_history == H_FALSE) {
4308 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4309 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4314 /* Take action if this is the first board of a new game, or of a
4315 different game than is currently being displayed. */
4316 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4317 relation == RELATION_ISOLATED_BOARD) {
4319 /* Forget the old game and get the history (if any) of the new one */
4320 if (gameMode != BeginningOfGame) {
4324 if (appData.autoRaiseBoard) BoardToTop();
4326 if (gamenum == -1) {
4327 newGameMode = IcsIdle;
4328 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4329 appData.getMoveList && !reqFlag) {
4330 /* Need to get game history */
4331 ics_getting_history = H_REQUESTED;
4332 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4336 /* Initially flip the board to have black on the bottom if playing
4337 black or if the ICS flip flag is set, but let the user change
4338 it with the Flip View button. */
4339 flipView = appData.autoFlipView ?
4340 (newGameMode == IcsPlayingBlack) || ics_flip :
4343 /* Done with values from previous mode; copy in new ones */
4344 gameMode = newGameMode;
4346 ics_gamenum = gamenum;
4347 if (gamenum == gs_gamenum) {
4348 int klen = strlen(gs_kind);
4349 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4350 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4351 gameInfo.event = StrSave(str);
4353 gameInfo.event = StrSave("ICS game");
4355 gameInfo.site = StrSave(appData.icsHost);
4356 gameInfo.date = PGNDate();
4357 gameInfo.round = StrSave("-");
4358 gameInfo.white = StrSave(white);
4359 gameInfo.black = StrSave(black);
4360 timeControl = basetime * 60 * 1000;
4362 timeIncrement = increment * 1000;
4363 movesPerSession = 0;
4364 gameInfo.timeControl = TimeControlTagValue();
4365 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4366 if (appData.debugMode) {
4367 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4368 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4369 setbuf(debugFP, NULL);
4372 gameInfo.outOfBook = NULL;
4374 /* Do we have the ratings? */
4375 if (strcmp(player1Name, white) == 0 &&
4376 strcmp(player2Name, black) == 0) {
4377 if (appData.debugMode)
4378 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4379 player1Rating, player2Rating);
4380 gameInfo.whiteRating = player1Rating;
4381 gameInfo.blackRating = player2Rating;
4382 } else if (strcmp(player2Name, white) == 0 &&
4383 strcmp(player1Name, black) == 0) {
4384 if (appData.debugMode)
4385 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4386 player2Rating, player1Rating);
4387 gameInfo.whiteRating = player2Rating;
4388 gameInfo.blackRating = player1Rating;
4390 player1Name[0] = player2Name[0] = NULLCHAR;
4392 /* Silence shouts if requested */
4393 if (appData.quietPlay &&
4394 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4395 SendToICS(ics_prefix);
4396 SendToICS("set shout 0\n");
4400 /* Deal with midgame name changes */
4402 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4403 if (gameInfo.white) free(gameInfo.white);
4404 gameInfo.white = StrSave(white);
4406 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4407 if (gameInfo.black) free(gameInfo.black);
4408 gameInfo.black = StrSave(black);
4412 /* Throw away game result if anything actually changes in examine mode */
4413 if (gameMode == IcsExamining && !newGame) {
4414 gameInfo.result = GameUnfinished;
4415 if (gameInfo.resultDetails != NULL) {
4416 free(gameInfo.resultDetails);
4417 gameInfo.resultDetails = NULL;
4421 /* In pausing && IcsExamining mode, we ignore boards coming
4422 in if they are in a different variation than we are. */
4423 if (pauseExamInvalid) return;
4424 if (pausing && gameMode == IcsExamining) {
4425 if (moveNum <= pauseExamForwardMostMove) {
4426 pauseExamInvalid = TRUE;
4427 forwardMostMove = pauseExamForwardMostMove;
4432 if (appData.debugMode) {
4433 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4435 /* Parse the board */
4436 for (k = 0; k < ranks; k++) {
4437 for (j = 0; j < files; j++)
4438 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4439 if(gameInfo.holdingsWidth > 1) {
4440 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4441 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4444 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4445 board[5][BOARD_RGHT+1] = WhiteAngel;
4446 board[6][BOARD_RGHT+1] = WhiteMarshall;
4447 board[1][0] = BlackMarshall;
4448 board[2][0] = BlackAngel;
4449 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4451 CopyBoard(boards[moveNum], board);
4452 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4454 startedFromSetupPosition =
4455 !CompareBoards(board, initialPosition);
4456 if(startedFromSetupPosition)
4457 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4460 /* [HGM] Set castling rights. Take the outermost Rooks,
4461 to make it also work for FRC opening positions. Note that board12
4462 is really defective for later FRC positions, as it has no way to
4463 indicate which Rook can castle if they are on the same side of King.
4464 For the initial position we grant rights to the outermost Rooks,
4465 and remember thos rights, and we then copy them on positions
4466 later in an FRC game. This means WB might not recognize castlings with
4467 Rooks that have moved back to their original position as illegal,
4468 but in ICS mode that is not its job anyway.
4470 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4471 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4473 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4474 if(board[0][i] == WhiteRook) j = i;
4475 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4476 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4477 if(board[0][i] == WhiteRook) j = i;
4478 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4479 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4480 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4481 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4482 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4483 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4484 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4486 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4487 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4488 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4489 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4490 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4491 if(board[BOARD_HEIGHT-1][k] == bKing)
4492 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4493 if(gameInfo.variant == VariantTwoKings) {
4494 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4495 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4496 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4499 r = boards[moveNum][CASTLING][0] = initialRights[0];
4500 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4501 r = boards[moveNum][CASTLING][1] = initialRights[1];
4502 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4503 r = boards[moveNum][CASTLING][3] = initialRights[3];
4504 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4505 r = boards[moveNum][CASTLING][4] = initialRights[4];
4506 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4507 /* wildcastle kludge: always assume King has rights */
4508 r = boards[moveNum][CASTLING][2] = initialRights[2];
4509 r = boards[moveNum][CASTLING][5] = initialRights[5];
4511 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4512 boards[moveNum][EP_STATUS] = EP_NONE;
4513 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4514 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4515 if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4518 if (ics_getting_history == H_GOT_REQ_HEADER ||
4519 ics_getting_history == H_GOT_UNREQ_HEADER) {
4520 /* This was an initial position from a move list, not
4521 the current position */
4525 /* Update currentMove and known move number limits */
4526 newMove = newGame || moveNum > forwardMostMove;
4529 forwardMostMove = backwardMostMove = currentMove = moveNum;
4530 if (gameMode == IcsExamining && moveNum == 0) {
4531 /* Workaround for ICS limitation: we are not told the wild
4532 type when starting to examine a game. But if we ask for
4533 the move list, the move list header will tell us */
4534 ics_getting_history = H_REQUESTED;
4535 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4538 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4539 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4541 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4542 /* [HGM] applied this also to an engine that is silently watching */
4543 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4544 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4545 gameInfo.variant == currentlyInitializedVariant) {
4546 takeback = forwardMostMove - moveNum;
4547 for (i = 0; i < takeback; i++) {
4548 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4549 SendToProgram("undo\n", &first);
4554 forwardMostMove = moveNum;
4555 if (!pausing || currentMove > forwardMostMove)
4556 currentMove = forwardMostMove;
4558 /* New part of history that is not contiguous with old part */
4559 if (pausing && gameMode == IcsExamining) {
4560 pauseExamInvalid = TRUE;
4561 forwardMostMove = pauseExamForwardMostMove;
4564 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4566 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4567 // [HGM] when we will receive the move list we now request, it will be
4568 // fed to the engine from the first move on. So if the engine is not
4569 // in the initial position now, bring it there.
4570 InitChessProgram(&first, 0);
4573 ics_getting_history = H_REQUESTED;
4574 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4577 forwardMostMove = backwardMostMove = currentMove = moveNum;
4580 /* Update the clocks */
4581 if (strchr(elapsed_time, '.')) {
4583 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4584 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4586 /* Time is in seconds */
4587 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4588 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4593 if (appData.zippyPlay && newGame &&
4594 gameMode != IcsObserving && gameMode != IcsIdle &&
4595 gameMode != IcsExamining)
4596 ZippyFirstBoard(moveNum, basetime, increment);
4599 /* Put the move on the move list, first converting
4600 to canonical algebraic form. */
4602 if (appData.debugMode) {
4603 if (appData.debugMode) { int f = forwardMostMove;
4604 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4605 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4606 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4608 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4609 fprintf(debugFP, "moveNum = %d\n", moveNum);
4610 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4611 setbuf(debugFP, NULL);
4613 if (moveNum <= backwardMostMove) {
4614 /* We don't know what the board looked like before
4616 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4617 strcat(parseList[moveNum - 1], " ");
4618 strcat(parseList[moveNum - 1], elapsed_time);
4619 moveList[moveNum - 1][0] = NULLCHAR;
4620 } else if (strcmp(move_str, "none") == 0) {
4621 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4622 /* Again, we don't know what the board looked like;
4623 this is really the start of the game. */
4624 parseList[moveNum - 1][0] = NULLCHAR;
4625 moveList[moveNum - 1][0] = NULLCHAR;
4626 backwardMostMove = moveNum;
4627 startedFromSetupPosition = TRUE;
4628 fromX = fromY = toX = toY = -1;
4630 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4631 // So we parse the long-algebraic move string in stead of the SAN move
4632 int valid; char buf[MSG_SIZ], *prom;
4634 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4635 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4636 // str looks something like "Q/a1-a2"; kill the slash
4638 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4639 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4640 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4641 strcat(buf, prom); // long move lacks promo specification!
4642 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4643 if(appData.debugMode)
4644 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4645 safeStrCpy(move_str, buf, MSG_SIZ);
4647 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4648 &fromX, &fromY, &toX, &toY, &promoChar)
4649 || ParseOneMove(buf, moveNum - 1, &moveType,
4650 &fromX, &fromY, &toX, &toY, &promoChar);
4651 // end of long SAN patch
4653 (void) CoordsToAlgebraic(boards[moveNum - 1],
4654 PosFlags(moveNum - 1),
4655 fromY, fromX, toY, toX, promoChar,
4656 parseList[moveNum-1]);
4657 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4663 if(gameInfo.variant != VariantShogi)
4664 strcat(parseList[moveNum - 1], "+");
4667 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4668 strcat(parseList[moveNum - 1], "#");
4671 strcat(parseList[moveNum - 1], " ");
4672 strcat(parseList[moveNum - 1], elapsed_time);
4673 /* currentMoveString is set as a side-effect of ParseOneMove */
4674 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4675 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4676 strcat(moveList[moveNum - 1], "\n");
4678 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4679 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4680 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4681 ChessSquare old, new = boards[moveNum][k][j];
4682 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4683 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4684 if(old == new) continue;
4685 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4686 else if(new == WhiteWazir || new == BlackWazir) {
4687 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4688 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4689 else boards[moveNum][k][j] = old; // preserve type of Gold
4690 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4691 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4694 /* Move from ICS was illegal!? Punt. */
4695 if (appData.debugMode) {
4696 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4697 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4699 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4700 strcat(parseList[moveNum - 1], " ");
4701 strcat(parseList[moveNum - 1], elapsed_time);
4702 moveList[moveNum - 1][0] = NULLCHAR;
4703 fromX = fromY = toX = toY = -1;
4706 if (appData.debugMode) {
4707 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4708 setbuf(debugFP, NULL);
4712 /* Send move to chess program (BEFORE animating it). */
4713 if (appData.zippyPlay && !newGame && newMove &&
4714 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4716 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4717 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4718 if (moveList[moveNum - 1][0] == NULLCHAR) {
4719 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4721 DisplayError(str, 0);
4723 if (first.sendTime) {
4724 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4726 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4727 if (firstMove && !bookHit) {
4729 if (first.useColors) {
4730 SendToProgram(gameMode == IcsPlayingWhite ?
4732 "black\ngo\n", &first);
4734 SendToProgram("go\n", &first);
4736 first.maybeThinking = TRUE;
4739 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4740 if (moveList[moveNum - 1][0] == NULLCHAR) {
4741 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4742 DisplayError(str, 0);
4744 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4745 SendMoveToProgram(moveNum - 1, &first);
4752 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4753 /* If move comes from a remote source, animate it. If it
4754 isn't remote, it will have already been animated. */
4755 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4756 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4758 if (!pausing && appData.highlightLastMove) {
4759 SetHighlights(fromX, fromY, toX, toY);
4763 /* Start the clocks */
4764 whiteFlag = blackFlag = FALSE;
4765 appData.clockMode = !(basetime == 0 && increment == 0);
4767 ics_clock_paused = TRUE;
4769 } else if (ticking == 1) {
4770 ics_clock_paused = FALSE;
4772 if (gameMode == IcsIdle ||
4773 relation == RELATION_OBSERVING_STATIC ||
4774 relation == RELATION_EXAMINING ||
4776 DisplayBothClocks();
4780 /* Display opponents and material strengths */
4781 if (gameInfo.variant != VariantBughouse &&
4782 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4783 if (tinyLayout || smallLayout) {
4784 if(gameInfo.variant == VariantNormal)
4785 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4786 gameInfo.white, white_stren, gameInfo.black, black_stren,
4787 basetime, increment);
4789 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4790 gameInfo.white, white_stren, gameInfo.black, black_stren,
4791 basetime, increment, (int) gameInfo.variant);
4793 if(gameInfo.variant == VariantNormal)
4794 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4795 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4796 basetime, increment);
4798 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
4799 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4800 basetime, increment, VariantName(gameInfo.variant));
4803 if (appData.debugMode) {
4804 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4809 /* Display the board */
4810 if (!pausing && !appData.noGUI) {
4812 if (appData.premove)
4814 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4815 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4816 ClearPremoveHighlights();
4818 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4819 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4820 DrawPosition(j, boards[currentMove]);
4822 DisplayMove(moveNum - 1);
4823 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4824 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4825 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4826 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4830 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4832 if(bookHit) { // [HGM] book: simulate book reply
4833 static char bookMove[MSG_SIZ]; // a bit generous?
4835 programStats.nodes = programStats.depth = programStats.time =
4836 programStats.score = programStats.got_only_move = 0;
4837 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4839 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4840 strcat(bookMove, bookHit);
4841 HandleMachineMove(bookMove, &first);
4850 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4851 ics_getting_history = H_REQUESTED;
4852 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4858 AnalysisPeriodicEvent (int force)
4860 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4861 && !force) || !appData.periodicUpdates)
4864 /* Send . command to Crafty to collect stats */
4865 SendToProgram(".\n", &first);
4867 /* Don't send another until we get a response (this makes
4868 us stop sending to old Crafty's which don't understand
4869 the "." command (sending illegal cmds resets node count & time,
4870 which looks bad)) */
4871 programStats.ok_to_send = 0;
4875 ics_update_width (int new_width)
4877 ics_printf("set width %d\n", new_width);
4881 SendMoveToProgram (int moveNum, ChessProgramState *cps)
4885 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
4886 // null move in variant where engine does not understand it (for analysis purposes)
4887 SendBoard(cps, moveNum + 1); // send position after move in stead.
4890 if (cps->useUsermove) {
4891 SendToProgram("usermove ", cps);
4895 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4896 int len = space - parseList[moveNum];
4897 memcpy(buf, parseList[moveNum], len);
4899 buf[len] = NULLCHAR;
4901 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4903 SendToProgram(buf, cps);
4905 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4906 AlphaRank(moveList[moveNum], 4);
4907 SendToProgram(moveList[moveNum], cps);
4908 AlphaRank(moveList[moveNum], 4); // and back
4910 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4911 * the engine. It would be nice to have a better way to identify castle
4913 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4914 && cps->useOOCastle) {
4915 int fromX = moveList[moveNum][0] - AAA;
4916 int fromY = moveList[moveNum][1] - ONE;
4917 int toX = moveList[moveNum][2] - AAA;
4918 int toY = moveList[moveNum][3] - ONE;
4919 if((boards[moveNum][fromY][fromX] == WhiteKing
4920 && boards[moveNum][toY][toX] == WhiteRook)
4921 || (boards[moveNum][fromY][fromX] == BlackKing
4922 && boards[moveNum][toY][toX] == BlackRook)) {
4923 if(toX > fromX) SendToProgram("O-O\n", cps);
4924 else SendToProgram("O-O-O\n", cps);
4926 else SendToProgram(moveList[moveNum], cps);
4928 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
4929 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
4930 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
4931 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
4932 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4934 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
4935 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4936 SendToProgram(buf, cps);
4938 else SendToProgram(moveList[moveNum], cps);
4939 /* End of additions by Tord */
4942 /* [HGM] setting up the opening has brought engine in force mode! */
4943 /* Send 'go' if we are in a mode where machine should play. */
4944 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4945 (gameMode == TwoMachinesPlay ||
4947 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4949 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4950 SendToProgram("go\n", cps);
4951 if (appData.debugMode) {
4952 fprintf(debugFP, "(extra)\n");
4955 setboardSpoiledMachineBlack = 0;
4959 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
4961 char user_move[MSG_SIZ];
4964 if(gameInfo.variant == VariantSChess && promoChar) {
4965 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
4966 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
4967 } else suffix[0] = NULLCHAR;
4971 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4972 (int)moveType, fromX, fromY, toX, toY);
4973 DisplayError(user_move + strlen("say "), 0);
4975 case WhiteKingSideCastle:
4976 case BlackKingSideCastle:
4977 case WhiteQueenSideCastleWild:
4978 case BlackQueenSideCastleWild:
4980 case WhiteHSideCastleFR:
4981 case BlackHSideCastleFR:
4983 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
4985 case WhiteQueenSideCastle:
4986 case BlackQueenSideCastle:
4987 case WhiteKingSideCastleWild:
4988 case BlackKingSideCastleWild:
4990 case WhiteASideCastleFR:
4991 case BlackASideCastleFR:
4993 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
4995 case WhiteNonPromotion:
4996 case BlackNonPromotion:
4997 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4999 case WhitePromotion:
5000 case BlackPromotion:
5001 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5002 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5003 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5004 PieceToChar(WhiteFerz));
5005 else if(gameInfo.variant == VariantGreat)
5006 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5007 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5008 PieceToChar(WhiteMan));
5010 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5011 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5017 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5018 ToUpper(PieceToChar((ChessSquare) fromX)),
5019 AAA + toX, ONE + toY);
5021 case IllegalMove: /* could be a variant we don't quite understand */
5022 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5024 case WhiteCapturesEnPassant:
5025 case BlackCapturesEnPassant:
5026 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5027 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5030 SendToICS(user_move);
5031 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5032 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5037 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5038 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5039 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5040 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5041 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5044 if(gameMode != IcsExamining) { // is this ever not the case?
5045 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5047 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5048 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5049 } else { // on FICS we must first go to general examine mode
5050 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5052 if(gameInfo.variant != VariantNormal) {
5053 // try figure out wild number, as xboard names are not always valid on ICS
5054 for(i=1; i<=36; i++) {
5055 snprintf(buf, MSG_SIZ, "wild/%d", i);
5056 if(StringToVariant(buf) == gameInfo.variant) break;
5058 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5059 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5060 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5061 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5062 SendToICS(ics_prefix);
5064 if(startedFromSetupPosition || backwardMostMove != 0) {
5065 fen = PositionToFEN(backwardMostMove, NULL);
5066 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5067 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5069 } else { // FICS: everything has to set by separate bsetup commands
5070 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5071 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5073 if(!WhiteOnMove(backwardMostMove)) {
5074 SendToICS("bsetup tomove black\n");
5076 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5077 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5079 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5080 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5082 i = boards[backwardMostMove][EP_STATUS];
5083 if(i >= 0) { // set e.p.
5084 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5090 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5091 SendToICS("bsetup done\n"); // switch to normal examining.
5093 for(i = backwardMostMove; i<last; i++) {
5095 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5098 SendToICS(ics_prefix);
5099 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5103 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5105 if (rf == DROP_RANK) {
5106 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5107 sprintf(move, "%c@%c%c\n",
5108 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5110 if (promoChar == 'x' || promoChar == NULLCHAR) {
5111 sprintf(move, "%c%c%c%c\n",
5112 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5114 sprintf(move, "%c%c%c%c%c\n",
5115 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5121 ProcessICSInitScript (FILE *f)
5125 while (fgets(buf, MSG_SIZ, f)) {
5126 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5133 static int lastX, lastY, selectFlag, dragging;
5138 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5139 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5140 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5141 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5142 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5143 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
5146 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5147 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5148 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5149 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5150 if(!step) step = -1;
5151 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5152 appData.testLegality && (promoSweep == king ||
5153 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
5154 ChangeDragPiece(promoSweep);
5158 PromoScroll (int x, int y)
5162 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5163 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5164 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5165 if(!step) return FALSE;
5166 lastX = x; lastY = y;
5167 if((promoSweep < BlackPawn) == flipView) step = -step;
5168 if(step > 0) selectFlag = 1;
5169 if(!selectFlag) Sweep(step);
5174 NextPiece (int step)
5176 ChessSquare piece = boards[currentMove][toY][toX];
5179 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5180 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5181 if(!step) step = -1;
5182 } while(PieceToChar(pieceSweep) == '.');
5183 boards[currentMove][toY][toX] = pieceSweep;
5184 DrawPosition(FALSE, boards[currentMove]);
5185 boards[currentMove][toY][toX] = piece;
5187 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5189 AlphaRank (char *move, int n)
5191 // char *p = move, c; int x, y;
5193 if (appData.debugMode) {
5194 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5198 move[2]>='0' && move[2]<='9' &&
5199 move[3]>='a' && move[3]<='x' ) {
5201 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5202 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5204 if(move[0]>='0' && move[0]<='9' &&
5205 move[1]>='a' && move[1]<='x' &&
5206 move[2]>='0' && move[2]<='9' &&
5207 move[3]>='a' && move[3]<='x' ) {
5208 /* input move, Shogi -> normal */
5209 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5210 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5211 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5212 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5215 move[3]>='0' && move[3]<='9' &&
5216 move[2]>='a' && move[2]<='x' ) {
5218 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5219 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5222 move[0]>='a' && move[0]<='x' &&
5223 move[3]>='0' && move[3]<='9' &&
5224 move[2]>='a' && move[2]<='x' ) {
5225 /* output move, normal -> Shogi */
5226 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5227 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5228 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5229 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5230 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5232 if (appData.debugMode) {
5233 fprintf(debugFP, " out = '%s'\n", move);
5237 char yy_textstr[8000];
5239 /* Parser for moves from gnuchess, ICS, or user typein box */
5241 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5243 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5245 switch (*moveType) {
5246 case WhitePromotion:
5247 case BlackPromotion:
5248 case WhiteNonPromotion:
5249 case BlackNonPromotion:
5251 case WhiteCapturesEnPassant:
5252 case BlackCapturesEnPassant:
5253 case WhiteKingSideCastle:
5254 case WhiteQueenSideCastle:
5255 case BlackKingSideCastle:
5256 case BlackQueenSideCastle:
5257 case WhiteKingSideCastleWild:
5258 case WhiteQueenSideCastleWild:
5259 case BlackKingSideCastleWild:
5260 case BlackQueenSideCastleWild:
5261 /* Code added by Tord: */
5262 case WhiteHSideCastleFR:
5263 case WhiteASideCastleFR:
5264 case BlackHSideCastleFR:
5265 case BlackASideCastleFR:
5266 /* End of code added by Tord */
5267 case IllegalMove: /* bug or odd chess variant */
5268 *fromX = currentMoveString[0] - AAA;
5269 *fromY = currentMoveString[1] - ONE;
5270 *toX = currentMoveString[2] - AAA;
5271 *toY = currentMoveString[3] - ONE;
5272 *promoChar = currentMoveString[4];
5273 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5274 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5275 if (appData.debugMode) {
5276 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5278 *fromX = *fromY = *toX = *toY = 0;
5281 if (appData.testLegality) {
5282 return (*moveType != IllegalMove);
5284 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5285 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5290 *fromX = *moveType == WhiteDrop ?
5291 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5292 (int) CharToPiece(ToLower(currentMoveString[0]));
5294 *toX = currentMoveString[2] - AAA;
5295 *toY = currentMoveString[3] - ONE;
5296 *promoChar = NULLCHAR;
5300 case ImpossibleMove:
5310 if (appData.debugMode) {
5311 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5314 *fromX = *fromY = *toX = *toY = 0;
5315 *promoChar = NULLCHAR;
5320 Boolean pushed = FALSE;
5321 char *lastParseAttempt;
5324 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5325 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5326 int fromX, fromY, toX, toY; char promoChar;
5331 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
5332 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5335 endPV = forwardMostMove;
5337 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5338 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5339 lastParseAttempt = pv;
5340 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5341 if(!valid && nr == 0 &&
5342 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5343 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5344 // Hande case where played move is different from leading PV move
5345 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5346 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5347 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5348 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5349 endPV += 2; // if position different, keep this
5350 moveList[endPV-1][0] = fromX + AAA;
5351 moveList[endPV-1][1] = fromY + ONE;
5352 moveList[endPV-1][2] = toX + AAA;
5353 moveList[endPV-1][3] = toY + ONE;
5354 parseList[endPV-1][0] = NULLCHAR;
5355 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5358 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5359 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5360 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5361 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5362 valid++; // allow comments in PV
5366 if(endPV+1 > framePtr) break; // no space, truncate
5369 CopyBoard(boards[endPV], boards[endPV-1]);
5370 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5371 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5372 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5373 CoordsToAlgebraic(boards[endPV - 1],
5374 PosFlags(endPV - 1),
5375 fromY, fromX, toY, toX, promoChar,
5376 parseList[endPV - 1]);
5378 if(atEnd == 2) return; // used hidden, for PV conversion
5379 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5380 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5381 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5382 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5383 DrawPosition(TRUE, boards[currentMove]);
5387 MultiPV (ChessProgramState *cps)
5388 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5390 for(i=0; i<cps->nrOptions; i++)
5391 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5397 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end)
5399 int startPV, multi, lineStart, origIndex = index;
5400 char *p, buf2[MSG_SIZ];
5402 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5403 lastX = x; lastY = y;
5404 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5405 lineStart = startPV = index;
5406 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5407 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5409 do{ while(buf[index] && buf[index] != '\n') index++;
5410 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5412 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(&first)) >= 0) {
5413 int n = first.option[multi].value;
5414 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5415 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5416 if(first.option[multi].value != n) SendToProgram(buf2, &first);
5417 first.option[multi].value = n;
5421 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5422 *start = startPV; *end = index-1;
5429 static char buf[10*MSG_SIZ];
5430 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5432 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV);
5433 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5434 for(i = forwardMostMove; i<endPV; i++){
5435 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5436 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5439 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5440 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5446 LoadPV (int x, int y)
5447 { // called on right mouse click to load PV
5448 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5449 lastX = x; lastY = y;
5450 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5457 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5458 if(endPV < 0) return;
5459 if(appData.autoCopyPV) CopyFENToClipboard();
5461 if(gameMode == AnalyzeMode && currentMove > forwardMostMove) {
5462 Boolean saveAnimate = appData.animate;
5464 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5465 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5466 } else storedGames--; // abandon shelved tail of original game
5469 forwardMostMove = currentMove;
5470 currentMove = oldFMM;
5471 appData.animate = FALSE;
5472 ToNrEvent(forwardMostMove);
5473 appData.animate = saveAnimate;
5475 currentMove = forwardMostMove;
5476 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5477 ClearPremoveHighlights();
5478 DrawPosition(TRUE, boards[currentMove]);
5482 MovePV (int x, int y, int h)
5483 { // step through PV based on mouse coordinates (called on mouse move)
5484 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5486 // we must somehow check if right button is still down (might be released off board!)
5487 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5488 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5489 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5491 lastX = x; lastY = y;
5493 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5494 if(endPV < 0) return;
5495 if(y < margin) step = 1; else
5496 if(y > h - margin) step = -1;
5497 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5498 currentMove += step;
5499 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5500 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5501 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5502 DrawPosition(FALSE, boards[currentMove]);
5506 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5507 // All positions will have equal probability, but the current method will not provide a unique
5508 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5514 int piecesLeft[(int)BlackPawn];
5515 int seed, nrOfShuffles;
5518 GetPositionNumber ()
5519 { // sets global variable seed
5522 seed = appData.defaultFrcPosition;
5523 if(seed < 0) { // randomize based on time for negative FRC position numbers
5524 for(i=0; i<50; i++) seed += random();
5525 seed = random() ^ random() >> 8 ^ random() << 8;
5526 if(seed<0) seed = -seed;
5531 put (Board board, int pieceType, int rank, int n, int shade)
5532 // put the piece on the (n-1)-th empty squares of the given shade
5536 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5537 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5538 board[rank][i] = (ChessSquare) pieceType;
5539 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5541 piecesLeft[pieceType]--;
5550 AddOnePiece (Board board, int pieceType, int rank, int shade)
5551 // calculate where the next piece goes, (any empty square), and put it there
5555 i = seed % squaresLeft[shade];
5556 nrOfShuffles *= squaresLeft[shade];
5557 seed /= squaresLeft[shade];
5558 put(board, pieceType, rank, i, shade);
5562 AddTwoPieces (Board board, int pieceType, int rank)
5563 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5565 int i, n=squaresLeft[ANY], j=n-1, k;
5567 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5568 i = seed % k; // pick one
5571 while(i >= j) i -= j--;
5572 j = n - 1 - j; i += j;
5573 put(board, pieceType, rank, j, ANY);
5574 put(board, pieceType, rank, i, ANY);
5578 SetUpShuffle (Board board, int number)
5582 GetPositionNumber(); nrOfShuffles = 1;
5584 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5585 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5586 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5588 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5590 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5591 p = (int) board[0][i];
5592 if(p < (int) BlackPawn) piecesLeft[p] ++;
5593 board[0][i] = EmptySquare;
5596 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5597 // shuffles restricted to allow normal castling put KRR first
5598 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5599 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5600 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5601 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5602 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5603 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5604 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5605 put(board, WhiteRook, 0, 0, ANY);
5606 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5609 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5610 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5611 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5612 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5613 while(piecesLeft[p] >= 2) {
5614 AddOnePiece(board, p, 0, LITE);
5615 AddOnePiece(board, p, 0, DARK);
5617 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5620 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5621 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5622 // but we leave King and Rooks for last, to possibly obey FRC restriction
5623 if(p == (int)WhiteRook) continue;
5624 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5625 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5628 // now everything is placed, except perhaps King (Unicorn) and Rooks
5630 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5631 // Last King gets castling rights
5632 while(piecesLeft[(int)WhiteUnicorn]) {
5633 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5634 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5637 while(piecesLeft[(int)WhiteKing]) {
5638 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5639 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5644 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5645 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5648 // Only Rooks can be left; simply place them all
5649 while(piecesLeft[(int)WhiteRook]) {
5650 i = put(board, WhiteRook, 0, 0, ANY);
5651 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5654 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5656 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5659 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5660 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5663 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5667 SetCharTable (char *table, const char * map)
5668 /* [HGM] moved here from winboard.c because of its general usefulness */
5669 /* Basically a safe strcpy that uses the last character as King */
5671 int result = FALSE; int NrPieces;
5673 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5674 && NrPieces >= 12 && !(NrPieces&1)) {
5675 int i; /* [HGM] Accept even length from 12 to 34 */
5677 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5678 for( i=0; i<NrPieces/2-1; i++ ) {
5680 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5682 table[(int) WhiteKing] = map[NrPieces/2-1];
5683 table[(int) BlackKing] = map[NrPieces-1];
5692 Prelude (Board board)
5693 { // [HGM] superchess: random selection of exo-pieces
5694 int i, j, k; ChessSquare p;
5695 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5697 GetPositionNumber(); // use FRC position number
5699 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5700 SetCharTable(pieceToChar, appData.pieceToCharTable);
5701 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5702 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5705 j = seed%4; seed /= 4;
5706 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5707 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5708 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5709 j = seed%3 + (seed%3 >= j); seed /= 3;
5710 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5711 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5712 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5713 j = seed%3; seed /= 3;
5714 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5715 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5716 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5717 j = seed%2 + (seed%2 >= j); seed /= 2;
5718 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5719 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5720 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5721 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5722 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5723 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5724 put(board, exoPieces[0], 0, 0, ANY);
5725 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5729 InitPosition (int redraw)
5731 ChessSquare (* pieces)[BOARD_FILES];
5732 int i, j, pawnRow, overrule,
5733 oldx = gameInfo.boardWidth,
5734 oldy = gameInfo.boardHeight,
5735 oldh = gameInfo.holdingsWidth;
5738 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5740 /* [AS] Initialize pv info list [HGM] and game status */
5742 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5743 pvInfoList[i].depth = 0;
5744 boards[i][EP_STATUS] = EP_NONE;
5745 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5748 initialRulePlies = 0; /* 50-move counter start */
5750 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5751 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5755 /* [HGM] logic here is completely changed. In stead of full positions */
5756 /* the initialized data only consist of the two backranks. The switch */
5757 /* selects which one we will use, which is than copied to the Board */
5758 /* initialPosition, which for the rest is initialized by Pawns and */
5759 /* empty squares. This initial position is then copied to boards[0], */
5760 /* possibly after shuffling, so that it remains available. */
5762 gameInfo.holdingsWidth = 0; /* default board sizes */
5763 gameInfo.boardWidth = 8;
5764 gameInfo.boardHeight = 8;
5765 gameInfo.holdingsSize = 0;
5766 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5767 for(i=0; i<BOARD_FILES-2; i++)
5768 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5769 initialPosition[EP_STATUS] = EP_NONE;
5770 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5771 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5772 SetCharTable(pieceNickName, appData.pieceNickNames);
5773 else SetCharTable(pieceNickName, "............");
5776 switch (gameInfo.variant) {
5777 case VariantFischeRandom:
5778 shuffleOpenings = TRUE;
5781 case VariantShatranj:
5782 pieces = ShatranjArray;
5783 nrCastlingRights = 0;
5784 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5787 pieces = makrukArray;
5788 nrCastlingRights = 0;
5789 startedFromSetupPosition = TRUE;
5790 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5792 case VariantTwoKings:
5793 pieces = twoKingsArray;
5796 pieces = GrandArray;
5797 nrCastlingRights = 0;
5798 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5799 gameInfo.boardWidth = 10;
5800 gameInfo.boardHeight = 10;
5801 gameInfo.holdingsSize = 7;
5803 case VariantCapaRandom:
5804 shuffleOpenings = TRUE;
5805 case VariantCapablanca:
5806 pieces = CapablancaArray;
5807 gameInfo.boardWidth = 10;
5808 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5811 pieces = GothicArray;
5812 gameInfo.boardWidth = 10;
5813 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5816 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5817 gameInfo.holdingsSize = 7;
5820 pieces = JanusArray;
5821 gameInfo.boardWidth = 10;
5822 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5823 nrCastlingRights = 6;
5824 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5825 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5826 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5827 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5828 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5829 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5832 pieces = FalconArray;
5833 gameInfo.boardWidth = 10;
5834 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5836 case VariantXiangqi:
5837 pieces = XiangqiArray;
5838 gameInfo.boardWidth = 9;
5839 gameInfo.boardHeight = 10;
5840 nrCastlingRights = 0;
5841 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5844 pieces = ShogiArray;
5845 gameInfo.boardWidth = 9;
5846 gameInfo.boardHeight = 9;
5847 gameInfo.holdingsSize = 7;
5848 nrCastlingRights = 0;
5849 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5851 case VariantCourier:
5852 pieces = CourierArray;
5853 gameInfo.boardWidth = 12;
5854 nrCastlingRights = 0;
5855 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5857 case VariantKnightmate:
5858 pieces = KnightmateArray;
5859 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5861 case VariantSpartan:
5862 pieces = SpartanArray;
5863 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5866 pieces = fairyArray;
5867 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5870 pieces = GreatArray;
5871 gameInfo.boardWidth = 10;
5872 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5873 gameInfo.holdingsSize = 8;
5877 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5878 gameInfo.holdingsSize = 8;
5879 startedFromSetupPosition = TRUE;
5881 case VariantCrazyhouse:
5882 case VariantBughouse:
5884 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5885 gameInfo.holdingsSize = 5;
5887 case VariantWildCastle:
5889 /* !!?shuffle with kings guaranteed to be on d or e file */
5890 shuffleOpenings = 1;
5892 case VariantNoCastle:
5894 nrCastlingRights = 0;
5895 /* !!?unconstrained back-rank shuffle */
5896 shuffleOpenings = 1;
5901 if(appData.NrFiles >= 0) {
5902 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5903 gameInfo.boardWidth = appData.NrFiles;
5905 if(appData.NrRanks >= 0) {
5906 gameInfo.boardHeight = appData.NrRanks;
5908 if(appData.holdingsSize >= 0) {
5909 i = appData.holdingsSize;
5910 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5911 gameInfo.holdingsSize = i;
5913 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5914 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5915 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5917 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5918 if(pawnRow < 1) pawnRow = 1;
5919 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) pawnRow = 2;
5921 /* User pieceToChar list overrules defaults */
5922 if(appData.pieceToCharTable != NULL)
5923 SetCharTable(pieceToChar, appData.pieceToCharTable);
5925 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5927 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5928 s = (ChessSquare) 0; /* account holding counts in guard band */
5929 for( i=0; i<BOARD_HEIGHT; i++ )
5930 initialPosition[i][j] = s;
5932 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5933 initialPosition[gameInfo.variant == VariantGrand][j] = pieces[0][j-gameInfo.holdingsWidth];
5934 initialPosition[pawnRow][j] = WhitePawn;
5935 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5936 if(gameInfo.variant == VariantXiangqi) {
5938 initialPosition[pawnRow][j] =
5939 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5940 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5941 initialPosition[2][j] = WhiteCannon;
5942 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5946 if(gameInfo.variant == VariantGrand) {
5947 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
5948 initialPosition[0][j] = WhiteRook;
5949 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
5952 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand)][j] = pieces[1][j-gameInfo.holdingsWidth];
5954 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5957 initialPosition[1][j] = WhiteBishop;
5958 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5960 initialPosition[1][j] = WhiteRook;
5961 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5964 if( nrCastlingRights == -1) {
5965 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5966 /* This sets default castling rights from none to normal corners */
5967 /* Variants with other castling rights must set them themselves above */
5968 nrCastlingRights = 6;
5970 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5971 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5972 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5973 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5974 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5975 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5978 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5979 if(gameInfo.variant == VariantGreat) { // promotion commoners
5980 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5981 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5982 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5983 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5985 if( gameInfo.variant == VariantSChess ) {
5986 initialPosition[1][0] = BlackMarshall;
5987 initialPosition[2][0] = BlackAngel;
5988 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5989 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5990 initialPosition[1][1] = initialPosition[2][1] =
5991 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5993 if (appData.debugMode) {
5994 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5996 if(shuffleOpenings) {
5997 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5998 startedFromSetupPosition = TRUE;
6000 if(startedFromPositionFile) {
6001 /* [HGM] loadPos: use PositionFile for every new game */
6002 CopyBoard(initialPosition, filePosition);
6003 for(i=0; i<nrCastlingRights; i++)
6004 initialRights[i] = filePosition[CASTLING][i];
6005 startedFromSetupPosition = TRUE;
6008 CopyBoard(boards[0], initialPosition);
6010 if(oldx != gameInfo.boardWidth ||
6011 oldy != gameInfo.boardHeight ||
6012 oldv != gameInfo.variant ||
6013 oldh != gameInfo.holdingsWidth
6015 InitDrawingSizes(-2 ,0);
6017 oldv = gameInfo.variant;
6019 DrawPosition(TRUE, boards[currentMove]);
6023 SendBoard (ChessProgramState *cps, int moveNum)
6025 char message[MSG_SIZ];
6027 if (cps->useSetboard) {
6028 char* fen = PositionToFEN(moveNum, cps->fenOverride);
6029 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6030 SendToProgram(message, cps);
6035 int i, j, left=0, right=BOARD_WIDTH;
6036 /* Kludge to set black to move, avoiding the troublesome and now
6037 * deprecated "black" command.
6039 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6040 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6042 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6044 SendToProgram("edit\n", cps);
6045 SendToProgram("#\n", cps);
6046 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6047 bp = &boards[moveNum][i][left];
6048 for (j = left; j < right; j++, bp++) {
6049 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6050 if ((int) *bp < (int) BlackPawn) {
6051 if(j == BOARD_RGHT+1)
6052 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6053 else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6054 if(message[0] == '+' || message[0] == '~') {
6055 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6056 PieceToChar((ChessSquare)(DEMOTED *bp)),
6059 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6060 message[1] = BOARD_RGHT - 1 - j + '1';
6061 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6063 SendToProgram(message, cps);
6068 SendToProgram("c\n", cps);
6069 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6070 bp = &boards[moveNum][i][left];
6071 for (j = left; j < right; j++, bp++) {
6072 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6073 if (((int) *bp != (int) EmptySquare)
6074 && ((int) *bp >= (int) BlackPawn)) {
6075 if(j == BOARD_LEFT-2)
6076 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6077 else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6079 if(message[0] == '+' || message[0] == '~') {
6080 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6081 PieceToChar((ChessSquare)(DEMOTED *bp)),
6084 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6085 message[1] = BOARD_RGHT - 1 - j + '1';
6086 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6088 SendToProgram(message, cps);
6093 SendToProgram(".\n", cps);
6095 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6099 DefaultPromoChoice (int white)
6102 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
6103 result = WhiteFerz; // no choice
6104 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6105 result= WhiteKing; // in Suicide Q is the last thing we want
6106 else if(gameInfo.variant == VariantSpartan)
6107 result = white ? WhiteQueen : WhiteAngel;
6108 else result = WhiteQueen;
6109 if(!white) result = WHITE_TO_BLACK result;
6113 static int autoQueen; // [HGM] oneclick
6116 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6118 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6119 /* [HGM] add Shogi promotions */
6120 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6125 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6126 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6128 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6129 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6132 piece = boards[currentMove][fromY][fromX];
6133 if(gameInfo.variant == VariantShogi) {
6134 promotionZoneSize = BOARD_HEIGHT/3;
6135 highestPromotingPiece = (int)WhiteFerz;
6136 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) {
6137 promotionZoneSize = 3;
6140 // Treat Lance as Pawn when it is not representing Amazon
6141 if(gameInfo.variant != VariantSuper) {
6142 if(piece == WhiteLance) piece = WhitePawn; else
6143 if(piece == BlackLance) piece = BlackPawn;
6146 // next weed out all moves that do not touch the promotion zone at all
6147 if((int)piece >= BlackPawn) {
6148 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6150 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6152 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6153 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6156 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6158 // weed out mandatory Shogi promotions
6159 if(gameInfo.variant == VariantShogi) {
6160 if(piece >= BlackPawn) {
6161 if(toY == 0 && piece == BlackPawn ||
6162 toY == 0 && piece == BlackQueen ||
6163 toY <= 1 && piece == BlackKnight) {
6168 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6169 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6170 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6177 // weed out obviously illegal Pawn moves
6178 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6179 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6180 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6181 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6182 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6183 // note we are not allowed to test for valid (non-)capture, due to premove
6186 // we either have a choice what to promote to, or (in Shogi) whether to promote
6187 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
6188 *promoChoice = PieceToChar(BlackFerz); // no choice
6191 // no sense asking what we must promote to if it is going to explode...
6192 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6193 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6196 // give caller the default choice even if we will not make it
6197 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6198 if(gameInfo.variant == VariantShogi) *promoChoice = (defaultPromoChoice == piece ? '=' : '+');
6199 if( sweepSelect && gameInfo.variant != VariantGreat
6200 && gameInfo.variant != VariantGrand
6201 && gameInfo.variant != VariantSuper) return FALSE;
6202 if(autoQueen) return FALSE; // predetermined
6204 // suppress promotion popup on illegal moves that are not premoves
6205 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6206 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6207 if(appData.testLegality && !premove) {
6208 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6209 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
6210 if(moveType != WhitePromotion && moveType != BlackPromotion)
6218 InPalace (int row, int column)
6219 { /* [HGM] for Xiangqi */
6220 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6221 column < (BOARD_WIDTH + 4)/2 &&
6222 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6227 PieceForSquare (int x, int y)
6229 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6232 return boards[currentMove][y][x];
6236 OKToStartUserMove (int x, int y)
6238 ChessSquare from_piece;
6241 if (matchMode) return FALSE;
6242 if (gameMode == EditPosition) return TRUE;
6244 if (x >= 0 && y >= 0)
6245 from_piece = boards[currentMove][y][x];
6247 from_piece = EmptySquare;
6249 if (from_piece == EmptySquare) return FALSE;
6251 white_piece = (int)from_piece >= (int)WhitePawn &&
6252 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6256 case TwoMachinesPlay:
6264 case MachinePlaysWhite:
6265 case IcsPlayingBlack:
6266 if (appData.zippyPlay) return FALSE;
6268 DisplayMoveError(_("You are playing Black"));
6273 case MachinePlaysBlack:
6274 case IcsPlayingWhite:
6275 if (appData.zippyPlay) return FALSE;
6277 DisplayMoveError(_("You are playing White"));
6282 case PlayFromGameFile:
6283 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6285 if (!white_piece && WhiteOnMove(currentMove)) {
6286 DisplayMoveError(_("It is White's turn"));
6289 if (white_piece && !WhiteOnMove(currentMove)) {
6290 DisplayMoveError(_("It is Black's turn"));
6293 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6294 /* Editing correspondence game history */
6295 /* Could disallow this or prompt for confirmation */
6300 case BeginningOfGame:
6301 if (appData.icsActive) return FALSE;
6302 if (!appData.noChessProgram) {
6304 DisplayMoveError(_("You are playing White"));
6311 if (!white_piece && WhiteOnMove(currentMove)) {
6312 DisplayMoveError(_("It is White's turn"));
6315 if (white_piece && !WhiteOnMove(currentMove)) {
6316 DisplayMoveError(_("It is Black's turn"));
6325 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6326 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6327 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6328 && gameMode != AnalyzeFile && gameMode != Training) {
6329 DisplayMoveError(_("Displayed position is not current"));
6336 OnlyMove (int *x, int *y, Boolean captures)
6338 DisambiguateClosure cl;
6339 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6341 case MachinePlaysBlack:
6342 case IcsPlayingWhite:
6343 case BeginningOfGame:
6344 if(!WhiteOnMove(currentMove)) return FALSE;
6346 case MachinePlaysWhite:
6347 case IcsPlayingBlack:
6348 if(WhiteOnMove(currentMove)) return FALSE;
6355 cl.pieceIn = EmptySquare;
6360 cl.promoCharIn = NULLCHAR;
6361 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6362 if( cl.kind == NormalMove ||
6363 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6364 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6365 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6372 if(cl.kind != ImpossibleMove) return FALSE;
6373 cl.pieceIn = EmptySquare;
6378 cl.promoCharIn = NULLCHAR;
6379 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6380 if( cl.kind == NormalMove ||
6381 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6382 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6383 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6388 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6394 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6395 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6396 int lastLoadGameUseList = FALSE;
6397 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6398 ChessMove lastLoadGameStart = EndOfFile;
6401 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6404 ChessSquare pdown, pup;
6406 /* Check if the user is playing in turn. This is complicated because we
6407 let the user "pick up" a piece before it is his turn. So the piece he
6408 tried to pick up may have been captured by the time he puts it down!
6409 Therefore we use the color the user is supposed to be playing in this
6410 test, not the color of the piece that is currently on the starting
6411 square---except in EditGame mode, where the user is playing both
6412 sides; fortunately there the capture race can't happen. (It can
6413 now happen in IcsExamining mode, but that's just too bad. The user
6414 will get a somewhat confusing message in that case.)
6419 case TwoMachinesPlay:
6423 /* We switched into a game mode where moves are not accepted,
6424 perhaps while the mouse button was down. */
6427 case MachinePlaysWhite:
6428 /* User is moving for Black */
6429 if (WhiteOnMove(currentMove)) {
6430 DisplayMoveError(_("It is White's turn"));
6435 case MachinePlaysBlack:
6436 /* User is moving for White */
6437 if (!WhiteOnMove(currentMove)) {
6438 DisplayMoveError(_("It is Black's turn"));
6443 case PlayFromGameFile:
6444 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6447 case BeginningOfGame:
6450 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6451 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6452 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6453 /* User is moving for Black */
6454 if (WhiteOnMove(currentMove)) {
6455 DisplayMoveError(_("It is White's turn"));
6459 /* User is moving for White */
6460 if (!WhiteOnMove(currentMove)) {
6461 DisplayMoveError(_("It is Black's turn"));
6467 case IcsPlayingBlack:
6468 /* User is moving for Black */
6469 if (WhiteOnMove(currentMove)) {
6470 if (!appData.premove) {
6471 DisplayMoveError(_("It is White's turn"));
6472 } else if (toX >= 0 && toY >= 0) {
6475 premoveFromX = fromX;
6476 premoveFromY = fromY;
6477 premovePromoChar = promoChar;
6479 if (appData.debugMode)
6480 fprintf(debugFP, "Got premove: fromX %d,"
6481 "fromY %d, toX %d, toY %d\n",
6482 fromX, fromY, toX, toY);
6488 case IcsPlayingWhite:
6489 /* User is moving for White */
6490 if (!WhiteOnMove(currentMove)) {
6491 if (!appData.premove) {
6492 DisplayMoveError(_("It is Black's turn"));
6493 } else if (toX >= 0 && toY >= 0) {
6496 premoveFromX = fromX;
6497 premoveFromY = fromY;
6498 premovePromoChar = promoChar;
6500 if (appData.debugMode)
6501 fprintf(debugFP, "Got premove: fromX %d,"
6502 "fromY %d, toX %d, toY %d\n",
6503 fromX, fromY, toX, toY);
6513 /* EditPosition, empty square, or different color piece;
6514 click-click move is possible */
6515 if (toX == -2 || toY == -2) {
6516 boards[0][fromY][fromX] = EmptySquare;
6517 DrawPosition(FALSE, boards[currentMove]);
6519 } else if (toX >= 0 && toY >= 0) {
6520 boards[0][toY][toX] = boards[0][fromY][fromX];
6521 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6522 if(boards[0][fromY][0] != EmptySquare) {
6523 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6524 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6527 if(fromX == BOARD_RGHT+1) {
6528 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6529 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6530 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6533 boards[0][fromY][fromX] = EmptySquare;
6534 DrawPosition(FALSE, boards[currentMove]);
6540 if(toX < 0 || toY < 0) return;
6541 pdown = boards[currentMove][fromY][fromX];
6542 pup = boards[currentMove][toY][toX];
6544 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6545 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6546 if( pup != EmptySquare ) return;
6547 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6548 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6549 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6550 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6551 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6552 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6553 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6557 /* [HGM] always test for legality, to get promotion info */
6558 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6559 fromY, fromX, toY, toX, promoChar);
6561 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame)) moveType = NormalMove;
6563 /* [HGM] but possibly ignore an IllegalMove result */
6564 if (appData.testLegality) {
6565 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6566 DisplayMoveError(_("Illegal move"));
6571 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6574 /* Common tail of UserMoveEvent and DropMenuEvent */
6576 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
6580 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
6581 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
6582 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6583 if(WhiteOnMove(currentMove)) {
6584 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6586 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6590 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6591 move type in caller when we know the move is a legal promotion */
6592 if(moveType == NormalMove && promoChar)
6593 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6595 /* [HGM] <popupFix> The following if has been moved here from
6596 UserMoveEvent(). Because it seemed to belong here (why not allow
6597 piece drops in training games?), and because it can only be
6598 performed after it is known to what we promote. */
6599 if (gameMode == Training) {
6600 /* compare the move played on the board to the next move in the
6601 * game. If they match, display the move and the opponent's response.
6602 * If they don't match, display an error message.
6606 CopyBoard(testBoard, boards[currentMove]);
6607 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6609 if (CompareBoards(testBoard, boards[currentMove+1])) {
6610 ForwardInner(currentMove+1);
6612 /* Autoplay the opponent's response.
6613 * if appData.animate was TRUE when Training mode was entered,
6614 * the response will be animated.
6616 saveAnimate = appData.animate;
6617 appData.animate = animateTraining;
6618 ForwardInner(currentMove+1);
6619 appData.animate = saveAnimate;
6621 /* check for the end of the game */
6622 if (currentMove >= forwardMostMove) {
6623 gameMode = PlayFromGameFile;
6625 SetTrainingModeOff();
6626 DisplayInformation(_("End of game"));
6629 DisplayError(_("Incorrect move"), 0);
6634 /* Ok, now we know that the move is good, so we can kill
6635 the previous line in Analysis Mode */
6636 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
6637 && currentMove < forwardMostMove) {
6638 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6639 else forwardMostMove = currentMove;
6642 /* If we need the chess program but it's dead, restart it */
6643 ResurrectChessProgram();
6645 /* A user move restarts a paused game*/
6649 thinkOutput[0] = NULLCHAR;
6651 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6653 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6654 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6658 if (gameMode == BeginningOfGame) {
6659 if (appData.noChessProgram) {
6660 gameMode = EditGame;
6664 gameMode = MachinePlaysBlack;
6667 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
6669 if (first.sendName) {
6670 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6671 SendToProgram(buf, &first);
6678 /* Relay move to ICS or chess engine */
6679 if (appData.icsActive) {
6680 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6681 gameMode == IcsExamining) {
6682 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6683 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6685 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6687 // also send plain move, in case ICS does not understand atomic claims
6688 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6692 if (first.sendTime && (gameMode == BeginningOfGame ||
6693 gameMode == MachinePlaysWhite ||
6694 gameMode == MachinePlaysBlack)) {
6695 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6697 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6698 // [HGM] book: if program might be playing, let it use book
6699 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6700 first.maybeThinking = TRUE;
6701 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
6702 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
6703 SendBoard(&first, currentMove+1);
6704 } else SendMoveToProgram(forwardMostMove-1, &first);
6705 if (currentMove == cmailOldMove + 1) {
6706 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6710 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6714 if(appData.testLegality)
6715 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6721 if (WhiteOnMove(currentMove)) {
6722 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6724 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6728 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6733 case MachinePlaysBlack:
6734 case MachinePlaysWhite:
6735 /* disable certain menu options while machine is thinking */
6736 SetMachineThinkingEnables();
6743 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6744 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6746 if(bookHit) { // [HGM] book: simulate book reply
6747 static char bookMove[MSG_SIZ]; // a bit generous?
6749 programStats.nodes = programStats.depth = programStats.time =
6750 programStats.score = programStats.got_only_move = 0;
6751 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6753 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6754 strcat(bookMove, bookHit);
6755 HandleMachineMove(bookMove, &first);
6761 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
6763 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6764 Markers *m = (Markers *) closure;
6765 if(rf == fromY && ff == fromX)
6766 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6767 || kind == WhiteCapturesEnPassant
6768 || kind == BlackCapturesEnPassant);
6769 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6773 MarkTargetSquares (int clear)
6776 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
6777 !appData.testLegality || gameMode == EditPosition) return;
6779 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6782 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
6783 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6784 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6786 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6789 DrawPosition(TRUE, NULL);
6793 Explode (Board board, int fromX, int fromY, int toX, int toY)
6795 if(gameInfo.variant == VariantAtomic &&
6796 (board[toY][toX] != EmptySquare || // capture?
6797 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6798 board[fromY][fromX] == BlackPawn )
6800 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6806 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6809 CanPromote (ChessSquare piece, int y)
6811 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6812 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6813 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6814 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6815 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6816 gameInfo.variant == VariantMakruk) return FALSE;
6817 return (piece == BlackPawn && y == 1 ||
6818 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6819 piece == BlackLance && y == 1 ||
6820 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6824 LeftClick (ClickType clickType, int xPix, int yPix)
6827 Boolean saveAnimate;
6828 static int second = 0, promotionChoice = 0, clearFlag = 0;
6829 char promoChoice = NULLCHAR;
6832 if(appData.seekGraph && appData.icsActive && loggedOn &&
6833 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6834 SeekGraphClick(clickType, xPix, yPix, 0);
6838 if (clickType == Press) ErrorPopDown();
6840 x = EventToSquare(xPix, BOARD_WIDTH);
6841 y = EventToSquare(yPix, BOARD_HEIGHT);
6842 if (!flipView && y >= 0) {
6843 y = BOARD_HEIGHT - 1 - y;
6845 if (flipView && x >= 0) {
6846 x = BOARD_WIDTH - 1 - x;
6849 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6850 defaultPromoChoice = promoSweep;
6851 promoSweep = EmptySquare; // terminate sweep
6852 promoDefaultAltered = TRUE;
6853 if(!selectFlag && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6856 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6857 if(clickType == Release) return; // ignore upclick of click-click destination
6858 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6859 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6860 if(gameInfo.holdingsWidth &&
6861 (WhiteOnMove(currentMove)
6862 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
6863 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
6864 // click in right holdings, for determining promotion piece
6865 ChessSquare p = boards[currentMove][y][x];
6866 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6867 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
6868 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
6869 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
6874 DrawPosition(FALSE, boards[currentMove]);
6878 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6879 if(clickType == Press
6880 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6881 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6882 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6885 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6886 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6888 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6889 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6890 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6891 defaultPromoChoice = DefaultPromoChoice(side);
6894 autoQueen = appData.alwaysPromoteToQueen;
6898 gatingPiece = EmptySquare;
6899 if (clickType != Press) {
6900 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6901 DragPieceEnd(xPix, yPix); dragging = 0;
6902 DrawPosition(FALSE, NULL);
6906 fromX = x; fromY = y; toX = toY = -1;
6907 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6908 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6909 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6911 if (OKToStartUserMove(fromX, fromY)) {
6913 MarkTargetSquares(0);
6914 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
6915 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6916 promoSweep = defaultPromoChoice;
6917 selectFlag = 0; lastX = xPix; lastY = yPix;
6918 Sweep(0); // Pawn that is going to promote: preview promotion piece
6919 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6921 if (appData.highlightDragging) {
6922 SetHighlights(fromX, fromY, -1, -1);
6924 } else fromX = fromY = -1;
6930 if (clickType == Press && gameMode != EditPosition) {
6935 // ignore off-board to clicks
6936 if(y < 0 || x < 0) return;
6938 /* Check if clicking again on the same color piece */
6939 fromP = boards[currentMove][fromY][fromX];
6940 toP = boards[currentMove][y][x];
6941 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6942 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6943 WhitePawn <= toP && toP <= WhiteKing &&
6944 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6945 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6946 (BlackPawn <= fromP && fromP <= BlackKing &&
6947 BlackPawn <= toP && toP <= BlackKing &&
6948 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6949 !(fromP == BlackKing && toP == BlackRook && frc))) {
6950 /* Clicked again on same color piece -- changed his mind */
6951 second = (x == fromX && y == fromY);
6952 promoDefaultAltered = FALSE;
6953 MarkTargetSquares(1);
6954 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6955 if (appData.highlightDragging) {
6956 SetHighlights(x, y, -1, -1);
6960 if (OKToStartUserMove(x, y)) {
6961 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6962 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6963 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6964 gatingPiece = boards[currentMove][fromY][fromX];
6965 else gatingPiece = EmptySquare;
6967 fromY = y; dragging = 1;
6968 MarkTargetSquares(0);
6969 DragPieceBegin(xPix, yPix, FALSE);
6970 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6971 promoSweep = defaultPromoChoice;
6972 selectFlag = 0; lastX = xPix; lastY = yPix;
6973 Sweep(0); // Pawn that is going to promote: preview promotion piece
6977 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6980 // ignore clicks on holdings
6981 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6984 if (clickType == Release && x == fromX && y == fromY) {
6985 DragPieceEnd(xPix, yPix); dragging = 0;
6987 // a deferred attempt to click-click move an empty square on top of a piece
6988 boards[currentMove][y][x] = EmptySquare;
6990 DrawPosition(FALSE, boards[currentMove]);
6991 fromX = fromY = -1; clearFlag = 0;
6994 if (appData.animateDragging) {
6995 /* Undo animation damage if any */
6996 DrawPosition(FALSE, NULL);
6999 /* Second up/down in same square; just abort move */
7002 gatingPiece = EmptySquare;
7005 ClearPremoveHighlights();
7007 /* First upclick in same square; start click-click mode */
7008 SetHighlights(x, y, -1, -1);
7015 /* we now have a different from- and (possibly off-board) to-square */
7016 /* Completed move */
7019 saveAnimate = appData.animate;
7020 MarkTargetSquares(1);
7021 if (clickType == Press) {
7022 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7023 // must be Edit Position mode with empty-square selected
7024 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7025 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7028 if(appData.sweepSelect && HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7029 ChessSquare piece = boards[currentMove][fromY][fromX];
7030 DragPieceBegin(xPix, yPix, TRUE); dragging = 1;
7031 promoSweep = defaultPromoChoice;
7032 if(PieceToChar(PROMOTED piece) == '+') promoSweep = PROMOTED piece;
7033 selectFlag = 0; lastX = xPix; lastY = yPix;
7034 Sweep(0); // Pawn that is going to promote: preview promotion piece
7035 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7036 DrawPosition(FALSE, boards[currentMove]);
7039 /* Finish clickclick move */
7040 if (appData.animate || appData.highlightLastMove) {
7041 SetHighlights(fromX, fromY, toX, toY);
7046 /* Finish drag move */
7047 if (appData.highlightLastMove) {
7048 SetHighlights(fromX, fromY, toX, toY);
7052 DragPieceEnd(xPix, yPix); dragging = 0;
7053 /* Don't animate move and drag both */
7054 appData.animate = FALSE;
7057 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7058 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7059 ChessSquare piece = boards[currentMove][fromY][fromX];
7060 if(gameMode == EditPosition && piece != EmptySquare &&
7061 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7064 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7065 n = PieceToNumber(piece - (int)BlackPawn);
7066 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7067 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7068 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7070 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7071 n = PieceToNumber(piece);
7072 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7073 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7074 boards[currentMove][n][BOARD_WIDTH-2]++;
7076 boards[currentMove][fromY][fromX] = EmptySquare;
7080 DrawPosition(TRUE, boards[currentMove]);
7084 // off-board moves should not be highlighted
7085 if(x < 0 || y < 0) ClearHighlights();
7087 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
7089 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7090 SetHighlights(fromX, fromY, toX, toY);
7091 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7092 // [HGM] super: promotion to captured piece selected from holdings
7093 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7094 promotionChoice = TRUE;
7095 // kludge follows to temporarily execute move on display, without promoting yet
7096 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7097 boards[currentMove][toY][toX] = p;
7098 DrawPosition(FALSE, boards[currentMove]);
7099 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7100 boards[currentMove][toY][toX] = q;
7101 DisplayMessage("Click in holdings to choose piece", "");
7106 int oldMove = currentMove;
7107 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7108 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7109 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7110 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7111 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7112 DrawPosition(TRUE, boards[currentMove]);
7115 appData.animate = saveAnimate;
7116 if (appData.animate || appData.animateDragging) {
7117 /* Undo animation damage if needed */
7118 DrawPosition(FALSE, NULL);
7123 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7124 { // front-end-free part taken out of PieceMenuPopup
7125 int whichMenu; int xSqr, ySqr;
7127 if(seekGraphUp) { // [HGM] seekgraph
7128 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7129 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7133 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7134 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7135 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7136 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7137 if(action == Press) {
7138 originalFlip = flipView;
7139 flipView = !flipView; // temporarily flip board to see game from partners perspective
7140 DrawPosition(TRUE, partnerBoard);
7141 DisplayMessage(partnerStatus, "");
7143 } else if(action == Release) {
7144 flipView = originalFlip;
7145 DrawPosition(TRUE, boards[currentMove]);
7151 xSqr = EventToSquare(x, BOARD_WIDTH);
7152 ySqr = EventToSquare(y, BOARD_HEIGHT);
7153 if (action == Release) {
7154 if(pieceSweep != EmptySquare) {
7155 EditPositionMenuEvent(pieceSweep, toX, toY);
7156 pieceSweep = EmptySquare;
7157 } else UnLoadPV(); // [HGM] pv
7159 if (action != Press) return -2; // return code to be ignored
7162 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7164 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7165 if (xSqr < 0 || ySqr < 0) return -1;
7166 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7167 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7168 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7169 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7173 if(!appData.icsEngineAnalyze) return -1;
7174 case IcsPlayingWhite:
7175 case IcsPlayingBlack:
7176 if(!appData.zippyPlay) goto noZip;
7179 case MachinePlaysWhite:
7180 case MachinePlaysBlack:
7181 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7182 if (!appData.dropMenu) {
7184 return 2; // flag front-end to grab mouse events
7186 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7187 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7190 if (xSqr < 0 || ySqr < 0) return -1;
7191 if (!appData.dropMenu || appData.testLegality &&
7192 gameInfo.variant != VariantBughouse &&
7193 gameInfo.variant != VariantCrazyhouse) return -1;
7194 whichMenu = 1; // drop menu
7200 if (((*fromX = xSqr) < 0) ||
7201 ((*fromY = ySqr) < 0)) {
7202 *fromX = *fromY = -1;
7206 *fromX = BOARD_WIDTH - 1 - *fromX;
7208 *fromY = BOARD_HEIGHT - 1 - *fromY;
7214 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7216 // char * hint = lastHint;
7217 FrontEndProgramStats stats;
7219 stats.which = cps == &first ? 0 : 1;
7220 stats.depth = cpstats->depth;
7221 stats.nodes = cpstats->nodes;
7222 stats.score = cpstats->score;
7223 stats.time = cpstats->time;
7224 stats.pv = cpstats->movelist;
7225 stats.hint = lastHint;
7226 stats.an_move_index = 0;
7227 stats.an_move_count = 0;
7229 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7230 stats.hint = cpstats->move_name;
7231 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7232 stats.an_move_count = cpstats->nr_moves;
7235 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
7237 SetProgramStats( &stats );
7241 ClearEngineOutputPane (int which)
7243 static FrontEndProgramStats dummyStats;
7244 dummyStats.which = which;
7245 dummyStats.pv = "#";
7246 SetProgramStats( &dummyStats );
7249 #define MAXPLAYERS 500
7252 TourneyStandings (int display)
7254 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7255 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7256 char result, *p, *names[MAXPLAYERS];
7258 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7259 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7260 names[0] = p = strdup(appData.participants);
7261 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7263 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7265 while(result = appData.results[nr]) {
7266 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7267 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7268 wScore = bScore = 0;
7270 case '+': wScore = 2; break;
7271 case '-': bScore = 2; break;
7272 case '=': wScore = bScore = 1; break;
7274 case '*': return strdup("busy"); // tourney not finished
7282 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7283 for(w=0; w<nPlayers; w++) {
7285 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7286 ranking[w] = b; points[w] = bScore; score[b] = -2;
7288 p = malloc(nPlayers*34+1);
7289 for(w=0; w<nPlayers && w<display; w++)
7290 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7296 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7297 { // count all piece types
7299 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7300 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7301 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7304 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7305 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7306 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7307 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7308 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7309 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7314 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7316 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7317 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7319 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7320 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7321 if(myPawns == 2 && nMine == 3) // KPP
7322 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7323 if(myPawns == 1 && nMine == 2) // KP
7324 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7325 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7326 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7327 if(myPawns) return FALSE;
7328 if(pCnt[WhiteRook+side])
7329 return pCnt[BlackRook-side] ||
7330 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7331 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7332 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7333 if(pCnt[WhiteCannon+side]) {
7334 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7335 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7337 if(pCnt[WhiteKnight+side])
7338 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7343 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7345 VariantClass v = gameInfo.variant;
7347 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7348 if(v == VariantShatranj) return TRUE; // always winnable through baring
7349 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7350 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7352 if(v == VariantXiangqi) {
7353 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7355 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7356 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7357 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7358 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7359 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7360 if(stale) // we have at least one last-rank P plus perhaps C
7361 return majors // KPKX
7362 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7364 return pCnt[WhiteFerz+side] // KCAK
7365 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7366 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7367 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7369 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7370 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7372 if(nMine == 1) return FALSE; // bare King
7373 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
7374 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7375 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7376 // by now we have King + 1 piece (or multiple Bishops on the same color)
7377 if(pCnt[WhiteKnight+side])
7378 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7379 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7380 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7382 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7383 if(pCnt[WhiteAlfil+side])
7384 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7385 if(pCnt[WhiteWazir+side])
7386 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7393 CompareWithRights (Board b1, Board b2)
7396 if(!CompareBoards(b1, b2)) return FALSE;
7397 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
7398 /* compare castling rights */
7399 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
7400 rights++; /* King lost rights, while rook still had them */
7401 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
7402 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
7403 rights++; /* but at least one rook lost them */
7405 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
7407 if( b1[CASTLING][5] != NoRights ) {
7408 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
7415 Adjudicate (ChessProgramState *cps)
7416 { // [HGM] some adjudications useful with buggy engines
7417 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7418 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7419 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7420 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7421 int k, count = 0; static int bare = 1;
7422 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7423 Boolean canAdjudicate = !appData.icsActive;
7425 // most tests only when we understand the game, i.e. legality-checking on
7426 if( appData.testLegality )
7427 { /* [HGM] Some more adjudications for obstinate engines */
7428 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7429 static int moveCount = 6;
7431 char *reason = NULL;
7433 /* Count what is on board. */
7434 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7436 /* Some material-based adjudications that have to be made before stalemate test */
7437 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7438 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7439 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7440 if(canAdjudicate && appData.checkMates) {
7442 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7443 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7444 "Xboard adjudication: King destroyed", GE_XBOARD );
7449 /* Bare King in Shatranj (loses) or Losers (wins) */
7450 if( nrW == 1 || nrB == 1) {
7451 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7452 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7453 if(canAdjudicate && appData.checkMates) {
7455 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7456 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7457 "Xboard adjudication: Bare king", GE_XBOARD );
7461 if( gameInfo.variant == VariantShatranj && --bare < 0)
7463 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7464 if(canAdjudicate && appData.checkMates) {
7465 /* but only adjudicate if adjudication enabled */
7467 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7468 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7469 "Xboard adjudication: Bare king", GE_XBOARD );
7476 // don't wait for engine to announce game end if we can judge ourselves
7477 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7479 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7480 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7481 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7482 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7485 reason = "Xboard adjudication: 3rd check";
7486 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7496 reason = "Xboard adjudication: Stalemate";
7497 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7498 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7499 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7500 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7501 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7502 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7503 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7504 EP_CHECKMATE : EP_WINS);
7505 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7506 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7510 reason = "Xboard adjudication: Checkmate";
7511 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7515 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7517 result = GameIsDrawn; break;
7519 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7521 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7525 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7527 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7528 GameEnds( result, reason, GE_XBOARD );
7532 /* Next absolutely insufficient mating material. */
7533 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7534 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7535 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7537 /* always flag draws, for judging claims */
7538 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7540 if(canAdjudicate && appData.materialDraws) {
7541 /* but only adjudicate them if adjudication enabled */
7542 if(engineOpponent) {
7543 SendToProgram("force\n", engineOpponent); // suppress reply
7544 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7546 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7551 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7552 if(gameInfo.variant == VariantXiangqi ?
7553 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7555 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7556 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7557 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7558 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7560 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7561 { /* if the first 3 moves do not show a tactical win, declare draw */
7562 if(engineOpponent) {
7563 SendToProgram("force\n", engineOpponent); // suppress reply
7564 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7566 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7569 } else moveCount = 6;
7572 // Repetition draws and 50-move rule can be applied independently of legality testing
7574 /* Check for rep-draws */
7576 for(k = forwardMostMove-2;
7577 k>=backwardMostMove && k>=forwardMostMove-100 &&
7578 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7579 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7582 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7583 /* compare castling rights */
7584 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7585 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7586 rights++; /* King lost rights, while rook still had them */
7587 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7588 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7589 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7590 rights++; /* but at least one rook lost them */
7592 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7593 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7595 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7596 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7597 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7600 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7601 && appData.drawRepeats > 1) {
7602 /* adjudicate after user-specified nr of repeats */
7603 int result = GameIsDrawn;
7604 char *details = "XBoard adjudication: repetition draw";
7605 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7606 // [HGM] xiangqi: check for forbidden perpetuals
7607 int m, ourPerpetual = 1, hisPerpetual = 1;
7608 for(m=forwardMostMove; m>k; m-=2) {
7609 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7610 ourPerpetual = 0; // the current mover did not always check
7611 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7612 hisPerpetual = 0; // the opponent did not always check
7614 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7615 ourPerpetual, hisPerpetual);
7616 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7617 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7618 details = "Xboard adjudication: perpetual checking";
7620 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7621 break; // (or we would have caught him before). Abort repetition-checking loop.
7623 // Now check for perpetual chases
7624 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7625 hisPerpetual = PerpetualChase(k, forwardMostMove);
7626 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7627 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7628 static char resdet[MSG_SIZ];
7629 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7631 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
7633 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7634 break; // Abort repetition-checking loop.
7636 // if neither of us is checking or chasing all the time, or both are, it is draw
7638 if(engineOpponent) {
7639 SendToProgram("force\n", engineOpponent); // suppress reply
7640 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7642 GameEnds( result, details, GE_XBOARD );
7645 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7646 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7650 /* Now we test for 50-move draws. Determine ply count */
7651 count = forwardMostMove;
7652 /* look for last irreversble move */
7653 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7655 /* if we hit starting position, add initial plies */
7656 if( count == backwardMostMove )
7657 count -= initialRulePlies;
7658 count = forwardMostMove - count;
7659 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7660 // adjust reversible move counter for checks in Xiangqi
7661 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7662 if(i < backwardMostMove) i = backwardMostMove;
7663 while(i <= forwardMostMove) {
7664 lastCheck = inCheck; // check evasion does not count
7665 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7666 if(inCheck || lastCheck) count--; // check does not count
7671 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7672 /* this is used to judge if draw claims are legal */
7673 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7674 if(engineOpponent) {
7675 SendToProgram("force\n", engineOpponent); // suppress reply
7676 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7678 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7682 /* if draw offer is pending, treat it as a draw claim
7683 * when draw condition present, to allow engines a way to
7684 * claim draws before making their move to avoid a race
7685 * condition occurring after their move
7687 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7689 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7690 p = "Draw claim: 50-move rule";
7691 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7692 p = "Draw claim: 3-fold repetition";
7693 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7694 p = "Draw claim: insufficient mating material";
7695 if( p != NULL && canAdjudicate) {
7696 if(engineOpponent) {
7697 SendToProgram("force\n", engineOpponent); // suppress reply
7698 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7700 GameEnds( GameIsDrawn, p, GE_XBOARD );
7705 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7706 if(engineOpponent) {
7707 SendToProgram("force\n", engineOpponent); // suppress reply
7708 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7710 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7717 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
7718 { // [HGM] book: this routine intercepts moves to simulate book replies
7719 char *bookHit = NULL;
7721 //first determine if the incoming move brings opponent into his book
7722 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7723 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7724 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7725 if(bookHit != NULL && !cps->bookSuspend) {
7726 // make sure opponent is not going to reply after receiving move to book position
7727 SendToProgram("force\n", cps);
7728 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7730 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7731 // now arrange restart after book miss
7733 // after a book hit we never send 'go', and the code after the call to this routine
7734 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7735 char buf[MSG_SIZ], *move = bookHit;
7737 int fromX, fromY, toX, toY;
7741 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
7742 &fromX, &fromY, &toX, &toY, &promoChar)) {
7743 (void) CoordsToAlgebraic(boards[forwardMostMove],
7744 PosFlags(forwardMostMove),
7745 fromY, fromX, toY, toX, promoChar, move);
7747 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
7751 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
7752 SendToProgram(buf, cps);
7753 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7754 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7755 SendToProgram("go\n", cps);
7756 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7757 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7758 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7759 SendToProgram("go\n", cps);
7760 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7762 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7766 ChessProgramState *savedState;
7768 DeferredBookMove (void)
7770 if(savedState->lastPing != savedState->lastPong)
7771 ScheduleDelayedEvent(DeferredBookMove, 10);
7773 HandleMachineMove(savedMessage, savedState);
7776 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
7779 HandleMachineMove (char *message, ChessProgramState *cps)
7781 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7782 char realname[MSG_SIZ];
7783 int fromX, fromY, toX, toY;
7790 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
7791 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
7792 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
7793 DisplayError(_("Invalid pairing from pairing engine"), 0);
7796 pairingReceived = 1;
7798 return; // Skim the pairing messages here.
7803 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7805 * Kludge to ignore BEL characters
7807 while (*message == '\007') message++;
7810 * [HGM] engine debug message: ignore lines starting with '#' character
7812 if(cps->debug && *message == '#') return;
7815 * Look for book output
7817 if (cps == &first && bookRequested) {
7818 if (message[0] == '\t' || message[0] == ' ') {
7819 /* Part of the book output is here; append it */
7820 strcat(bookOutput, message);
7821 strcat(bookOutput, " \n");
7823 } else if (bookOutput[0] != NULLCHAR) {
7824 /* All of book output has arrived; display it */
7825 char *p = bookOutput;
7826 while (*p != NULLCHAR) {
7827 if (*p == '\t') *p = ' ';
7830 DisplayInformation(bookOutput);
7831 bookRequested = FALSE;
7832 /* Fall through to parse the current output */
7837 * Look for machine move.
7839 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7840 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7842 /* This method is only useful on engines that support ping */
7843 if (cps->lastPing != cps->lastPong) {
7844 if (gameMode == BeginningOfGame) {
7845 /* Extra move from before last new; ignore */
7846 if (appData.debugMode) {
7847 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7850 if (appData.debugMode) {
7851 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7852 cps->which, gameMode);
7855 SendToProgram("undo\n", cps);
7861 case BeginningOfGame:
7862 /* Extra move from before last reset; ignore */
7863 if (appData.debugMode) {
7864 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7871 /* Extra move after we tried to stop. The mode test is
7872 not a reliable way of detecting this problem, but it's
7873 the best we can do on engines that don't support ping.
7875 if (appData.debugMode) {
7876 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7877 cps->which, gameMode);
7879 SendToProgram("undo\n", cps);
7882 case MachinePlaysWhite:
7883 case IcsPlayingWhite:
7884 machineWhite = TRUE;
7887 case MachinePlaysBlack:
7888 case IcsPlayingBlack:
7889 machineWhite = FALSE;
7892 case TwoMachinesPlay:
7893 machineWhite = (cps->twoMachinesColor[0] == 'w');
7896 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7897 if (appData.debugMode) {
7899 "Ignoring move out of turn by %s, gameMode %d"
7900 ", forwardMost %d\n",
7901 cps->which, gameMode, forwardMostMove);
7906 if(cps->alphaRank) AlphaRank(machineMove, 4);
7907 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7908 &fromX, &fromY, &toX, &toY, &promoChar)) {
7909 /* Machine move could not be parsed; ignore it. */
7910 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7911 machineMove, _(cps->which));
7912 DisplayError(buf1, 0);
7913 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7914 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7915 if (gameMode == TwoMachinesPlay) {
7916 GameEnds(machineWhite ? BlackWins : WhiteWins,
7922 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7923 /* So we have to redo legality test with true e.p. status here, */
7924 /* to make sure an illegal e.p. capture does not slip through, */
7925 /* to cause a forfeit on a justified illegal-move complaint */
7926 /* of the opponent. */
7927 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7929 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7930 fromY, fromX, toY, toX, promoChar);
7931 if(moveType == IllegalMove) {
7932 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7933 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7934 GameEnds(machineWhite ? BlackWins : WhiteWins,
7937 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7938 /* [HGM] Kludge to handle engines that send FRC-style castling
7939 when they shouldn't (like TSCP-Gothic) */
7941 case WhiteASideCastleFR:
7942 case BlackASideCastleFR:
7944 currentMoveString[2]++;
7946 case WhiteHSideCastleFR:
7947 case BlackHSideCastleFR:
7949 currentMoveString[2]--;
7951 default: ; // nothing to do, but suppresses warning of pedantic compilers
7954 hintRequested = FALSE;
7955 lastHint[0] = NULLCHAR;
7956 bookRequested = FALSE;
7957 /* Program may be pondering now */
7958 cps->maybeThinking = TRUE;
7959 if (cps->sendTime == 2) cps->sendTime = 1;
7960 if (cps->offeredDraw) cps->offeredDraw--;
7962 /* [AS] Save move info*/
7963 pvInfoList[ forwardMostMove ].score = programStats.score;
7964 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7965 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7967 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7969 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7970 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7973 while( count < adjudicateLossPlies ) {
7974 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7977 score = -score; /* Flip score for winning side */
7980 if( score > adjudicateLossThreshold ) {
7987 if( count >= adjudicateLossPlies ) {
7988 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7990 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7991 "Xboard adjudication",
7998 if(Adjudicate(cps)) {
7999 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8000 return; // [HGM] adjudicate: for all automatic game ends
8004 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8006 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8007 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8009 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8011 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8013 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8014 char buf[3*MSG_SIZ];
8016 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8017 programStats.score / 100.,
8019 programStats.time / 100.,
8020 (unsigned int)programStats.nodes,
8021 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8022 programStats.movelist);
8024 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
8029 /* [AS] Clear stats for next move */
8030 ClearProgramStats();
8031 thinkOutput[0] = NULLCHAR;
8032 hiddenThinkOutputState = 0;
8035 if (gameMode == TwoMachinesPlay) {
8036 /* [HGM] relaying draw offers moved to after reception of move */
8037 /* and interpreting offer as claim if it brings draw condition */
8038 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8039 SendToProgram("draw\n", cps->other);
8041 if (cps->other->sendTime) {
8042 SendTimeRemaining(cps->other,
8043 cps->other->twoMachinesColor[0] == 'w');
8045 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8046 if (firstMove && !bookHit) {
8048 if (cps->other->useColors) {
8049 SendToProgram(cps->other->twoMachinesColor, cps->other);
8051 SendToProgram("go\n", cps->other);
8053 cps->other->maybeThinking = TRUE;
8056 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8058 if (!pausing && appData.ringBellAfterMoves) {
8063 * Reenable menu items that were disabled while
8064 * machine was thinking
8066 if (gameMode != TwoMachinesPlay)
8067 SetUserThinkingEnables();
8069 // [HGM] book: after book hit opponent has received move and is now in force mode
8070 // force the book reply into it, and then fake that it outputted this move by jumping
8071 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8073 static char bookMove[MSG_SIZ]; // a bit generous?
8075 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8076 strcat(bookMove, bookHit);
8079 programStats.nodes = programStats.depth = programStats.time =
8080 programStats.score = programStats.got_only_move = 0;
8081 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8083 if(cps->lastPing != cps->lastPong) {
8084 savedMessage = message; // args for deferred call
8086 ScheduleDelayedEvent(DeferredBookMove, 10);
8095 /* Set special modes for chess engines. Later something general
8096 * could be added here; for now there is just one kludge feature,
8097 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8098 * when "xboard" is given as an interactive command.
8100 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8101 cps->useSigint = FALSE;
8102 cps->useSigterm = FALSE;
8104 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8105 ParseFeatures(message+8, cps);
8106 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8109 if ((!appData.testLegality || gameInfo.variant == VariantFairy) &&
8110 !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
8111 int dummy, s=6; char buf[MSG_SIZ];
8112 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8113 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8114 if(startedFromSetupPosition) return;
8115 ParseFEN(boards[0], &dummy, message+s);
8116 DrawPosition(TRUE, boards[0]);
8117 startedFromSetupPosition = TRUE;
8120 /* [HGM] Allow engine to set up a position. Don't ask me why one would
8121 * want this, I was asked to put it in, and obliged.
8123 if (!strncmp(message, "setboard ", 9)) {
8124 Board initial_position;
8126 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8128 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
8129 DisplayError(_("Bad FEN received from engine"), 0);
8133 CopyBoard(boards[0], initial_position);
8134 initialRulePlies = FENrulePlies;
8135 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8136 else gameMode = MachinePlaysBlack;
8137 DrawPosition(FALSE, boards[currentMove]);
8143 * Look for communication commands
8145 if (!strncmp(message, "telluser ", 9)) {
8146 if(message[9] == '\\' && message[10] == '\\')
8147 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8149 DisplayNote(message + 9);
8152 if (!strncmp(message, "tellusererror ", 14)) {
8154 if(message[14] == '\\' && message[15] == '\\')
8155 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8157 DisplayError(message + 14, 0);
8160 if (!strncmp(message, "tellopponent ", 13)) {
8161 if (appData.icsActive) {
8163 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8167 DisplayNote(message + 13);
8171 if (!strncmp(message, "tellothers ", 11)) {
8172 if (appData.icsActive) {
8174 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8180 if (!strncmp(message, "tellall ", 8)) {
8181 if (appData.icsActive) {
8183 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
8187 DisplayNote(message + 8);
8191 if (strncmp(message, "warning", 7) == 0) {
8192 /* Undocumented feature, use tellusererror in new code */
8193 DisplayError(message, 0);
8196 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
8197 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
8198 strcat(realname, " query");
8199 AskQuestion(realname, buf2, buf1, cps->pr);
8202 /* Commands from the engine directly to ICS. We don't allow these to be
8203 * sent until we are logged on. Crafty kibitzes have been known to
8204 * interfere with the login process.
8207 if (!strncmp(message, "tellics ", 8)) {
8208 SendToICS(message + 8);
8212 if (!strncmp(message, "tellicsnoalias ", 15)) {
8213 SendToICS(ics_prefix);
8214 SendToICS(message + 15);
8218 /* The following are for backward compatibility only */
8219 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
8220 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
8221 SendToICS(ics_prefix);
8227 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
8231 * If the move is illegal, cancel it and redraw the board.
8232 * Also deal with other error cases. Matching is rather loose
8233 * here to accommodate engines written before the spec.
8235 if (strncmp(message + 1, "llegal move", 11) == 0 ||
8236 strncmp(message, "Error", 5) == 0) {
8237 if (StrStr(message, "name") ||
8238 StrStr(message, "rating") || StrStr(message, "?") ||
8239 StrStr(message, "result") || StrStr(message, "board") ||
8240 StrStr(message, "bk") || StrStr(message, "computer") ||
8241 StrStr(message, "variant") || StrStr(message, "hint") ||
8242 StrStr(message, "random") || StrStr(message, "depth") ||
8243 StrStr(message, "accepted")) {
8246 if (StrStr(message, "protover")) {
8247 /* Program is responding to input, so it's apparently done
8248 initializing, and this error message indicates it is
8249 protocol version 1. So we don't need to wait any longer
8250 for it to initialize and send feature commands. */
8251 FeatureDone(cps, 1);
8252 cps->protocolVersion = 1;
8255 cps->maybeThinking = FALSE;
8257 if (StrStr(message, "draw")) {
8258 /* Program doesn't have "draw" command */
8259 cps->sendDrawOffers = 0;
8262 if (cps->sendTime != 1 &&
8263 (StrStr(message, "time") || StrStr(message, "otim"))) {
8264 /* Program apparently doesn't have "time" or "otim" command */
8268 if (StrStr(message, "analyze")) {
8269 cps->analysisSupport = FALSE;
8270 cps->analyzing = FALSE;
8271 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
8272 EditGameEvent(); // [HGM] try to preserve loaded game
8273 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
8274 DisplayError(buf2, 0);
8277 if (StrStr(message, "(no matching move)st")) {
8278 /* Special kludge for GNU Chess 4 only */
8279 cps->stKludge = TRUE;
8280 SendTimeControl(cps, movesPerSession, timeControl,
8281 timeIncrement, appData.searchDepth,
8285 if (StrStr(message, "(no matching move)sd")) {
8286 /* Special kludge for GNU Chess 4 only */
8287 cps->sdKludge = TRUE;
8288 SendTimeControl(cps, movesPerSession, timeControl,
8289 timeIncrement, appData.searchDepth,
8293 if (!StrStr(message, "llegal")) {
8296 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8297 gameMode == IcsIdle) return;
8298 if (forwardMostMove <= backwardMostMove) return;
8299 if (pausing) PauseEvent();
8300 if(appData.forceIllegal) {
8301 // [HGM] illegal: machine refused move; force position after move into it
8302 SendToProgram("force\n", cps);
8303 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
8304 // we have a real problem now, as SendBoard will use the a2a3 kludge
8305 // when black is to move, while there might be nothing on a2 or black
8306 // might already have the move. So send the board as if white has the move.
8307 // But first we must change the stm of the engine, as it refused the last move
8308 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
8309 if(WhiteOnMove(forwardMostMove)) {
8310 SendToProgram("a7a6\n", cps); // for the engine black still had the move
8311 SendBoard(cps, forwardMostMove); // kludgeless board
8313 SendToProgram("a2a3\n", cps); // for the engine white still had the move
8314 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8315 SendBoard(cps, forwardMostMove+1); // kludgeless board
8317 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
8318 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
8319 gameMode == TwoMachinesPlay)
8320 SendToProgram("go\n", cps);
8323 if (gameMode == PlayFromGameFile) {
8324 /* Stop reading this game file */
8325 gameMode = EditGame;
8328 /* [HGM] illegal-move claim should forfeit game when Xboard */
8329 /* only passes fully legal moves */
8330 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
8331 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
8332 "False illegal-move claim", GE_XBOARD );
8333 return; // do not take back move we tested as valid
8335 currentMove = forwardMostMove-1;
8336 DisplayMove(currentMove-1); /* before DisplayMoveError */
8337 SwitchClocks(forwardMostMove-1); // [HGM] race
8338 DisplayBothClocks();
8339 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
8340 parseList[currentMove], _(cps->which));
8341 DisplayMoveError(buf1);
8342 DrawPosition(FALSE, boards[currentMove]);
8344 SetUserThinkingEnables();
8347 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
8348 /* Program has a broken "time" command that
8349 outputs a string not ending in newline.
8355 * If chess program startup fails, exit with an error message.
8356 * Attempts to recover here are futile.
8358 if ((StrStr(message, "unknown host") != NULL)
8359 || (StrStr(message, "No remote directory") != NULL)
8360 || (StrStr(message, "not found") != NULL)
8361 || (StrStr(message, "No such file") != NULL)
8362 || (StrStr(message, "can't alloc") != NULL)
8363 || (StrStr(message, "Permission denied") != NULL)) {
8365 cps->maybeThinking = FALSE;
8366 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
8367 _(cps->which), cps->program, cps->host, message);
8368 RemoveInputSource(cps->isr);
8369 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
8370 if(cps == &first) appData.noChessProgram = TRUE;
8371 DisplayError(buf1, 0);
8377 * Look for hint output
8379 if (sscanf(message, "Hint: %s", buf1) == 1) {
8380 if (cps == &first && hintRequested) {
8381 hintRequested = FALSE;
8382 if (ParseOneMove(buf1, forwardMostMove, &moveType,
8383 &fromX, &fromY, &toX, &toY, &promoChar)) {
8384 (void) CoordsToAlgebraic(boards[forwardMostMove],
8385 PosFlags(forwardMostMove),
8386 fromY, fromX, toY, toX, promoChar, buf1);
8387 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
8388 DisplayInformation(buf2);
8390 /* Hint move could not be parsed!? */
8391 snprintf(buf2, sizeof(buf2),
8392 _("Illegal hint move \"%s\"\nfrom %s chess program"),
8393 buf1, _(cps->which));
8394 DisplayError(buf2, 0);
8397 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
8403 * Ignore other messages if game is not in progress
8405 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8406 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
8409 * look for win, lose, draw, or draw offer
8411 if (strncmp(message, "1-0", 3) == 0) {
8412 char *p, *q, *r = "";
8413 p = strchr(message, '{');
8421 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8423 } else if (strncmp(message, "0-1", 3) == 0) {
8424 char *p, *q, *r = "";
8425 p = strchr(message, '{');
8433 /* Kludge for Arasan 4.1 bug */
8434 if (strcmp(r, "Black resigns") == 0) {
8435 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8438 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8440 } else if (strncmp(message, "1/2", 3) == 0) {
8441 char *p, *q, *r = "";
8442 p = strchr(message, '{');
8451 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8454 } else if (strncmp(message, "White resign", 12) == 0) {
8455 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8457 } else if (strncmp(message, "Black resign", 12) == 0) {
8458 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8460 } else if (strncmp(message, "White matches", 13) == 0 ||
8461 strncmp(message, "Black matches", 13) == 0 ) {
8462 /* [HGM] ignore GNUShogi noises */
8464 } else if (strncmp(message, "White", 5) == 0 &&
8465 message[5] != '(' &&
8466 StrStr(message, "Black") == NULL) {
8467 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8469 } else if (strncmp(message, "Black", 5) == 0 &&
8470 message[5] != '(') {
8471 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8473 } else if (strcmp(message, "resign") == 0 ||
8474 strcmp(message, "computer resigns") == 0) {
8476 case MachinePlaysBlack:
8477 case IcsPlayingBlack:
8478 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8480 case MachinePlaysWhite:
8481 case IcsPlayingWhite:
8482 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8484 case TwoMachinesPlay:
8485 if (cps->twoMachinesColor[0] == 'w')
8486 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8488 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8495 } else if (strncmp(message, "opponent mates", 14) == 0) {
8497 case MachinePlaysBlack:
8498 case IcsPlayingBlack:
8499 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8501 case MachinePlaysWhite:
8502 case IcsPlayingWhite:
8503 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8505 case TwoMachinesPlay:
8506 if (cps->twoMachinesColor[0] == 'w')
8507 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8509 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8516 } else if (strncmp(message, "computer mates", 14) == 0) {
8518 case MachinePlaysBlack:
8519 case IcsPlayingBlack:
8520 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8522 case MachinePlaysWhite:
8523 case IcsPlayingWhite:
8524 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8526 case TwoMachinesPlay:
8527 if (cps->twoMachinesColor[0] == 'w')
8528 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8530 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8537 } else if (strncmp(message, "checkmate", 9) == 0) {
8538 if (WhiteOnMove(forwardMostMove)) {
8539 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8541 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8544 } else if (strstr(message, "Draw") != NULL ||
8545 strstr(message, "game is a draw") != NULL) {
8546 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8548 } else if (strstr(message, "offer") != NULL &&
8549 strstr(message, "draw") != NULL) {
8551 if (appData.zippyPlay && first.initDone) {
8552 /* Relay offer to ICS */
8553 SendToICS(ics_prefix);
8554 SendToICS("draw\n");
8557 cps->offeredDraw = 2; /* valid until this engine moves twice */
8558 if (gameMode == TwoMachinesPlay) {
8559 if (cps->other->offeredDraw) {
8560 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8561 /* [HGM] in two-machine mode we delay relaying draw offer */
8562 /* until after we also have move, to see if it is really claim */
8564 } else if (gameMode == MachinePlaysWhite ||
8565 gameMode == MachinePlaysBlack) {
8566 if (userOfferedDraw) {
8567 DisplayInformation(_("Machine accepts your draw offer"));
8568 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8570 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8577 * Look for thinking output
8579 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8580 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8582 int plylev, mvleft, mvtot, curscore, time;
8583 char mvname[MOVE_LEN];
8587 int prefixHint = FALSE;
8588 mvname[0] = NULLCHAR;
8591 case MachinePlaysBlack:
8592 case IcsPlayingBlack:
8593 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8595 case MachinePlaysWhite:
8596 case IcsPlayingWhite:
8597 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8602 case IcsObserving: /* [DM] icsEngineAnalyze */
8603 if (!appData.icsEngineAnalyze) ignore = TRUE;
8605 case TwoMachinesPlay:
8606 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8616 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8618 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8619 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8621 if (plyext != ' ' && plyext != '\t') {
8625 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8626 if( cps->scoreIsAbsolute &&
8627 ( gameMode == MachinePlaysBlack ||
8628 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8629 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8630 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8631 !WhiteOnMove(currentMove)
8634 curscore = -curscore;
8637 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
8639 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
8642 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
8643 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
8644 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
8645 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
8646 if(f = fopen(buf, "w")) { // export PV to applicable PV file
8647 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
8649 } else DisplayError(_("failed writing PV"), 0);
8652 tempStats.depth = plylev;
8653 tempStats.nodes = nodes;
8654 tempStats.time = time;
8655 tempStats.score = curscore;
8656 tempStats.got_only_move = 0;
8658 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8661 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8662 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8663 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8664 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8665 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8666 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8667 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8668 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8671 /* Buffer overflow protection */
8672 if (pv[0] != NULLCHAR) {
8673 if (strlen(pv) >= sizeof(tempStats.movelist)
8674 && appData.debugMode) {
8676 "PV is too long; using the first %u bytes.\n",
8677 (unsigned) sizeof(tempStats.movelist) - 1);
8680 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8682 sprintf(tempStats.movelist, " no PV\n");
8685 if (tempStats.seen_stat) {
8686 tempStats.ok_to_send = 1;
8689 if (strchr(tempStats.movelist, '(') != NULL) {
8690 tempStats.line_is_book = 1;
8691 tempStats.nr_moves = 0;
8692 tempStats.moves_left = 0;
8694 tempStats.line_is_book = 0;
8697 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8698 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8700 SendProgramStatsToFrontend( cps, &tempStats );
8703 [AS] Protect the thinkOutput buffer from overflow... this
8704 is only useful if buf1 hasn't overflowed first!
8706 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8708 (gameMode == TwoMachinesPlay ?
8709 ToUpper(cps->twoMachinesColor[0]) : ' '),
8710 ((double) curscore) / 100.0,
8711 prefixHint ? lastHint : "",
8712 prefixHint ? " " : "" );
8714 if( buf1[0] != NULLCHAR ) {
8715 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8717 if( strlen(pv) > max_len ) {
8718 if( appData.debugMode) {
8719 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8721 pv[max_len+1] = '\0';
8724 strcat( thinkOutput, pv);
8727 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8728 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8729 DisplayMove(currentMove - 1);
8733 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8734 /* crafty (9.25+) says "(only move) <move>"
8735 * if there is only 1 legal move
8737 sscanf(p, "(only move) %s", buf1);
8738 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8739 sprintf(programStats.movelist, "%s (only move)", buf1);
8740 programStats.depth = 1;
8741 programStats.nr_moves = 1;
8742 programStats.moves_left = 1;
8743 programStats.nodes = 1;
8744 programStats.time = 1;
8745 programStats.got_only_move = 1;
8747 /* Not really, but we also use this member to
8748 mean "line isn't going to change" (Crafty
8749 isn't searching, so stats won't change) */
8750 programStats.line_is_book = 1;
8752 SendProgramStatsToFrontend( cps, &programStats );
8754 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8755 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8756 DisplayMove(currentMove - 1);
8759 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8760 &time, &nodes, &plylev, &mvleft,
8761 &mvtot, mvname) >= 5) {
8762 /* The stat01: line is from Crafty (9.29+) in response
8763 to the "." command */
8764 programStats.seen_stat = 1;
8765 cps->maybeThinking = TRUE;
8767 if (programStats.got_only_move || !appData.periodicUpdates)
8770 programStats.depth = plylev;
8771 programStats.time = time;
8772 programStats.nodes = nodes;
8773 programStats.moves_left = mvleft;
8774 programStats.nr_moves = mvtot;
8775 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8776 programStats.ok_to_send = 1;
8777 programStats.movelist[0] = '\0';
8779 SendProgramStatsToFrontend( cps, &programStats );
8783 } else if (strncmp(message,"++",2) == 0) {
8784 /* Crafty 9.29+ outputs this */
8785 programStats.got_fail = 2;
8788 } else if (strncmp(message,"--",2) == 0) {
8789 /* Crafty 9.29+ outputs this */
8790 programStats.got_fail = 1;
8793 } else if (thinkOutput[0] != NULLCHAR &&
8794 strncmp(message, " ", 4) == 0) {
8795 unsigned message_len;
8798 while (*p && *p == ' ') p++;
8800 message_len = strlen( p );
8802 /* [AS] Avoid buffer overflow */
8803 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8804 strcat(thinkOutput, " ");
8805 strcat(thinkOutput, p);
8808 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8809 strcat(programStats.movelist, " ");
8810 strcat(programStats.movelist, p);
8813 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8814 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8815 DisplayMove(currentMove - 1);
8823 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8824 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8826 ChessProgramStats cpstats;
8828 if (plyext != ' ' && plyext != '\t') {
8832 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8833 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8834 curscore = -curscore;
8837 cpstats.depth = plylev;
8838 cpstats.nodes = nodes;
8839 cpstats.time = time;
8840 cpstats.score = curscore;
8841 cpstats.got_only_move = 0;
8842 cpstats.movelist[0] = '\0';
8844 if (buf1[0] != NULLCHAR) {
8845 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8848 cpstats.ok_to_send = 0;
8849 cpstats.line_is_book = 0;
8850 cpstats.nr_moves = 0;
8851 cpstats.moves_left = 0;
8853 SendProgramStatsToFrontend( cps, &cpstats );
8860 /* Parse a game score from the character string "game", and
8861 record it as the history of the current game. The game
8862 score is NOT assumed to start from the standard position.
8863 The display is not updated in any way.
8866 ParseGameHistory (char *game)
8869 int fromX, fromY, toX, toY, boardIndex;
8874 if (appData.debugMode)
8875 fprintf(debugFP, "Parsing game history: %s\n", game);
8877 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8878 gameInfo.site = StrSave(appData.icsHost);
8879 gameInfo.date = PGNDate();
8880 gameInfo.round = StrSave("-");
8882 /* Parse out names of players */
8883 while (*game == ' ') game++;
8885 while (*game != ' ') *p++ = *game++;
8887 gameInfo.white = StrSave(buf);
8888 while (*game == ' ') game++;
8890 while (*game != ' ' && *game != '\n') *p++ = *game++;
8892 gameInfo.black = StrSave(buf);
8895 boardIndex = blackPlaysFirst ? 1 : 0;
8898 yyboardindex = boardIndex;
8899 moveType = (ChessMove) Myylex();
8901 case IllegalMove: /* maybe suicide chess, etc. */
8902 if (appData.debugMode) {
8903 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8904 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8905 setbuf(debugFP, NULL);
8907 case WhitePromotion:
8908 case BlackPromotion:
8909 case WhiteNonPromotion:
8910 case BlackNonPromotion:
8912 case WhiteCapturesEnPassant:
8913 case BlackCapturesEnPassant:
8914 case WhiteKingSideCastle:
8915 case WhiteQueenSideCastle:
8916 case BlackKingSideCastle:
8917 case BlackQueenSideCastle:
8918 case WhiteKingSideCastleWild:
8919 case WhiteQueenSideCastleWild:
8920 case BlackKingSideCastleWild:
8921 case BlackQueenSideCastleWild:
8923 case WhiteHSideCastleFR:
8924 case WhiteASideCastleFR:
8925 case BlackHSideCastleFR:
8926 case BlackASideCastleFR:
8928 fromX = currentMoveString[0] - AAA;
8929 fromY = currentMoveString[1] - ONE;
8930 toX = currentMoveString[2] - AAA;
8931 toY = currentMoveString[3] - ONE;
8932 promoChar = currentMoveString[4];
8936 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
8937 fromX = moveType == WhiteDrop ?
8938 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8939 (int) CharToPiece(ToLower(currentMoveString[0]));
8941 toX = currentMoveString[2] - AAA;
8942 toY = currentMoveString[3] - ONE;
8943 promoChar = NULLCHAR;
8947 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8948 if (appData.debugMode) {
8949 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8950 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8951 setbuf(debugFP, NULL);
8953 DisplayError(buf, 0);
8955 case ImpossibleMove:
8957 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8958 if (appData.debugMode) {
8959 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8960 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8961 setbuf(debugFP, NULL);
8963 DisplayError(buf, 0);
8966 if (boardIndex < backwardMostMove) {
8967 /* Oops, gap. How did that happen? */
8968 DisplayError(_("Gap in move list"), 0);
8971 backwardMostMove = blackPlaysFirst ? 1 : 0;
8972 if (boardIndex > forwardMostMove) {
8973 forwardMostMove = boardIndex;
8977 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8978 strcat(parseList[boardIndex-1], " ");
8979 strcat(parseList[boardIndex-1], yy_text);
8991 case GameUnfinished:
8992 if (gameMode == IcsExamining) {
8993 if (boardIndex < backwardMostMove) {
8994 /* Oops, gap. How did that happen? */
8997 backwardMostMove = blackPlaysFirst ? 1 : 0;
9000 gameInfo.result = moveType;
9001 p = strchr(yy_text, '{');
9002 if (p == NULL) p = strchr(yy_text, '(');
9005 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9007 q = strchr(p, *p == '{' ? '}' : ')');
9008 if (q != NULL) *q = NULLCHAR;
9011 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9012 gameInfo.resultDetails = StrSave(p);
9015 if (boardIndex >= forwardMostMove &&
9016 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9017 backwardMostMove = blackPlaysFirst ? 1 : 0;
9020 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9021 fromY, fromX, toY, toX, promoChar,
9022 parseList[boardIndex]);
9023 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9024 /* currentMoveString is set as a side-effect of yylex */
9025 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9026 strcat(moveList[boardIndex], "\n");
9028 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9029 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9035 if(gameInfo.variant != VariantShogi)
9036 strcat(parseList[boardIndex - 1], "+");
9040 strcat(parseList[boardIndex - 1], "#");
9047 /* Apply a move to the given board */
9049 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9051 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9052 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
9054 /* [HGM] compute & store e.p. status and castling rights for new position */
9055 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9057 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9058 oldEP = (signed char)board[EP_STATUS];
9059 board[EP_STATUS] = EP_NONE;
9061 if (fromY == DROP_RANK) {
9063 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9064 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9067 piece = board[toY][toX] = (ChessSquare) fromX;
9071 if( board[toY][toX] != EmptySquare )
9072 board[EP_STATUS] = EP_CAPTURE;
9074 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9075 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9076 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9078 if( board[fromY][fromX] == WhitePawn ) {
9079 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9080 board[EP_STATUS] = EP_PAWN_MOVE;
9082 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9083 gameInfo.variant != VariantBerolina || toX < fromX)
9084 board[EP_STATUS] = toX | berolina;
9085 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9086 gameInfo.variant != VariantBerolina || toX > fromX)
9087 board[EP_STATUS] = toX;
9090 if( board[fromY][fromX] == BlackPawn ) {
9091 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9092 board[EP_STATUS] = EP_PAWN_MOVE;
9093 if( toY-fromY== -2) {
9094 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9095 gameInfo.variant != VariantBerolina || toX < fromX)
9096 board[EP_STATUS] = toX | berolina;
9097 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9098 gameInfo.variant != VariantBerolina || toX > fromX)
9099 board[EP_STATUS] = toX;
9103 for(i=0; i<nrCastlingRights; i++) {
9104 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9105 board[CASTLING][i] == toX && castlingRank[i] == toY
9106 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9109 if (fromX == toX && fromY == toY) return;
9111 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9112 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9113 if(gameInfo.variant == VariantKnightmate)
9114 king += (int) WhiteUnicorn - (int) WhiteKing;
9116 /* Code added by Tord: */
9117 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9118 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9119 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9120 board[fromY][fromX] = EmptySquare;
9121 board[toY][toX] = EmptySquare;
9122 if((toX > fromX) != (piece == WhiteRook)) {
9123 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9125 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9127 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9128 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9129 board[fromY][fromX] = EmptySquare;
9130 board[toY][toX] = EmptySquare;
9131 if((toX > fromX) != (piece == BlackRook)) {
9132 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9134 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9136 /* End of code added by Tord */
9138 } else if (board[fromY][fromX] == king
9139 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9140 && toY == fromY && toX > fromX+1) {
9141 board[fromY][fromX] = EmptySquare;
9142 board[toY][toX] = king;
9143 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9144 board[fromY][BOARD_RGHT-1] = EmptySquare;
9145 } else if (board[fromY][fromX] == king
9146 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9147 && toY == fromY && toX < fromX-1) {
9148 board[fromY][fromX] = EmptySquare;
9149 board[toY][toX] = king;
9150 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9151 board[fromY][BOARD_LEFT] = EmptySquare;
9152 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
9153 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9154 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
9156 /* white pawn promotion */
9157 board[toY][toX] = CharToPiece(ToUpper(promoChar));
9158 if(gameInfo.variant==VariantBughouse ||
9159 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9160 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9161 board[fromY][fromX] = EmptySquare;
9162 } else if ((fromY >= BOARD_HEIGHT>>1)
9164 && gameInfo.variant != VariantXiangqi
9165 && gameInfo.variant != VariantBerolina
9166 && (board[fromY][fromX] == WhitePawn)
9167 && (board[toY][toX] == EmptySquare)) {
9168 board[fromY][fromX] = EmptySquare;
9169 board[toY][toX] = WhitePawn;
9170 captured = board[toY - 1][toX];
9171 board[toY - 1][toX] = EmptySquare;
9172 } else if ((fromY == BOARD_HEIGHT-4)
9174 && gameInfo.variant == VariantBerolina
9175 && (board[fromY][fromX] == WhitePawn)
9176 && (board[toY][toX] == EmptySquare)) {
9177 board[fromY][fromX] = EmptySquare;
9178 board[toY][toX] = WhitePawn;
9179 if(oldEP & EP_BEROLIN_A) {
9180 captured = board[fromY][fromX-1];
9181 board[fromY][fromX-1] = EmptySquare;
9182 }else{ captured = board[fromY][fromX+1];
9183 board[fromY][fromX+1] = EmptySquare;
9185 } else if (board[fromY][fromX] == king
9186 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9187 && toY == fromY && toX > fromX+1) {
9188 board[fromY][fromX] = EmptySquare;
9189 board[toY][toX] = king;
9190 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9191 board[fromY][BOARD_RGHT-1] = EmptySquare;
9192 } else if (board[fromY][fromX] == king
9193 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9194 && toY == fromY && toX < fromX-1) {
9195 board[fromY][fromX] = EmptySquare;
9196 board[toY][toX] = king;
9197 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9198 board[fromY][BOARD_LEFT] = EmptySquare;
9199 } else if (fromY == 7 && fromX == 3
9200 && board[fromY][fromX] == BlackKing
9201 && toY == 7 && toX == 5) {
9202 board[fromY][fromX] = EmptySquare;
9203 board[toY][toX] = BlackKing;
9204 board[fromY][7] = EmptySquare;
9205 board[toY][4] = BlackRook;
9206 } else if (fromY == 7 && fromX == 3
9207 && board[fromY][fromX] == BlackKing
9208 && toY == 7 && toX == 1) {
9209 board[fromY][fromX] = EmptySquare;
9210 board[toY][toX] = BlackKing;
9211 board[fromY][0] = EmptySquare;
9212 board[toY][2] = BlackRook;
9213 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
9214 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9215 && toY < promoRank && promoChar
9217 /* black pawn promotion */
9218 board[toY][toX] = CharToPiece(ToLower(promoChar));
9219 if(gameInfo.variant==VariantBughouse ||
9220 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9221 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9222 board[fromY][fromX] = EmptySquare;
9223 } else if ((fromY < BOARD_HEIGHT>>1)
9225 && gameInfo.variant != VariantXiangqi
9226 && gameInfo.variant != VariantBerolina
9227 && (board[fromY][fromX] == BlackPawn)
9228 && (board[toY][toX] == EmptySquare)) {
9229 board[fromY][fromX] = EmptySquare;
9230 board[toY][toX] = BlackPawn;
9231 captured = board[toY + 1][toX];
9232 board[toY + 1][toX] = EmptySquare;
9233 } else if ((fromY == 3)
9235 && gameInfo.variant == VariantBerolina
9236 && (board[fromY][fromX] == BlackPawn)
9237 && (board[toY][toX] == EmptySquare)) {
9238 board[fromY][fromX] = EmptySquare;
9239 board[toY][toX] = BlackPawn;
9240 if(oldEP & EP_BEROLIN_A) {
9241 captured = board[fromY][fromX-1];
9242 board[fromY][fromX-1] = EmptySquare;
9243 }else{ captured = board[fromY][fromX+1];
9244 board[fromY][fromX+1] = EmptySquare;
9247 board[toY][toX] = board[fromY][fromX];
9248 board[fromY][fromX] = EmptySquare;
9252 if (gameInfo.holdingsWidth != 0) {
9254 /* !!A lot more code needs to be written to support holdings */
9255 /* [HGM] OK, so I have written it. Holdings are stored in the */
9256 /* penultimate board files, so they are automaticlly stored */
9257 /* in the game history. */
9258 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
9259 && promoChar && piece != WhitePawn && piece != BlackPawn) {
9260 /* Delete from holdings, by decreasing count */
9261 /* and erasing image if necessary */
9262 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
9263 if(p < (int) BlackPawn) { /* white drop */
9264 p -= (int)WhitePawn;
9265 p = PieceToNumber((ChessSquare)p);
9266 if(p >= gameInfo.holdingsSize) p = 0;
9267 if(--board[p][BOARD_WIDTH-2] <= 0)
9268 board[p][BOARD_WIDTH-1] = EmptySquare;
9269 if((int)board[p][BOARD_WIDTH-2] < 0)
9270 board[p][BOARD_WIDTH-2] = 0;
9271 } else { /* black drop */
9272 p -= (int)BlackPawn;
9273 p = PieceToNumber((ChessSquare)p);
9274 if(p >= gameInfo.holdingsSize) p = 0;
9275 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
9276 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
9277 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
9278 board[BOARD_HEIGHT-1-p][1] = 0;
9281 if (captured != EmptySquare && gameInfo.holdingsSize > 0
9282 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
9283 /* [HGM] holdings: Add to holdings, if holdings exist */
9284 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
9285 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
9286 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
9289 if (p >= (int) BlackPawn) {
9290 p -= (int)BlackPawn;
9291 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9292 /* in Shogi restore piece to its original first */
9293 captured = (ChessSquare) (DEMOTED captured);
9296 p = PieceToNumber((ChessSquare)p);
9297 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
9298 board[p][BOARD_WIDTH-2]++;
9299 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
9301 p -= (int)WhitePawn;
9302 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9303 captured = (ChessSquare) (DEMOTED captured);
9306 p = PieceToNumber((ChessSquare)p);
9307 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
9308 board[BOARD_HEIGHT-1-p][1]++;
9309 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
9312 } else if (gameInfo.variant == VariantAtomic) {
9313 if (captured != EmptySquare) {
9315 for (y = toY-1; y <= toY+1; y++) {
9316 for (x = toX-1; x <= toX+1; x++) {
9317 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
9318 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
9319 board[y][x] = EmptySquare;
9323 board[toY][toX] = EmptySquare;
9326 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
9327 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
9329 if(promoChar == '+') {
9330 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
9331 board[toY][toX] = (ChessSquare) (PROMOTED piece);
9332 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
9333 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
9335 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
9336 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
9337 // [HGM] superchess: take promotion piece out of holdings
9338 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
9339 if((int)piece < (int)BlackPawn) { // determine stm from piece color
9340 if(!--board[k][BOARD_WIDTH-2])
9341 board[k][BOARD_WIDTH-1] = EmptySquare;
9343 if(!--board[BOARD_HEIGHT-1-k][1])
9344 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
9350 /* Updates forwardMostMove */
9352 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
9354 // forwardMostMove++; // [HGM] bare: moved downstream
9356 (void) CoordsToAlgebraic(boards[forwardMostMove],
9357 PosFlags(forwardMostMove),
9358 fromY, fromX, toY, toX, promoChar,
9359 parseList[forwardMostMove]);
9361 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
9362 int timeLeft; static int lastLoadFlag=0; int king, piece;
9363 piece = boards[forwardMostMove][fromY][fromX];
9364 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
9365 if(gameInfo.variant == VariantKnightmate)
9366 king += (int) WhiteUnicorn - (int) WhiteKing;
9367 if(forwardMostMove == 0) {
9368 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
9369 fprintf(serverMoves, "%s;", UserName());
9370 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
9371 fprintf(serverMoves, "%s;", second.tidy);
9372 fprintf(serverMoves, "%s;", first.tidy);
9373 if(gameMode == MachinePlaysWhite)
9374 fprintf(serverMoves, "%s;", UserName());
9375 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
9376 fprintf(serverMoves, "%s;", second.tidy);
9377 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
9378 lastLoadFlag = loadFlag;
9380 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
9381 // print castling suffix
9382 if( toY == fromY && piece == king ) {
9384 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
9386 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
9389 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
9390 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
9391 boards[forwardMostMove][toY][toX] == EmptySquare
9392 && fromX != toX && fromY != toY)
9393 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
9395 if(promoChar != NULLCHAR)
9396 fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
9398 char buf[MOVE_LEN*2], *p; int len;
9399 fprintf(serverMoves, "/%d/%d",
9400 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
9401 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
9402 else timeLeft = blackTimeRemaining/1000;
9403 fprintf(serverMoves, "/%d", timeLeft);
9404 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
9405 if(p = strchr(buf, '=')) *p = NULLCHAR;
9406 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
9407 fprintf(serverMoves, "/%s", buf);
9409 fflush(serverMoves);
9412 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
9413 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
9416 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
9417 if (commentList[forwardMostMove+1] != NULL) {
9418 free(commentList[forwardMostMove+1]);
9419 commentList[forwardMostMove+1] = NULL;
9421 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9422 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
9423 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
9424 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
9425 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9426 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9427 adjustedClock = FALSE;
9428 gameInfo.result = GameUnfinished;
9429 if (gameInfo.resultDetails != NULL) {
9430 free(gameInfo.resultDetails);
9431 gameInfo.resultDetails = NULL;
9433 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9434 moveList[forwardMostMove - 1]);
9435 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9441 if(gameInfo.variant != VariantShogi)
9442 strcat(parseList[forwardMostMove - 1], "+");
9446 strcat(parseList[forwardMostMove - 1], "#");
9452 /* Updates currentMove if not pausing */
9454 ShowMove (int fromX, int fromY, int toX, int toY)
9456 int instant = (gameMode == PlayFromGameFile) ?
9457 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9458 if(appData.noGUI) return;
9459 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9461 if (forwardMostMove == currentMove + 1) {
9462 AnimateMove(boards[forwardMostMove - 1],
9463 fromX, fromY, toX, toY);
9465 if (appData.highlightLastMove) {
9466 SetHighlights(fromX, fromY, toX, toY);
9469 currentMove = forwardMostMove;
9472 if (instant) return;
9474 DisplayMove(currentMove - 1);
9475 DrawPosition(FALSE, boards[currentMove]);
9476 DisplayBothClocks();
9477 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9481 SendEgtPath (ChessProgramState *cps)
9482 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9483 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9485 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9488 char c, *q = name+1, *r, *s;
9490 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9491 while(*p && *p != ',') *q++ = *p++;
9493 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9494 strcmp(name, ",nalimov:") == 0 ) {
9495 // take nalimov path from the menu-changeable option first, if it is defined
9496 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9497 SendToProgram(buf,cps); // send egtbpath command for nalimov
9499 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9500 (s = StrStr(appData.egtFormats, name)) != NULL) {
9501 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9502 s = r = StrStr(s, ":") + 1; // beginning of path info
9503 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9504 c = *r; *r = 0; // temporarily null-terminate path info
9505 *--q = 0; // strip of trailig ':' from name
9506 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9508 SendToProgram(buf,cps); // send egtbpath command for this format
9510 if(*p == ',') p++; // read away comma to position for next format name
9515 InitChessProgram (ChessProgramState *cps, int setup)
9516 /* setup needed to setup FRC opening position */
9518 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9519 if (appData.noChessProgram) return;
9520 hintRequested = FALSE;
9521 bookRequested = FALSE;
9523 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
9524 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9525 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9526 if(cps->memSize) { /* [HGM] memory */
9527 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9528 SendToProgram(buf, cps);
9530 SendEgtPath(cps); /* [HGM] EGT */
9531 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9532 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9533 SendToProgram(buf, cps);
9536 SendToProgram(cps->initString, cps);
9537 if (gameInfo.variant != VariantNormal &&
9538 gameInfo.variant != VariantLoadable
9539 /* [HGM] also send variant if board size non-standard */
9540 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9542 char *v = VariantName(gameInfo.variant);
9543 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9544 /* [HGM] in protocol 1 we have to assume all variants valid */
9545 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9546 DisplayFatalError(buf, 0, 1);
9550 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9551 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9552 if( gameInfo.variant == VariantXiangqi )
9553 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9554 if( gameInfo.variant == VariantShogi )
9555 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9556 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9557 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9558 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9559 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9560 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9561 if( gameInfo.variant == VariantCourier )
9562 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9563 if( gameInfo.variant == VariantSuper )
9564 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9565 if( gameInfo.variant == VariantGreat )
9566 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9567 if( gameInfo.variant == VariantSChess )
9568 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9569 if( gameInfo.variant == VariantGrand )
9570 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 7;
9573 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9574 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9575 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9576 if(StrStr(cps->variants, b) == NULL) {
9577 // specific sized variant not known, check if general sizing allowed
9578 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9579 if(StrStr(cps->variants, "boardsize") == NULL) {
9580 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9581 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9582 DisplayFatalError(buf, 0, 1);
9585 /* [HGM] here we really should compare with the maximum supported board size */
9588 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9589 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9590 SendToProgram(buf, cps);
9592 currentlyInitializedVariant = gameInfo.variant;
9594 /* [HGM] send opening position in FRC to first engine */
9596 SendToProgram("force\n", cps);
9598 /* engine is now in force mode! Set flag to wake it up after first move. */
9599 setboardSpoiledMachineBlack = 1;
9603 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9604 SendToProgram(buf, cps);
9606 cps->maybeThinking = FALSE;
9607 cps->offeredDraw = 0;
9608 if (!appData.icsActive) {
9609 SendTimeControl(cps, movesPerSession, timeControl,
9610 timeIncrement, appData.searchDepth,
9613 if (appData.showThinking
9614 // [HGM] thinking: four options require thinking output to be sent
9615 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9617 SendToProgram("post\n", cps);
9619 SendToProgram("hard\n", cps);
9620 if (!appData.ponderNextMove) {
9621 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9622 it without being sure what state we are in first. "hard"
9623 is not a toggle, so that one is OK.
9625 SendToProgram("easy\n", cps);
9628 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9629 SendToProgram(buf, cps);
9631 cps->initDone = TRUE;
9632 ClearEngineOutputPane(cps == &second);
9637 StartChessProgram (ChessProgramState *cps)
9642 if (appData.noChessProgram) return;
9643 cps->initDone = FALSE;
9645 if (strcmp(cps->host, "localhost") == 0) {
9646 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9647 } else if (*appData.remoteShell == NULLCHAR) {
9648 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9650 if (*appData.remoteUser == NULLCHAR) {
9651 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9654 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9655 cps->host, appData.remoteUser, cps->program);
9657 err = StartChildProcess(buf, "", &cps->pr);
9661 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9662 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
9663 if(cps != &first) return;
9664 appData.noChessProgram = TRUE;
9667 // DisplayFatalError(buf, err, 1);
9668 // cps->pr = NoProc;
9673 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9674 if (cps->protocolVersion > 1) {
9675 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9676 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9677 cps->comboCnt = 0; // and values of combo boxes
9678 SendToProgram(buf, cps);
9680 SendToProgram("xboard\n", cps);
9685 TwoMachinesEventIfReady P((void))
9687 static int curMess = 0;
9688 if (first.lastPing != first.lastPong) {
9689 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
9690 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9693 if (second.lastPing != second.lastPong) {
9694 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
9695 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9698 DisplayMessage("", ""); curMess = 0;
9704 MakeName (char *template)
9708 static char buf[MSG_SIZ];
9712 clock = time((time_t *)NULL);
9713 tm = localtime(&clock);
9715 while(*p++ = *template++) if(p[-1] == '%') {
9716 switch(*template++) {
9717 case 0: *p = 0; return buf;
9718 case 'Y': i = tm->tm_year+1900; break;
9719 case 'y': i = tm->tm_year-100; break;
9720 case 'M': i = tm->tm_mon+1; break;
9721 case 'd': i = tm->tm_mday; break;
9722 case 'h': i = tm->tm_hour; break;
9723 case 'm': i = tm->tm_min; break;
9724 case 's': i = tm->tm_sec; break;
9727 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
9733 CountPlayers (char *p)
9736 while(p = strchr(p, '\n')) p++, n++; // count participants
9741 WriteTourneyFile (char *results, FILE *f)
9742 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
9743 if(f == NULL) f = fopen(appData.tourneyFile, "w");
9744 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
9745 // create a file with tournament description
9746 fprintf(f, "-participants {%s}\n", appData.participants);
9747 fprintf(f, "-seedBase %d\n", appData.seedBase);
9748 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
9749 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
9750 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
9751 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
9752 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
9753 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
9754 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
9755 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
9756 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
9757 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
9758 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
9759 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
9761 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
9763 fprintf(f, "-mps %d\n", appData.movesPerSession);
9764 fprintf(f, "-tc %s\n", appData.timeControl);
9765 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
9767 fprintf(f, "-results \"%s\"\n", results);
9772 char *command[MAXENGINES], *mnemonic[MAXENGINES];
9775 Substitute (char *participants, int expunge)
9777 int i, changed, changes=0, nPlayers=0;
9778 char *p, *q, *r, buf[MSG_SIZ];
9779 if(participants == NULL) return;
9780 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
9781 r = p = participants; q = appData.participants;
9782 while(*p && *p == *q) {
9783 if(*p == '\n') r = p+1, nPlayers++;
9786 if(*p) { // difference
9787 while(*p && *p++ != '\n');
9788 while(*q && *q++ != '\n');
9790 changes = 1 + (strcmp(p, q) != 0);
9792 if(changes == 1) { // a single engine mnemonic was changed
9793 q = r; while(*q) nPlayers += (*q++ == '\n');
9794 p = buf; while(*r && (*p = *r++) != '\n') p++;
9796 NamesToList(firstChessProgramNames, command, mnemonic, "all");
9797 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
9798 if(mnemonic[i]) { // The substitute is valid
9800 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
9801 flock(fileno(f), LOCK_EX);
9802 ParseArgsFromFile(f);
9803 fseek(f, 0, SEEK_SET);
9804 FREE(appData.participants); appData.participants = participants;
9805 if(expunge) { // erase results of replaced engine
9806 int len = strlen(appData.results), w, b, dummy;
9807 for(i=0; i<len; i++) {
9808 Pairing(i, nPlayers, &w, &b, &dummy);
9809 if((w == changed || b == changed) && appData.results[i] == '*') {
9810 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
9815 for(i=0; i<len; i++) {
9816 Pairing(i, nPlayers, &w, &b, &dummy);
9817 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
9820 WriteTourneyFile(appData.results, f);
9821 fclose(f); // release lock
9824 } else DisplayError(_("No engine with the name you gave is installed"), 0);
9826 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
9827 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
9833 CreateTourney (char *name)
9836 if(matchMode && strcmp(name, appData.tourneyFile)) {
9837 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
9839 if(name[0] == NULLCHAR) {
9840 if(appData.participants[0])
9841 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
9844 f = fopen(name, "r");
9845 if(f) { // file exists
9846 ASSIGN(appData.tourneyFile, name);
9847 ParseArgsFromFile(f); // parse it
9849 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
9850 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
9851 DisplayError(_("Not enough participants"), 0);
9854 ASSIGN(appData.tourneyFile, name);
9855 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
9856 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
9859 appData.noChessProgram = FALSE;
9860 appData.clockMode = TRUE;
9866 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
9868 char buf[MSG_SIZ], *p, *q;
9869 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
9870 skip = !all && group[0]; // if group requested, we start in skip mode
9871 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
9872 p = names; q = buf; header = 0;
9873 while(*p && *p != '\n') *q++ = *p++;
9877 if(strstr(buf, "# end") == buf) { depth--; continue; } // leave group, and suppress printing label
9878 depth++; // we must be entering a new group
9879 if(all) continue; // suppress printing group headers when complete list requested
9881 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
9883 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
9884 if(engineList[i]) free(engineList[i]);
9885 engineList[i] = strdup(buf);
9886 if(buf[0] != '#') TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
9887 if(engineMnemonic[i]) free(engineMnemonic[i]);
9888 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
9890 sscanf(q + 8, "%s", buf + strlen(buf));
9893 engineMnemonic[i] = strdup(buf);
9896 engineList[i] = engineMnemonic[i] = NULL;
9900 // following implemented as macro to avoid type limitations
9901 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
9905 { // swap settings for first engine and other engine (so far only some selected options)
9910 SWAP(chessProgram, p)
9912 SWAP(hasOwnBookUCI, h)
9913 SWAP(protocolVersion, h)
9915 SWAP(scoreIsAbsolute, h)
9924 SetPlayer (int player, char *p)
9925 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
9927 char buf[MSG_SIZ], *engineName;
9928 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
9929 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
9930 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
9932 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
9933 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
9934 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
9935 ParseArgsFromString(buf);
9941 char *recentEngines;
9944 RecentEngineEvent (int nr)
9947 // SwapEngines(1); // bump first to second
9948 // ReplaceEngine(&second, 1); // and load it there
9949 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
9950 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
9951 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
9952 ReplaceEngine(&first, 0);
9953 FloatToFront(&appData.recentEngineList, command[n]);
9958 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
9959 { // determine players from game number
9960 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
9962 if(appData.tourneyType == 0) {
9963 roundsPerCycle = (nPlayers - 1) | 1;
9964 pairingsPerRound = nPlayers / 2;
9965 } else if(appData.tourneyType > 0) {
9966 roundsPerCycle = nPlayers - appData.tourneyType;
9967 pairingsPerRound = appData.tourneyType;
9969 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
9970 gamesPerCycle = gamesPerRound * roundsPerCycle;
9971 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
9972 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
9973 curRound = nr / gamesPerRound; nr %= gamesPerRound;
9974 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
9975 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
9976 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
9978 if(appData.cycleSync) *syncInterval = gamesPerCycle;
9979 if(appData.roundSync) *syncInterval = gamesPerRound;
9981 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
9983 if(appData.tourneyType == 0) {
9984 if(curPairing == (nPlayers-1)/2 ) {
9985 *whitePlayer = curRound;
9986 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
9988 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
9989 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
9990 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
9991 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
9993 } else if(appData.tourneyType > 1) {
9994 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
9995 *whitePlayer = curRound + appData.tourneyType;
9996 } else if(appData.tourneyType > 0) {
9997 *whitePlayer = curPairing;
9998 *blackPlayer = curRound + appData.tourneyType;
10001 // take care of white/black alternation per round.
10002 // For cycles and games this is already taken care of by default, derived from matchGame!
10003 return curRound & 1;
10007 NextTourneyGame (int nr, int *swapColors)
10008 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
10010 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers;
10012 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
10013 tf = fopen(appData.tourneyFile, "r");
10014 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
10015 ParseArgsFromFile(tf); fclose(tf);
10016 InitTimeControls(); // TC might be altered from tourney file
10018 nPlayers = CountPlayers(appData.participants); // count participants
10019 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
10020 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
10023 p = q = appData.results;
10024 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
10025 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
10026 DisplayMessage(_("Waiting for other game(s)"),"");
10027 waitingForGame = TRUE;
10028 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
10031 waitingForGame = FALSE;
10034 if(appData.tourneyType < 0) {
10035 if(nr>=0 && !pairingReceived) {
10037 if(pairing.pr == NoProc) {
10038 if(!appData.pairingEngine[0]) {
10039 DisplayFatalError(_("No pairing engine specified"), 0, 1);
10042 StartChessProgram(&pairing); // starts the pairing engine
10044 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
10045 SendToProgram(buf, &pairing);
10046 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
10047 SendToProgram(buf, &pairing);
10048 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
10050 pairingReceived = 0; // ... so we continue here
10052 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
10053 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
10054 matchGame = 1; roundNr = nr / syncInterval + 1;
10057 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
10059 // redefine engines, engine dir, etc.
10060 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10061 if(first.pr == NoProc) {
10062 SetPlayer(whitePlayer, appData.participants); // find white player amongst it, and parse its engine line
10063 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
10065 if(second.pr == NoProc) {
10067 SetPlayer(blackPlayer, appData.participants); // find black player amongst it, and parse its engine line
10068 SwapEngines(1); // and make that valid for second engine by swapping
10069 InitEngine(&second, 1);
10071 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
10072 UpdateLogos(FALSE); // leave display to ModeHiglight()
10078 { // performs game initialization that does not invoke engines, and then tries to start the game
10079 int res, firstWhite, swapColors = 0;
10080 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
10081 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
10083 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
10084 if(strcmp(buf, currentDebugFile)) { // name has changed
10085 FILE *f = fopen(buf, "w");
10086 if(f) { // if opening the new file failed, just keep using the old one
10087 ASSIGN(currentDebugFile, buf);
10091 if(appData.serverFileName) {
10092 if(serverFP) fclose(serverFP);
10093 serverFP = fopen(appData.serverFileName, "w");
10094 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
10095 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
10099 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
10100 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
10101 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
10102 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
10103 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
10104 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
10105 Reset(FALSE, first.pr != NoProc);
10106 res = LoadGameOrPosition(matchGame); // setup game
10107 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
10108 if(!res) return; // abort when bad game/pos file
10109 TwoMachinesEvent();
10113 UserAdjudicationEvent (int result)
10115 ChessMove gameResult = GameIsDrawn;
10118 gameResult = WhiteWins;
10120 else if( result < 0 ) {
10121 gameResult = BlackWins;
10124 if( gameMode == TwoMachinesPlay ) {
10125 GameEnds( gameResult, "User adjudication", GE_XBOARD );
10130 // [HGM] save: calculate checksum of game to make games easily identifiable
10132 StringCheckSum (char *s)
10135 if(s==NULL) return 0;
10136 while(*s) i = i*259 + *s++;
10144 for(i=backwardMostMove; i<forwardMostMove; i++) {
10145 sum += pvInfoList[i].depth;
10146 sum += StringCheckSum(parseList[i]);
10147 sum += StringCheckSum(commentList[i]);
10150 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
10151 return sum + StringCheckSum(commentList[i]);
10152 } // end of save patch
10155 GameEnds (ChessMove result, char *resultDetails, int whosays)
10157 GameMode nextGameMode;
10159 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
10161 if(endingGame) return; /* [HGM] crash: forbid recursion */
10163 if(twoBoards) { // [HGM] dual: switch back to one board
10164 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
10165 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
10167 if (appData.debugMode) {
10168 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
10169 result, resultDetails ? resultDetails : "(null)", whosays);
10172 fromX = fromY = -1; // [HGM] abort any move the user is entering.
10174 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
10175 /* If we are playing on ICS, the server decides when the
10176 game is over, but the engine can offer to draw, claim
10180 if (appData.zippyPlay && first.initDone) {
10181 if (result == GameIsDrawn) {
10182 /* In case draw still needs to be claimed */
10183 SendToICS(ics_prefix);
10184 SendToICS("draw\n");
10185 } else if (StrCaseStr(resultDetails, "resign")) {
10186 SendToICS(ics_prefix);
10187 SendToICS("resign\n");
10191 endingGame = 0; /* [HGM] crash */
10195 /* If we're loading the game from a file, stop */
10196 if (whosays == GE_FILE) {
10197 (void) StopLoadGameTimer();
10201 /* Cancel draw offers */
10202 first.offeredDraw = second.offeredDraw = 0;
10204 /* If this is an ICS game, only ICS can really say it's done;
10205 if not, anyone can. */
10206 isIcsGame = (gameMode == IcsPlayingWhite ||
10207 gameMode == IcsPlayingBlack ||
10208 gameMode == IcsObserving ||
10209 gameMode == IcsExamining);
10211 if (!isIcsGame || whosays == GE_ICS) {
10212 /* OK -- not an ICS game, or ICS said it was done */
10214 if (!isIcsGame && !appData.noChessProgram)
10215 SetUserThinkingEnables();
10217 /* [HGM] if a machine claims the game end we verify this claim */
10218 if(gameMode == TwoMachinesPlay && appData.testClaims) {
10219 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
10221 ChessMove trueResult = (ChessMove) -1;
10223 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
10224 first.twoMachinesColor[0] :
10225 second.twoMachinesColor[0] ;
10227 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
10228 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
10229 /* [HGM] verify: engine mate claims accepted if they were flagged */
10230 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
10232 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
10233 /* [HGM] verify: engine mate claims accepted if they were flagged */
10234 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
10236 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
10237 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
10240 // now verify win claims, but not in drop games, as we don't understand those yet
10241 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10242 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
10243 (result == WhiteWins && claimer == 'w' ||
10244 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
10245 if (appData.debugMode) {
10246 fprintf(debugFP, "result=%d sp=%d move=%d\n",
10247 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
10249 if(result != trueResult) {
10250 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
10251 result = claimer == 'w' ? BlackWins : WhiteWins;
10252 resultDetails = buf;
10255 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
10256 && (forwardMostMove <= backwardMostMove ||
10257 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
10258 (claimer=='b')==(forwardMostMove&1))
10260 /* [HGM] verify: draws that were not flagged are false claims */
10261 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
10262 result = claimer == 'w' ? BlackWins : WhiteWins;
10263 resultDetails = buf;
10265 /* (Claiming a loss is accepted no questions asked!) */
10267 /* [HGM] bare: don't allow bare King to win */
10268 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10269 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10270 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
10271 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
10272 && result != GameIsDrawn)
10273 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
10274 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
10275 int p = (signed char)boards[forwardMostMove][i][j] - color;
10276 if(p >= 0 && p <= (int)WhiteKing) k++;
10278 if (appData.debugMode) {
10279 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
10280 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
10283 result = GameIsDrawn;
10284 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
10285 resultDetails = buf;
10291 if(serverMoves != NULL && !loadFlag) { char c = '=';
10292 if(result==WhiteWins) c = '+';
10293 if(result==BlackWins) c = '-';
10294 if(resultDetails != NULL)
10295 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
10297 if (resultDetails != NULL) {
10298 gameInfo.result = result;
10299 gameInfo.resultDetails = StrSave(resultDetails);
10301 /* display last move only if game was not loaded from file */
10302 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
10303 DisplayMove(currentMove - 1);
10305 if (forwardMostMove != 0) {
10306 if (gameMode != PlayFromGameFile && gameMode != EditGame
10307 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
10309 if (*appData.saveGameFile != NULLCHAR) {
10310 SaveGameToFile(appData.saveGameFile, TRUE);
10311 } else if (appData.autoSaveGames) {
10314 if (*appData.savePositionFile != NULLCHAR) {
10315 SavePositionToFile(appData.savePositionFile);
10320 /* Tell program how game ended in case it is learning */
10321 /* [HGM] Moved this to after saving the PGN, just in case */
10322 /* engine died and we got here through time loss. In that */
10323 /* case we will get a fatal error writing the pipe, which */
10324 /* would otherwise lose us the PGN. */
10325 /* [HGM] crash: not needed anymore, but doesn't hurt; */
10326 /* output during GameEnds should never be fatal anymore */
10327 if (gameMode == MachinePlaysWhite ||
10328 gameMode == MachinePlaysBlack ||
10329 gameMode == TwoMachinesPlay ||
10330 gameMode == IcsPlayingWhite ||
10331 gameMode == IcsPlayingBlack ||
10332 gameMode == BeginningOfGame) {
10334 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
10336 if (first.pr != NoProc) {
10337 SendToProgram(buf, &first);
10339 if (second.pr != NoProc &&
10340 gameMode == TwoMachinesPlay) {
10341 SendToProgram(buf, &second);
10346 if (appData.icsActive) {
10347 if (appData.quietPlay &&
10348 (gameMode == IcsPlayingWhite ||
10349 gameMode == IcsPlayingBlack)) {
10350 SendToICS(ics_prefix);
10351 SendToICS("set shout 1\n");
10353 nextGameMode = IcsIdle;
10354 ics_user_moved = FALSE;
10355 /* clean up premove. It's ugly when the game has ended and the
10356 * premove highlights are still on the board.
10359 gotPremove = FALSE;
10360 ClearPremoveHighlights();
10361 DrawPosition(FALSE, boards[currentMove]);
10363 if (whosays == GE_ICS) {
10366 if (gameMode == IcsPlayingWhite)
10368 else if(gameMode == IcsPlayingBlack)
10369 PlayIcsLossSound();
10372 if (gameMode == IcsPlayingBlack)
10374 else if(gameMode == IcsPlayingWhite)
10375 PlayIcsLossSound();
10378 PlayIcsDrawSound();
10381 PlayIcsUnfinishedSound();
10384 } else if (gameMode == EditGame ||
10385 gameMode == PlayFromGameFile ||
10386 gameMode == AnalyzeMode ||
10387 gameMode == AnalyzeFile) {
10388 nextGameMode = gameMode;
10390 nextGameMode = EndOfGame;
10395 nextGameMode = gameMode;
10398 if (appData.noChessProgram) {
10399 gameMode = nextGameMode;
10401 endingGame = 0; /* [HGM] crash */
10406 /* Put first chess program into idle state */
10407 if (first.pr != NoProc &&
10408 (gameMode == MachinePlaysWhite ||
10409 gameMode == MachinePlaysBlack ||
10410 gameMode == TwoMachinesPlay ||
10411 gameMode == IcsPlayingWhite ||
10412 gameMode == IcsPlayingBlack ||
10413 gameMode == BeginningOfGame)) {
10414 SendToProgram("force\n", &first);
10415 if (first.usePing) {
10417 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
10418 SendToProgram(buf, &first);
10421 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10422 /* Kill off first chess program */
10423 if (first.isr != NULL)
10424 RemoveInputSource(first.isr);
10427 if (first.pr != NoProc) {
10429 DoSleep( appData.delayBeforeQuit );
10430 SendToProgram("quit\n", &first);
10431 DoSleep( appData.delayAfterQuit );
10432 DestroyChildProcess(first.pr, first.useSigterm);
10436 if (second.reuse) {
10437 /* Put second chess program into idle state */
10438 if (second.pr != NoProc &&
10439 gameMode == TwoMachinesPlay) {
10440 SendToProgram("force\n", &second);
10441 if (second.usePing) {
10443 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
10444 SendToProgram(buf, &second);
10447 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10448 /* Kill off second chess program */
10449 if (second.isr != NULL)
10450 RemoveInputSource(second.isr);
10453 if (second.pr != NoProc) {
10454 DoSleep( appData.delayBeforeQuit );
10455 SendToProgram("quit\n", &second);
10456 DoSleep( appData.delayAfterQuit );
10457 DestroyChildProcess(second.pr, second.useSigterm);
10459 second.pr = NoProc;
10462 if (matchMode && (gameMode == TwoMachinesPlay || waitingForGame && exiting)) {
10463 char resChar = '=';
10467 if (first.twoMachinesColor[0] == 'w') {
10470 second.matchWins++;
10475 if (first.twoMachinesColor[0] == 'b') {
10478 second.matchWins++;
10481 case GameUnfinished:
10487 if(waitingForGame) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
10488 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
10489 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
10490 ReserveGame(nextGame, resChar); // sets nextGame
10491 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
10492 else ranking = strdup("busy"); //suppress popup when aborted but not finished
10493 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
10495 if (nextGame <= appData.matchGames && !abortMatch) {
10496 gameMode = nextGameMode;
10497 matchGame = nextGame; // this will be overruled in tourney mode!
10498 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
10499 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
10500 endingGame = 0; /* [HGM] crash */
10503 gameMode = nextGameMode;
10504 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
10505 first.tidy, second.tidy,
10506 first.matchWins, second.matchWins,
10507 appData.matchGames - (first.matchWins + second.matchWins));
10508 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
10509 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
10510 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
10511 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
10512 first.twoMachinesColor = "black\n";
10513 second.twoMachinesColor = "white\n";
10515 first.twoMachinesColor = "white\n";
10516 second.twoMachinesColor = "black\n";
10520 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
10521 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
10523 gameMode = nextGameMode;
10525 endingGame = 0; /* [HGM] crash */
10526 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
10527 if(matchMode == TRUE) { // match through command line: exit with or without popup
10529 ToNrEvent(forwardMostMove);
10530 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
10532 } else DisplayFatalError(buf, 0, 0);
10533 } else { // match through menu; just stop, with or without popup
10534 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10537 if(strcmp(ranking, "busy")) DisplayNote(ranking);
10538 } else DisplayNote(buf);
10540 if(ranking) free(ranking);
10544 /* Assumes program was just initialized (initString sent).
10545 Leaves program in force mode. */
10547 FeedMovesToProgram (ChessProgramState *cps, int upto)
10551 if (appData.debugMode)
10552 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
10553 startedFromSetupPosition ? "position and " : "",
10554 backwardMostMove, upto, cps->which);
10555 if(currentlyInitializedVariant != gameInfo.variant) {
10557 // [HGM] variantswitch: make engine aware of new variant
10558 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
10559 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
10560 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
10561 SendToProgram(buf, cps);
10562 currentlyInitializedVariant = gameInfo.variant;
10564 SendToProgram("force\n", cps);
10565 if (startedFromSetupPosition) {
10566 SendBoard(cps, backwardMostMove);
10567 if (appData.debugMode) {
10568 fprintf(debugFP, "feedMoves\n");
10571 for (i = backwardMostMove; i < upto; i++) {
10572 SendMoveToProgram(i, cps);
10578 ResurrectChessProgram ()
10580 /* The chess program may have exited.
10581 If so, restart it and feed it all the moves made so far. */
10582 static int doInit = 0;
10584 if (appData.noChessProgram) return 1;
10586 if(matchMode && appData.tourneyFile[0]) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
10587 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit
10588 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
10589 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
10591 if (first.pr != NoProc) return 1;
10592 StartChessProgram(&first);
10594 InitChessProgram(&first, FALSE);
10595 FeedMovesToProgram(&first, currentMove);
10597 if (!first.sendTime) {
10598 /* can't tell gnuchess what its clock should read,
10599 so we bow to its notion. */
10601 timeRemaining[0][currentMove] = whiteTimeRemaining;
10602 timeRemaining[1][currentMove] = blackTimeRemaining;
10605 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
10606 appData.icsEngineAnalyze) && first.analysisSupport) {
10607 SendToProgram("analyze\n", &first);
10608 first.analyzing = TRUE;
10614 * Button procedures
10617 Reset (int redraw, int init)
10621 if (appData.debugMode) {
10622 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
10623 redraw, init, gameMode);
10625 CleanupTail(); // [HGM] vari: delete any stored variations
10626 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
10627 pausing = pauseExamInvalid = FALSE;
10628 startedFromSetupPosition = blackPlaysFirst = FALSE;
10630 whiteFlag = blackFlag = FALSE;
10631 userOfferedDraw = FALSE;
10632 hintRequested = bookRequested = FALSE;
10633 first.maybeThinking = FALSE;
10634 second.maybeThinking = FALSE;
10635 first.bookSuspend = FALSE; // [HGM] book
10636 second.bookSuspend = FALSE;
10637 thinkOutput[0] = NULLCHAR;
10638 lastHint[0] = NULLCHAR;
10639 ClearGameInfo(&gameInfo);
10640 gameInfo.variant = StringToVariant(appData.variant);
10641 ics_user_moved = ics_clock_paused = FALSE;
10642 ics_getting_history = H_FALSE;
10644 white_holding[0] = black_holding[0] = NULLCHAR;
10645 ClearProgramStats();
10646 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
10650 flipView = appData.flipView;
10651 ClearPremoveHighlights();
10652 gotPremove = FALSE;
10653 alarmSounded = FALSE;
10655 GameEnds(EndOfFile, NULL, GE_PLAYER);
10656 if(appData.serverMovesName != NULL) {
10657 /* [HGM] prepare to make moves file for broadcasting */
10658 clock_t t = clock();
10659 if(serverMoves != NULL) fclose(serverMoves);
10660 serverMoves = fopen(appData.serverMovesName, "r");
10661 if(serverMoves != NULL) {
10662 fclose(serverMoves);
10663 /* delay 15 sec before overwriting, so all clients can see end */
10664 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
10666 serverMoves = fopen(appData.serverMovesName, "w");
10670 gameMode = BeginningOfGame;
10672 if(appData.icsActive) gameInfo.variant = VariantNormal;
10673 currentMove = forwardMostMove = backwardMostMove = 0;
10674 MarkTargetSquares(1);
10675 InitPosition(redraw);
10676 for (i = 0; i < MAX_MOVES; i++) {
10677 if (commentList[i] != NULL) {
10678 free(commentList[i]);
10679 commentList[i] = NULL;
10683 timeRemaining[0][0] = whiteTimeRemaining;
10684 timeRemaining[1][0] = blackTimeRemaining;
10686 if (first.pr == NoProc) {
10687 StartChessProgram(&first);
10690 InitChessProgram(&first, startedFromSetupPosition);
10693 DisplayMessage("", "");
10694 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10695 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
10699 AutoPlayGameLoop ()
10702 if (!AutoPlayOneMove())
10704 if (matchMode || appData.timeDelay == 0)
10706 if (appData.timeDelay < 0)
10708 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
10717 int fromX, fromY, toX, toY;
10719 if (appData.debugMode) {
10720 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
10723 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
10726 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
10727 pvInfoList[currentMove].depth = programStats.depth;
10728 pvInfoList[currentMove].score = programStats.score;
10729 pvInfoList[currentMove].time = 0;
10730 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
10733 if (currentMove >= forwardMostMove) {
10734 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
10735 // gameMode = EndOfGame;
10736 // ModeHighlight();
10738 /* [AS] Clear current move marker at the end of a game */
10739 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
10744 toX = moveList[currentMove][2] - AAA;
10745 toY = moveList[currentMove][3] - ONE;
10747 if (moveList[currentMove][1] == '@') {
10748 if (appData.highlightLastMove) {
10749 SetHighlights(-1, -1, toX, toY);
10752 fromX = moveList[currentMove][0] - AAA;
10753 fromY = moveList[currentMove][1] - ONE;
10755 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
10757 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
10759 if (appData.highlightLastMove) {
10760 SetHighlights(fromX, fromY, toX, toY);
10763 DisplayMove(currentMove);
10764 SendMoveToProgram(currentMove++, &first);
10765 DisplayBothClocks();
10766 DrawPosition(FALSE, boards[currentMove]);
10767 // [HGM] PV info: always display, routine tests if empty
10768 DisplayComment(currentMove - 1, commentList[currentMove]);
10774 LoadGameOneMove (ChessMove readAhead)
10776 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
10777 char promoChar = NULLCHAR;
10778 ChessMove moveType;
10779 char move[MSG_SIZ];
10782 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
10783 gameMode != AnalyzeMode && gameMode != Training) {
10788 yyboardindex = forwardMostMove;
10789 if (readAhead != EndOfFile) {
10790 moveType = readAhead;
10792 if (gameFileFP == NULL)
10794 moveType = (ChessMove) Myylex();
10798 switch (moveType) {
10800 if (appData.debugMode)
10801 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10804 /* append the comment but don't display it */
10805 AppendComment(currentMove, p, FALSE);
10808 case WhiteCapturesEnPassant:
10809 case BlackCapturesEnPassant:
10810 case WhitePromotion:
10811 case BlackPromotion:
10812 case WhiteNonPromotion:
10813 case BlackNonPromotion:
10815 case WhiteKingSideCastle:
10816 case WhiteQueenSideCastle:
10817 case BlackKingSideCastle:
10818 case BlackQueenSideCastle:
10819 case WhiteKingSideCastleWild:
10820 case WhiteQueenSideCastleWild:
10821 case BlackKingSideCastleWild:
10822 case BlackQueenSideCastleWild:
10824 case WhiteHSideCastleFR:
10825 case WhiteASideCastleFR:
10826 case BlackHSideCastleFR:
10827 case BlackASideCastleFR:
10829 if (appData.debugMode)
10830 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
10831 fromX = currentMoveString[0] - AAA;
10832 fromY = currentMoveString[1] - ONE;
10833 toX = currentMoveString[2] - AAA;
10834 toY = currentMoveString[3] - ONE;
10835 promoChar = currentMoveString[4];
10840 if (appData.debugMode)
10841 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
10842 fromX = moveType == WhiteDrop ?
10843 (int) CharToPiece(ToUpper(currentMoveString[0])) :
10844 (int) CharToPiece(ToLower(currentMoveString[0]));
10846 toX = currentMoveString[2] - AAA;
10847 toY = currentMoveString[3] - ONE;
10853 case GameUnfinished:
10854 if (appData.debugMode)
10855 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
10856 p = strchr(yy_text, '{');
10857 if (p == NULL) p = strchr(yy_text, '(');
10860 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
10862 q = strchr(p, *p == '{' ? '}' : ')');
10863 if (q != NULL) *q = NULLCHAR;
10866 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10867 GameEnds(moveType, p, GE_FILE);
10869 if (cmailMsgLoaded) {
10871 flipView = WhiteOnMove(currentMove);
10872 if (moveType == GameUnfinished) flipView = !flipView;
10873 if (appData.debugMode)
10874 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
10879 if (appData.debugMode)
10880 fprintf(debugFP, "Parser hit end of file\n");
10881 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10887 if (WhiteOnMove(currentMove)) {
10888 GameEnds(BlackWins, "Black mates", GE_FILE);
10890 GameEnds(WhiteWins, "White mates", GE_FILE);
10894 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10900 case MoveNumberOne:
10901 if (lastLoadGameStart == GNUChessGame) {
10902 /* GNUChessGames have numbers, but they aren't move numbers */
10903 if (appData.debugMode)
10904 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10905 yy_text, (int) moveType);
10906 return LoadGameOneMove(EndOfFile); /* tail recursion */
10908 /* else fall thru */
10913 /* Reached start of next game in file */
10914 if (appData.debugMode)
10915 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
10916 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10922 if (WhiteOnMove(currentMove)) {
10923 GameEnds(BlackWins, "Black mates", GE_FILE);
10925 GameEnds(WhiteWins, "White mates", GE_FILE);
10929 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10935 case PositionDiagram: /* should not happen; ignore */
10936 case ElapsedTime: /* ignore */
10937 case NAG: /* ignore */
10938 if (appData.debugMode)
10939 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10940 yy_text, (int) moveType);
10941 return LoadGameOneMove(EndOfFile); /* tail recursion */
10944 if (appData.testLegality) {
10945 if (appData.debugMode)
10946 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10947 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10948 (forwardMostMove / 2) + 1,
10949 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10950 DisplayError(move, 0);
10953 if (appData.debugMode)
10954 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10955 yy_text, currentMoveString);
10956 fromX = currentMoveString[0] - AAA;
10957 fromY = currentMoveString[1] - ONE;
10958 toX = currentMoveString[2] - AAA;
10959 toY = currentMoveString[3] - ONE;
10960 promoChar = currentMoveString[4];
10964 case AmbiguousMove:
10965 if (appData.debugMode)
10966 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10967 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10968 (forwardMostMove / 2) + 1,
10969 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10970 DisplayError(move, 0);
10975 case ImpossibleMove:
10976 if (appData.debugMode)
10977 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10978 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10979 (forwardMostMove / 2) + 1,
10980 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10981 DisplayError(move, 0);
10987 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10988 DrawPosition(FALSE, boards[currentMove]);
10989 DisplayBothClocks();
10990 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10991 DisplayComment(currentMove - 1, commentList[currentMove]);
10993 (void) StopLoadGameTimer();
10995 cmailOldMove = forwardMostMove;
10998 /* currentMoveString is set as a side-effect of yylex */
11000 thinkOutput[0] = NULLCHAR;
11001 MakeMove(fromX, fromY, toX, toY, promoChar);
11002 currentMove = forwardMostMove;
11007 /* Load the nth game from the given file */
11009 LoadGameFromFile (char *filename, int n, char *title, int useList)
11014 if (strcmp(filename, "-") == 0) {
11018 f = fopen(filename, "rb");
11020 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11021 DisplayError(buf, errno);
11025 if (fseek(f, 0, 0) == -1) {
11026 /* f is not seekable; probably a pipe */
11029 if (useList && n == 0) {
11030 int error = GameListBuild(f);
11032 DisplayError(_("Cannot build game list"), error);
11033 } else if (!ListEmpty(&gameList) &&
11034 ((ListGame *) gameList.tailPred)->number > 1) {
11035 GameListPopUp(f, title);
11042 return LoadGame(f, n, title, FALSE);
11047 MakeRegisteredMove ()
11049 int fromX, fromY, toX, toY;
11051 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11052 switch (cmailMoveType[lastLoadGameNumber - 1]) {
11055 if (appData.debugMode)
11056 fprintf(debugFP, "Restoring %s for game %d\n",
11057 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11059 thinkOutput[0] = NULLCHAR;
11060 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
11061 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
11062 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
11063 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
11064 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
11065 promoChar = cmailMove[lastLoadGameNumber - 1][4];
11066 MakeMove(fromX, fromY, toX, toY, promoChar);
11067 ShowMove(fromX, fromY, toX, toY);
11069 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11076 if (WhiteOnMove(currentMove)) {
11077 GameEnds(BlackWins, "Black mates", GE_PLAYER);
11079 GameEnds(WhiteWins, "White mates", GE_PLAYER);
11084 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
11091 if (WhiteOnMove(currentMove)) {
11092 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11094 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11099 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11110 /* Wrapper around LoadGame for use when a Cmail message is loaded */
11112 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
11116 if (gameNumber > nCmailGames) {
11117 DisplayError(_("No more games in this message"), 0);
11120 if (f == lastLoadGameFP) {
11121 int offset = gameNumber - lastLoadGameNumber;
11123 cmailMsg[0] = NULLCHAR;
11124 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11125 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11126 nCmailMovesRegistered--;
11128 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11129 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
11130 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
11133 if (! RegisterMove()) return FALSE;
11137 retVal = LoadGame(f, gameNumber, title, useList);
11139 /* Make move registered during previous look at this game, if any */
11140 MakeRegisteredMove();
11142 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
11143 commentList[currentMove]
11144 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
11145 DisplayComment(currentMove - 1, commentList[currentMove]);
11151 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
11153 ReloadGame (int offset)
11155 int gameNumber = lastLoadGameNumber + offset;
11156 if (lastLoadGameFP == NULL) {
11157 DisplayError(_("No game has been loaded yet"), 0);
11160 if (gameNumber <= 0) {
11161 DisplayError(_("Can't back up any further"), 0);
11164 if (cmailMsgLoaded) {
11165 return CmailLoadGame(lastLoadGameFP, gameNumber,
11166 lastLoadGameTitle, lastLoadGameUseList);
11168 return LoadGame(lastLoadGameFP, gameNumber,
11169 lastLoadGameTitle, lastLoadGameUseList);
11173 int keys[EmptySquare+1];
11176 PositionMatches (Board b1, Board b2)
11179 switch(appData.searchMode) {
11180 case 1: return CompareWithRights(b1, b2);
11182 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11183 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
11187 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11188 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
11189 sum += keys[b1[r][f]] - keys[b2[r][f]];
11193 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11194 sum += keys[b1[r][f]] - keys[b2[r][f]];
11206 int pieceList[256], quickBoard[256];
11207 ChessSquare pieceType[256] = { EmptySquare };
11208 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
11209 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
11210 int soughtTotal, turn;
11211 Boolean epOK, flipSearch;
11214 unsigned char piece, to;
11217 #define DSIZE (250000)
11219 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
11220 Move *moveDatabase = initialSpace;
11221 unsigned int movePtr, dataSize = DSIZE;
11224 MakePieceList (Board board, int *counts)
11226 int r, f, n=Q_PROMO, total=0;
11227 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
11228 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11229 int sq = f + (r<<4);
11230 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
11231 quickBoard[sq] = ++n;
11233 pieceType[n] = board[r][f];
11234 counts[board[r][f]]++;
11235 if(board[r][f] == WhiteKing) pieceList[1] = n; else
11236 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
11240 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
11245 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
11247 int sq = fromX + (fromY<<4);
11248 int piece = quickBoard[sq];
11249 quickBoard[sq] = 0;
11250 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
11251 if(piece == pieceList[1] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11252 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
11253 moveDatabase[movePtr++].piece = Q_WCASTL;
11254 quickBoard[sq] = piece;
11255 piece = quickBoard[from]; quickBoard[from] = 0;
11256 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11258 if(piece == pieceList[2] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11259 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
11260 moveDatabase[movePtr++].piece = Q_BCASTL;
11261 quickBoard[sq] = piece;
11262 piece = quickBoard[from]; quickBoard[from] = 0;
11263 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11265 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
11266 quickBoard[(fromY<<4)+toX] = 0;
11267 moveDatabase[movePtr].piece = Q_EP;
11268 moveDatabase[movePtr++].to = (fromY<<4)+toX;
11269 moveDatabase[movePtr].to = sq;
11271 if(promoPiece != pieceType[piece]) {
11272 moveDatabase[movePtr++].piece = Q_PROMO;
11273 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
11275 moveDatabase[movePtr].piece = piece;
11276 quickBoard[sq] = piece;
11281 PackGame (Board board)
11283 Move *newSpace = NULL;
11284 moveDatabase[movePtr].piece = 0; // terminate previous game
11285 if(movePtr > dataSize) {
11286 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
11287 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
11288 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
11291 Move *p = moveDatabase, *q = newSpace;
11292 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
11293 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
11294 moveDatabase = newSpace;
11295 } else { // calloc failed, we must be out of memory. Too bad...
11296 dataSize = 0; // prevent calloc events for all subsequent games
11297 return 0; // and signal this one isn't cached
11301 MakePieceList(board, counts);
11306 QuickCompare (Board board, int *minCounts, int *maxCounts)
11307 { // compare according to search mode
11309 switch(appData.searchMode)
11311 case 1: // exact position match
11312 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
11313 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11314 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11317 case 2: // can have extra material on empty squares
11318 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11319 if(board[r][f] == EmptySquare) continue;
11320 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11323 case 3: // material with exact Pawn structure
11324 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11325 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
11326 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11327 } // fall through to material comparison
11328 case 4: // exact material
11329 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
11331 case 6: // material range with given imbalance
11332 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
11333 // fall through to range comparison
11334 case 5: // material range
11335 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
11341 QuickScan (Board board, Move *move)
11342 { // reconstruct game,and compare all positions in it
11343 int cnt=0, stretch=0, total = MakePieceList(board, counts);
11345 int piece = move->piece;
11346 int to = move->to, from = pieceList[piece];
11347 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
11348 if(!piece) return -1;
11349 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
11350 piece = (++move)->piece;
11351 from = pieceList[piece];
11352 counts[pieceType[piece]]--;
11353 pieceType[piece] = (ChessSquare) move->to;
11354 counts[move->to]++;
11355 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
11356 counts[pieceType[quickBoard[to]]]--;
11357 quickBoard[to] = 0; total--;
11360 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
11361 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
11362 from = pieceList[piece]; // so this must be King
11363 quickBoard[from] = 0;
11364 quickBoard[to] = piece;
11365 pieceList[piece] = to;
11370 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
11371 if((total -= (quickBoard[to] != 0)) < soughtTotal) return -1; // piece count dropped below what we search for
11372 quickBoard[from] = 0;
11373 quickBoard[to] = piece;
11374 pieceList[piece] = to;
11376 if(QuickCompare(soughtBoard, minSought, maxSought) ||
11377 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
11378 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
11379 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
11381 static int lastCounts[EmptySquare+1];
11383 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
11384 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
11385 } else stretch = 0;
11386 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) return cnt + 1 - stretch;
11395 flipSearch = FALSE;
11396 CopyBoard(soughtBoard, boards[currentMove]);
11397 soughtTotal = MakePieceList(soughtBoard, maxSought);
11398 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
11399 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
11400 CopyBoard(reverseBoard, boards[currentMove]);
11401 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11402 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
11403 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
11404 reverseBoard[r][f] = piece;
11406 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
11407 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
11408 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
11409 || (boards[currentMove][CASTLING][2] == NoRights ||
11410 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
11411 && (boards[currentMove][CASTLING][5] == NoRights ||
11412 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
11415 CopyBoard(flipBoard, soughtBoard);
11416 CopyBoard(rotateBoard, reverseBoard);
11417 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11418 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
11419 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
11422 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
11423 if(appData.searchMode >= 5) {
11424 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
11425 MakePieceList(soughtBoard, minSought);
11426 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
11428 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
11429 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
11432 GameInfo dummyInfo;
11435 GameContainsPosition (FILE *f, ListGame *lg)
11437 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
11438 int fromX, fromY, toX, toY;
11440 static int initDone=FALSE;
11442 // weed out games based on numerical tag comparison
11443 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
11444 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
11445 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
11446 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
11448 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
11451 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen);
11452 else CopyBoard(boards[scratch], initialPosition); // default start position
11455 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
11456 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
11459 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11460 fseek(f, lg->offset, 0);
11463 yyboardindex = scratch;
11464 quickFlag = plyNr+1;
11469 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
11475 if(plyNr) return -1; // after we have seen moves, this is for new game
11478 case AmbiguousMove: // we cannot reconstruct the game beyond these two
11479 case ImpossibleMove:
11480 case WhiteWins: // game ends here with these four
11483 case GameUnfinished:
11487 if(appData.testLegality) return -1;
11488 case WhiteCapturesEnPassant:
11489 case BlackCapturesEnPassant:
11490 case WhitePromotion:
11491 case BlackPromotion:
11492 case WhiteNonPromotion:
11493 case BlackNonPromotion:
11495 case WhiteKingSideCastle:
11496 case WhiteQueenSideCastle:
11497 case BlackKingSideCastle:
11498 case BlackQueenSideCastle:
11499 case WhiteKingSideCastleWild:
11500 case WhiteQueenSideCastleWild:
11501 case BlackKingSideCastleWild:
11502 case BlackQueenSideCastleWild:
11503 case WhiteHSideCastleFR:
11504 case WhiteASideCastleFR:
11505 case BlackHSideCastleFR:
11506 case BlackASideCastleFR:
11507 fromX = currentMoveString[0] - AAA;
11508 fromY = currentMoveString[1] - ONE;
11509 toX = currentMoveString[2] - AAA;
11510 toY = currentMoveString[3] - ONE;
11511 promoChar = currentMoveString[4];
11515 fromX = next == WhiteDrop ?
11516 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11517 (int) CharToPiece(ToLower(currentMoveString[0]));
11519 toX = currentMoveString[2] - AAA;
11520 toY = currentMoveString[3] - ONE;
11524 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
11526 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
11527 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11528 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
11529 if(appData.findMirror) {
11530 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
11531 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
11536 /* Load the nth game from open file f */
11538 LoadGame (FILE *f, int gameNumber, char *title, int useList)
11542 int gn = gameNumber;
11543 ListGame *lg = NULL;
11544 int numPGNTags = 0;
11546 GameMode oldGameMode;
11547 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
11549 if (appData.debugMode)
11550 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
11552 if (gameMode == Training )
11553 SetTrainingModeOff();
11555 oldGameMode = gameMode;
11556 if (gameMode != BeginningOfGame) {
11557 Reset(FALSE, TRUE);
11561 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
11562 fclose(lastLoadGameFP);
11566 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
11569 fseek(f, lg->offset, 0);
11570 GameListHighlight(gameNumber);
11571 pos = lg->position;
11575 DisplayError(_("Game number out of range"), 0);
11580 if (fseek(f, 0, 0) == -1) {
11581 if (f == lastLoadGameFP ?
11582 gameNumber == lastLoadGameNumber + 1 :
11586 DisplayError(_("Can't seek on game file"), 0);
11591 lastLoadGameFP = f;
11592 lastLoadGameNumber = gameNumber;
11593 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
11594 lastLoadGameUseList = useList;
11598 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
11599 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
11600 lg->gameInfo.black);
11602 } else if (*title != NULLCHAR) {
11603 if (gameNumber > 1) {
11604 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
11607 DisplayTitle(title);
11611 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
11612 gameMode = PlayFromGameFile;
11616 currentMove = forwardMostMove = backwardMostMove = 0;
11617 CopyBoard(boards[0], initialPosition);
11621 * Skip the first gn-1 games in the file.
11622 * Also skip over anything that precedes an identifiable
11623 * start of game marker, to avoid being confused by
11624 * garbage at the start of the file. Currently
11625 * recognized start of game markers are the move number "1",
11626 * the pattern "gnuchess .* game", the pattern
11627 * "^[#;%] [^ ]* game file", and a PGN tag block.
11628 * A game that starts with one of the latter two patterns
11629 * will also have a move number 1, possibly
11630 * following a position diagram.
11631 * 5-4-02: Let's try being more lenient and allowing a game to
11632 * start with an unnumbered move. Does that break anything?
11634 cm = lastLoadGameStart = EndOfFile;
11636 yyboardindex = forwardMostMove;
11637 cm = (ChessMove) Myylex();
11640 if (cmailMsgLoaded) {
11641 nCmailGames = CMAIL_MAX_GAMES - gn;
11644 DisplayError(_("Game not found in file"), 0);
11651 lastLoadGameStart = cm;
11654 case MoveNumberOne:
11655 switch (lastLoadGameStart) {
11660 case MoveNumberOne:
11662 gn--; /* count this game */
11663 lastLoadGameStart = cm;
11672 switch (lastLoadGameStart) {
11675 case MoveNumberOne:
11677 gn--; /* count this game */
11678 lastLoadGameStart = cm;
11681 lastLoadGameStart = cm; /* game counted already */
11689 yyboardindex = forwardMostMove;
11690 cm = (ChessMove) Myylex();
11691 } while (cm == PGNTag || cm == Comment);
11698 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
11699 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
11700 != CMAIL_OLD_RESULT) {
11702 cmailResult[ CMAIL_MAX_GAMES
11703 - gn - 1] = CMAIL_OLD_RESULT;
11709 /* Only a NormalMove can be at the start of a game
11710 * without a position diagram. */
11711 if (lastLoadGameStart == EndOfFile ) {
11713 lastLoadGameStart = MoveNumberOne;
11722 if (appData.debugMode)
11723 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
11725 if (cm == XBoardGame) {
11726 /* Skip any header junk before position diagram and/or move 1 */
11728 yyboardindex = forwardMostMove;
11729 cm = (ChessMove) Myylex();
11731 if (cm == EndOfFile ||
11732 cm == GNUChessGame || cm == XBoardGame) {
11733 /* Empty game; pretend end-of-file and handle later */
11738 if (cm == MoveNumberOne || cm == PositionDiagram ||
11739 cm == PGNTag || cm == Comment)
11742 } else if (cm == GNUChessGame) {
11743 if (gameInfo.event != NULL) {
11744 free(gameInfo.event);
11746 gameInfo.event = StrSave(yy_text);
11749 startedFromSetupPosition = FALSE;
11750 while (cm == PGNTag) {
11751 if (appData.debugMode)
11752 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
11753 err = ParsePGNTag(yy_text, &gameInfo);
11754 if (!err) numPGNTags++;
11756 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
11757 if(gameInfo.variant != oldVariant) {
11758 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
11759 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
11760 InitPosition(TRUE);
11761 oldVariant = gameInfo.variant;
11762 if (appData.debugMode)
11763 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
11767 if (gameInfo.fen != NULL) {
11768 Board initial_position;
11769 startedFromSetupPosition = TRUE;
11770 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
11772 DisplayError(_("Bad FEN position in file"), 0);
11775 CopyBoard(boards[0], initial_position);
11776 if (blackPlaysFirst) {
11777 currentMove = forwardMostMove = backwardMostMove = 1;
11778 CopyBoard(boards[1], initial_position);
11779 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
11780 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
11781 timeRemaining[0][1] = whiteTimeRemaining;
11782 timeRemaining[1][1] = blackTimeRemaining;
11783 if (commentList[0] != NULL) {
11784 commentList[1] = commentList[0];
11785 commentList[0] = NULL;
11788 currentMove = forwardMostMove = backwardMostMove = 0;
11790 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
11792 initialRulePlies = FENrulePlies;
11793 for( i=0; i< nrCastlingRights; i++ )
11794 initialRights[i] = initial_position[CASTLING][i];
11796 yyboardindex = forwardMostMove;
11797 free(gameInfo.fen);
11798 gameInfo.fen = NULL;
11801 yyboardindex = forwardMostMove;
11802 cm = (ChessMove) Myylex();
11804 /* Handle comments interspersed among the tags */
11805 while (cm == Comment) {
11807 if (appData.debugMode)
11808 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11810 AppendComment(currentMove, p, FALSE);
11811 yyboardindex = forwardMostMove;
11812 cm = (ChessMove) Myylex();
11816 /* don't rely on existence of Event tag since if game was
11817 * pasted from clipboard the Event tag may not exist
11819 if (numPGNTags > 0){
11821 if (gameInfo.variant == VariantNormal) {
11822 VariantClass v = StringToVariant(gameInfo.event);
11823 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
11824 if(v < VariantShogi) gameInfo.variant = v;
11827 if( appData.autoDisplayTags ) {
11828 tags = PGNTags(&gameInfo);
11829 TagsPopUp(tags, CmailMsg());
11834 /* Make something up, but don't display it now */
11839 if (cm == PositionDiagram) {
11842 Board initial_position;
11844 if (appData.debugMode)
11845 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
11847 if (!startedFromSetupPosition) {
11849 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
11850 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
11861 initial_position[i][j++] = CharToPiece(*p);
11864 while (*p == ' ' || *p == '\t' ||
11865 *p == '\n' || *p == '\r') p++;
11867 if (strncmp(p, "black", strlen("black"))==0)
11868 blackPlaysFirst = TRUE;
11870 blackPlaysFirst = FALSE;
11871 startedFromSetupPosition = TRUE;
11873 CopyBoard(boards[0], initial_position);
11874 if (blackPlaysFirst) {
11875 currentMove = forwardMostMove = backwardMostMove = 1;
11876 CopyBoard(boards[1], initial_position);
11877 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
11878 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
11879 timeRemaining[0][1] = whiteTimeRemaining;
11880 timeRemaining[1][1] = blackTimeRemaining;
11881 if (commentList[0] != NULL) {
11882 commentList[1] = commentList[0];
11883 commentList[0] = NULL;
11886 currentMove = forwardMostMove = backwardMostMove = 0;
11889 yyboardindex = forwardMostMove;
11890 cm = (ChessMove) Myylex();
11893 if (first.pr == NoProc) {
11894 StartChessProgram(&first);
11896 InitChessProgram(&first, FALSE);
11897 SendToProgram("force\n", &first);
11898 if (startedFromSetupPosition) {
11899 SendBoard(&first, forwardMostMove);
11900 if (appData.debugMode) {
11901 fprintf(debugFP, "Load Game\n");
11903 DisplayBothClocks();
11906 /* [HGM] server: flag to write setup moves in broadcast file as one */
11907 loadFlag = appData.suppressLoadMoves;
11909 while (cm == Comment) {
11911 if (appData.debugMode)
11912 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11914 AppendComment(currentMove, p, FALSE);
11915 yyboardindex = forwardMostMove;
11916 cm = (ChessMove) Myylex();
11919 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
11920 cm == WhiteWins || cm == BlackWins ||
11921 cm == GameIsDrawn || cm == GameUnfinished) {
11922 DisplayMessage("", _("No moves in game"));
11923 if (cmailMsgLoaded) {
11924 if (appData.debugMode)
11925 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
11929 DrawPosition(FALSE, boards[currentMove]);
11930 DisplayBothClocks();
11931 gameMode = EditGame;
11938 // [HGM] PV info: routine tests if comment empty
11939 if (!matchMode && (pausing || appData.timeDelay != 0)) {
11940 DisplayComment(currentMove - 1, commentList[currentMove]);
11942 if (!matchMode && appData.timeDelay != 0)
11943 DrawPosition(FALSE, boards[currentMove]);
11945 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
11946 programStats.ok_to_send = 1;
11949 /* if the first token after the PGN tags is a move
11950 * and not move number 1, retrieve it from the parser
11952 if (cm != MoveNumberOne)
11953 LoadGameOneMove(cm);
11955 /* load the remaining moves from the file */
11956 while (LoadGameOneMove(EndOfFile)) {
11957 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
11958 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
11961 /* rewind to the start of the game */
11962 currentMove = backwardMostMove;
11964 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11966 if (oldGameMode == AnalyzeFile ||
11967 oldGameMode == AnalyzeMode) {
11968 AnalyzeFileEvent();
11971 if (!matchMode && pos >= 0) {
11972 ToNrEvent(pos); // [HGM] no autoplay if selected on position
11974 if (matchMode || appData.timeDelay == 0) {
11976 } else if (appData.timeDelay > 0) {
11977 AutoPlayGameLoop();
11980 if (appData.debugMode)
11981 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
11983 loadFlag = 0; /* [HGM] true game starts */
11987 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
11989 ReloadPosition (int offset)
11991 int positionNumber = lastLoadPositionNumber + offset;
11992 if (lastLoadPositionFP == NULL) {
11993 DisplayError(_("No position has been loaded yet"), 0);
11996 if (positionNumber <= 0) {
11997 DisplayError(_("Can't back up any further"), 0);
12000 return LoadPosition(lastLoadPositionFP, positionNumber,
12001 lastLoadPositionTitle);
12004 /* Load the nth position from the given file */
12006 LoadPositionFromFile (char *filename, int n, char *title)
12011 if (strcmp(filename, "-") == 0) {
12012 return LoadPosition(stdin, n, "stdin");
12014 f = fopen(filename, "rb");
12016 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12017 DisplayError(buf, errno);
12020 return LoadPosition(f, n, title);
12025 /* Load the nth position from the given open file, and close it */
12027 LoadPosition (FILE *f, int positionNumber, char *title)
12029 char *p, line[MSG_SIZ];
12030 Board initial_position;
12031 int i, j, fenMode, pn;
12033 if (gameMode == Training )
12034 SetTrainingModeOff();
12036 if (gameMode != BeginningOfGame) {
12037 Reset(FALSE, TRUE);
12039 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
12040 fclose(lastLoadPositionFP);
12042 if (positionNumber == 0) positionNumber = 1;
12043 lastLoadPositionFP = f;
12044 lastLoadPositionNumber = positionNumber;
12045 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
12046 if (first.pr == NoProc && !appData.noChessProgram) {
12047 StartChessProgram(&first);
12048 InitChessProgram(&first, FALSE);
12050 pn = positionNumber;
12051 if (positionNumber < 0) {
12052 /* Negative position number means to seek to that byte offset */
12053 if (fseek(f, -positionNumber, 0) == -1) {
12054 DisplayError(_("Can't seek on position file"), 0);
12059 if (fseek(f, 0, 0) == -1) {
12060 if (f == lastLoadPositionFP ?
12061 positionNumber == lastLoadPositionNumber + 1 :
12062 positionNumber == 1) {
12065 DisplayError(_("Can't seek on position file"), 0);
12070 /* See if this file is FEN or old-style xboard */
12071 if (fgets(line, MSG_SIZ, f) == NULL) {
12072 DisplayError(_("Position not found in file"), 0);
12075 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
12076 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
12079 if (fenMode || line[0] == '#') pn--;
12081 /* skip positions before number pn */
12082 if (fgets(line, MSG_SIZ, f) == NULL) {
12084 DisplayError(_("Position not found in file"), 0);
12087 if (fenMode || line[0] == '#') pn--;
12092 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
12093 DisplayError(_("Bad FEN position in file"), 0);
12097 (void) fgets(line, MSG_SIZ, f);
12098 (void) fgets(line, MSG_SIZ, f);
12100 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
12101 (void) fgets(line, MSG_SIZ, f);
12102 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
12105 initial_position[i][j++] = CharToPiece(*p);
12109 blackPlaysFirst = FALSE;
12111 (void) fgets(line, MSG_SIZ, f);
12112 if (strncmp(line, "black", strlen("black"))==0)
12113 blackPlaysFirst = TRUE;
12116 startedFromSetupPosition = TRUE;
12118 CopyBoard(boards[0], initial_position);
12119 if (blackPlaysFirst) {
12120 currentMove = forwardMostMove = backwardMostMove = 1;
12121 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12122 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12123 CopyBoard(boards[1], initial_position);
12124 DisplayMessage("", _("Black to play"));
12126 currentMove = forwardMostMove = backwardMostMove = 0;
12127 DisplayMessage("", _("White to play"));
12129 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
12130 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
12131 SendToProgram("force\n", &first);
12132 SendBoard(&first, forwardMostMove);
12134 if (appData.debugMode) {
12136 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
12137 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
12138 fprintf(debugFP, "Load Position\n");
12141 if (positionNumber > 1) {
12142 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
12143 DisplayTitle(line);
12145 DisplayTitle(title);
12147 gameMode = EditGame;
12150 timeRemaining[0][1] = whiteTimeRemaining;
12151 timeRemaining[1][1] = blackTimeRemaining;
12152 DrawPosition(FALSE, boards[currentMove]);
12159 CopyPlayerNameIntoFileName (char **dest, char *src)
12161 while (*src != NULLCHAR && *src != ',') {
12166 *(*dest)++ = *src++;
12172 DefaultFileName (char *ext)
12174 static char def[MSG_SIZ];
12177 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
12179 CopyPlayerNameIntoFileName(&p, gameInfo.white);
12181 CopyPlayerNameIntoFileName(&p, gameInfo.black);
12183 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
12190 /* Save the current game to the given file */
12192 SaveGameToFile (char *filename, int append)
12196 int result, i, t,tot=0;
12198 if (strcmp(filename, "-") == 0) {
12199 return SaveGame(stdout, 0, NULL);
12201 for(i=0; i<10; i++) { // upto 10 tries
12202 f = fopen(filename, append ? "a" : "w");
12203 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
12204 if(f || errno != 13) break;
12205 DoSleep(t = 5 + random()%11); // wait 5-15 msec
12209 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12210 DisplayError(buf, errno);
12213 safeStrCpy(buf, lastMsg, MSG_SIZ);
12214 DisplayMessage(_("Waiting for access to save file"), "");
12215 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
12216 DisplayMessage(_("Saving game"), "");
12217 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
12218 result = SaveGame(f, 0, NULL);
12219 DisplayMessage(buf, "");
12226 SavePart (char *str)
12228 static char buf[MSG_SIZ];
12231 p = strchr(str, ' ');
12232 if (p == NULL) return str;
12233 strncpy(buf, str, p - str);
12234 buf[p - str] = NULLCHAR;
12238 #define PGN_MAX_LINE 75
12240 #define PGN_SIDE_WHITE 0
12241 #define PGN_SIDE_BLACK 1
12244 FindFirstMoveOutOfBook (int side)
12248 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
12249 int index = backwardMostMove;
12250 int has_book_hit = 0;
12252 if( (index % 2) != side ) {
12256 while( index < forwardMostMove ) {
12257 /* Check to see if engine is in book */
12258 int depth = pvInfoList[index].depth;
12259 int score = pvInfoList[index].score;
12265 else if( score == 0 && depth == 63 ) {
12266 in_book = 1; /* Zappa */
12268 else if( score == 2 && depth == 99 ) {
12269 in_book = 1; /* Abrok */
12272 has_book_hit += in_book;
12288 GetOutOfBookInfo (char * buf)
12292 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12294 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
12295 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
12299 if( oob[0] >= 0 || oob[1] >= 0 ) {
12300 for( i=0; i<2; i++ ) {
12304 if( i > 0 && oob[0] >= 0 ) {
12305 strcat( buf, " " );
12308 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
12309 sprintf( buf+strlen(buf), "%s%.2f",
12310 pvInfoList[idx].score >= 0 ? "+" : "",
12311 pvInfoList[idx].score / 100.0 );
12317 /* Save game in PGN style and close the file */
12319 SaveGamePGN (FILE *f)
12321 int i, offset, linelen, newblock;
12325 int movelen, numlen, blank;
12326 char move_buffer[100]; /* [AS] Buffer for move+PV info */
12328 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12330 tm = time((time_t *) NULL);
12332 PrintPGNTags(f, &gameInfo);
12334 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
12336 if (backwardMostMove > 0 || startedFromSetupPosition) {
12337 char *fen = PositionToFEN(backwardMostMove, NULL);
12338 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
12339 fprintf(f, "\n{--------------\n");
12340 PrintPosition(f, backwardMostMove);
12341 fprintf(f, "--------------}\n");
12345 /* [AS] Out of book annotation */
12346 if( appData.saveOutOfBookInfo ) {
12349 GetOutOfBookInfo( buf );
12351 if( buf[0] != '\0' ) {
12352 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
12359 i = backwardMostMove;
12363 while (i < forwardMostMove) {
12364 /* Print comments preceding this move */
12365 if (commentList[i] != NULL) {
12366 if (linelen > 0) fprintf(f, "\n");
12367 fprintf(f, "%s", commentList[i]);
12372 /* Format move number */
12374 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
12377 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
12379 numtext[0] = NULLCHAR;
12381 numlen = strlen(numtext);
12384 /* Print move number */
12385 blank = linelen > 0 && numlen > 0;
12386 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
12395 fprintf(f, "%s", numtext);
12399 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
12400 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
12403 blank = linelen > 0 && movelen > 0;
12404 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12413 fprintf(f, "%s", move_buffer);
12414 linelen += movelen;
12416 /* [AS] Add PV info if present */
12417 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
12418 /* [HGM] add time */
12419 char buf[MSG_SIZ]; int seconds;
12421 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
12427 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
12430 seconds = (seconds + 4)/10; // round to full seconds
12432 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
12434 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
12437 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
12438 pvInfoList[i].score >= 0 ? "+" : "",
12439 pvInfoList[i].score / 100.0,
12440 pvInfoList[i].depth,
12443 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
12445 /* Print score/depth */
12446 blank = linelen > 0 && movelen > 0;
12447 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12456 fprintf(f, "%s", move_buffer);
12457 linelen += movelen;
12463 /* Start a new line */
12464 if (linelen > 0) fprintf(f, "\n");
12466 /* Print comments after last move */
12467 if (commentList[i] != NULL) {
12468 fprintf(f, "%s\n", commentList[i]);
12472 if (gameInfo.resultDetails != NULL &&
12473 gameInfo.resultDetails[0] != NULLCHAR) {
12474 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
12475 PGNResult(gameInfo.result));
12477 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12481 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12485 /* Save game in old style and close the file */
12487 SaveGameOldStyle (FILE *f)
12492 tm = time((time_t *) NULL);
12494 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
12497 if (backwardMostMove > 0 || startedFromSetupPosition) {
12498 fprintf(f, "\n[--------------\n");
12499 PrintPosition(f, backwardMostMove);
12500 fprintf(f, "--------------]\n");
12505 i = backwardMostMove;
12506 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12508 while (i < forwardMostMove) {
12509 if (commentList[i] != NULL) {
12510 fprintf(f, "[%s]\n", commentList[i]);
12513 if ((i % 2) == 1) {
12514 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
12517 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
12519 if (commentList[i] != NULL) {
12523 if (i >= forwardMostMove) {
12527 fprintf(f, "%s\n", parseList[i]);
12532 if (commentList[i] != NULL) {
12533 fprintf(f, "[%s]\n", commentList[i]);
12536 /* This isn't really the old style, but it's close enough */
12537 if (gameInfo.resultDetails != NULL &&
12538 gameInfo.resultDetails[0] != NULLCHAR) {
12539 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
12540 gameInfo.resultDetails);
12542 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12549 /* Save the current game to open file f and close the file */
12551 SaveGame (FILE *f, int dummy, char *dummy2)
12553 if (gameMode == EditPosition) EditPositionDone(TRUE);
12554 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12555 if (appData.oldSaveStyle)
12556 return SaveGameOldStyle(f);
12558 return SaveGamePGN(f);
12561 /* Save the current position to the given file */
12563 SavePositionToFile (char *filename)
12568 if (strcmp(filename, "-") == 0) {
12569 return SavePosition(stdout, 0, NULL);
12571 f = fopen(filename, "a");
12573 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12574 DisplayError(buf, errno);
12577 safeStrCpy(buf, lastMsg, MSG_SIZ);
12578 DisplayMessage(_("Waiting for access to save file"), "");
12579 flock(fileno(f), LOCK_EX); // [HGM] lock
12580 DisplayMessage(_("Saving position"), "");
12581 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
12582 SavePosition(f, 0, NULL);
12583 DisplayMessage(buf, "");
12589 /* Save the current position to the given open file and close the file */
12591 SavePosition (FILE *f, int dummy, char *dummy2)
12596 if (gameMode == EditPosition) EditPositionDone(TRUE);
12597 if (appData.oldSaveStyle) {
12598 tm = time((time_t *) NULL);
12600 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
12602 fprintf(f, "[--------------\n");
12603 PrintPosition(f, currentMove);
12604 fprintf(f, "--------------]\n");
12606 fen = PositionToFEN(currentMove, NULL);
12607 fprintf(f, "%s\n", fen);
12615 ReloadCmailMsgEvent (int unregister)
12618 static char *inFilename = NULL;
12619 static char *outFilename;
12621 struct stat inbuf, outbuf;
12624 /* Any registered moves are unregistered if unregister is set, */
12625 /* i.e. invoked by the signal handler */
12627 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12628 cmailMoveRegistered[i] = FALSE;
12629 if (cmailCommentList[i] != NULL) {
12630 free(cmailCommentList[i]);
12631 cmailCommentList[i] = NULL;
12634 nCmailMovesRegistered = 0;
12637 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12638 cmailResult[i] = CMAIL_NOT_RESULT;
12642 if (inFilename == NULL) {
12643 /* Because the filenames are static they only get malloced once */
12644 /* and they never get freed */
12645 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
12646 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
12648 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
12649 sprintf(outFilename, "%s.out", appData.cmailGameName);
12652 status = stat(outFilename, &outbuf);
12654 cmailMailedMove = FALSE;
12656 status = stat(inFilename, &inbuf);
12657 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
12660 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
12661 counts the games, notes how each one terminated, etc.
12663 It would be nice to remove this kludge and instead gather all
12664 the information while building the game list. (And to keep it
12665 in the game list nodes instead of having a bunch of fixed-size
12666 parallel arrays.) Note this will require getting each game's
12667 termination from the PGN tags, as the game list builder does
12668 not process the game moves. --mann
12670 cmailMsgLoaded = TRUE;
12671 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
12673 /* Load first game in the file or popup game menu */
12674 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
12676 #endif /* !WIN32 */
12684 char string[MSG_SIZ];
12686 if ( cmailMailedMove
12687 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
12688 return TRUE; /* Allow free viewing */
12691 /* Unregister move to ensure that we don't leave RegisterMove */
12692 /* with the move registered when the conditions for registering no */
12694 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12695 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12696 nCmailMovesRegistered --;
12698 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
12700 free(cmailCommentList[lastLoadGameNumber - 1]);
12701 cmailCommentList[lastLoadGameNumber - 1] = NULL;
12705 if (cmailOldMove == -1) {
12706 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
12710 if (currentMove > cmailOldMove + 1) {
12711 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
12715 if (currentMove < cmailOldMove) {
12716 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
12720 if (forwardMostMove > currentMove) {
12721 /* Silently truncate extra moves */
12725 if ( (currentMove == cmailOldMove + 1)
12726 || ( (currentMove == cmailOldMove)
12727 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
12728 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
12729 if (gameInfo.result != GameUnfinished) {
12730 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
12733 if (commentList[currentMove] != NULL) {
12734 cmailCommentList[lastLoadGameNumber - 1]
12735 = StrSave(commentList[currentMove]);
12737 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
12739 if (appData.debugMode)
12740 fprintf(debugFP, "Saving %s for game %d\n",
12741 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12743 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
12745 f = fopen(string, "w");
12746 if (appData.oldSaveStyle) {
12747 SaveGameOldStyle(f); /* also closes the file */
12749 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
12750 f = fopen(string, "w");
12751 SavePosition(f, 0, NULL); /* also closes the file */
12753 fprintf(f, "{--------------\n");
12754 PrintPosition(f, currentMove);
12755 fprintf(f, "--------------}\n\n");
12757 SaveGame(f, 0, NULL); /* also closes the file*/
12760 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
12761 nCmailMovesRegistered ++;
12762 } else if (nCmailGames == 1) {
12763 DisplayError(_("You have not made a move yet"), 0);
12774 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
12775 FILE *commandOutput;
12776 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
12777 int nBytes = 0; /* Suppress warnings on uninitialized variables */
12783 if (! cmailMsgLoaded) {
12784 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
12788 if (nCmailGames == nCmailResults) {
12789 DisplayError(_("No unfinished games"), 0);
12793 #if CMAIL_PROHIBIT_REMAIL
12794 if (cmailMailedMove) {
12795 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);
12796 DisplayError(msg, 0);
12801 if (! (cmailMailedMove || RegisterMove())) return;
12803 if ( cmailMailedMove
12804 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
12805 snprintf(string, MSG_SIZ, partCommandString,
12806 appData.debugMode ? " -v" : "", appData.cmailGameName);
12807 commandOutput = popen(string, "r");
12809 if (commandOutput == NULL) {
12810 DisplayError(_("Failed to invoke cmail"), 0);
12812 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
12813 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
12815 if (nBuffers > 1) {
12816 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
12817 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
12818 nBytes = MSG_SIZ - 1;
12820 (void) memcpy(msg, buffer, nBytes);
12822 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
12824 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
12825 cmailMailedMove = TRUE; /* Prevent >1 moves */
12828 for (i = 0; i < nCmailGames; i ++) {
12829 if (cmailResult[i] == CMAIL_NOT_RESULT) {
12834 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
12836 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
12838 appData.cmailGameName,
12840 LoadGameFromFile(buffer, 1, buffer, FALSE);
12841 cmailMsgLoaded = FALSE;
12845 DisplayInformation(msg);
12846 pclose(commandOutput);
12849 if ((*cmailMsg) != '\0') {
12850 DisplayInformation(cmailMsg);
12855 #endif /* !WIN32 */
12864 int prependComma = 0;
12866 char string[MSG_SIZ]; /* Space for game-list */
12869 if (!cmailMsgLoaded) return "";
12871 if (cmailMailedMove) {
12872 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
12874 /* Create a list of games left */
12875 snprintf(string, MSG_SIZ, "[");
12876 for (i = 0; i < nCmailGames; i ++) {
12877 if (! ( cmailMoveRegistered[i]
12878 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
12879 if (prependComma) {
12880 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
12882 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
12886 strcat(string, number);
12889 strcat(string, "]");
12891 if (nCmailMovesRegistered + nCmailResults == 0) {
12892 switch (nCmailGames) {
12894 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
12898 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
12902 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
12907 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
12909 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
12914 if (nCmailResults == nCmailGames) {
12915 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
12917 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
12922 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
12934 if (gameMode == Training)
12935 SetTrainingModeOff();
12938 cmailMsgLoaded = FALSE;
12939 if (appData.icsActive) {
12940 SendToICS(ics_prefix);
12941 SendToICS("refresh\n");
12946 ExitEvent (int status)
12950 /* Give up on clean exit */
12954 /* Keep trying for clean exit */
12958 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
12960 if (telnetISR != NULL) {
12961 RemoveInputSource(telnetISR);
12963 if (icsPR != NoProc) {
12964 DestroyChildProcess(icsPR, TRUE);
12967 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
12968 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
12970 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
12971 /* make sure this other one finishes before killing it! */
12972 if(endingGame) { int count = 0;
12973 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
12974 while(endingGame && count++ < 10) DoSleep(1);
12975 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
12978 /* Kill off chess programs */
12979 if (first.pr != NoProc) {
12982 DoSleep( appData.delayBeforeQuit );
12983 SendToProgram("quit\n", &first);
12984 DoSleep( appData.delayAfterQuit );
12985 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
12987 if (second.pr != NoProc) {
12988 DoSleep( appData.delayBeforeQuit );
12989 SendToProgram("quit\n", &second);
12990 DoSleep( appData.delayAfterQuit );
12991 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
12993 if (first.isr != NULL) {
12994 RemoveInputSource(first.isr);
12996 if (second.isr != NULL) {
12997 RemoveInputSource(second.isr);
13000 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
13001 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
13003 ShutDownFrontEnd();
13010 if (appData.debugMode)
13011 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
13015 if (gameMode == MachinePlaysWhite ||
13016 gameMode == MachinePlaysBlack) {
13019 DisplayBothClocks();
13021 if (gameMode == PlayFromGameFile) {
13022 if (appData.timeDelay >= 0)
13023 AutoPlayGameLoop();
13024 } else if (gameMode == IcsExamining && pauseExamInvalid) {
13025 Reset(FALSE, TRUE);
13026 SendToICS(ics_prefix);
13027 SendToICS("refresh\n");
13028 } else if (currentMove < forwardMostMove) {
13029 ForwardInner(forwardMostMove);
13031 pauseExamInvalid = FALSE;
13033 switch (gameMode) {
13037 pauseExamForwardMostMove = forwardMostMove;
13038 pauseExamInvalid = FALSE;
13041 case IcsPlayingWhite:
13042 case IcsPlayingBlack:
13046 case PlayFromGameFile:
13047 (void) StopLoadGameTimer();
13051 case BeginningOfGame:
13052 if (appData.icsActive) return;
13053 /* else fall through */
13054 case MachinePlaysWhite:
13055 case MachinePlaysBlack:
13056 case TwoMachinesPlay:
13057 if (forwardMostMove == 0)
13058 return; /* don't pause if no one has moved */
13059 if ((gameMode == MachinePlaysWhite &&
13060 !WhiteOnMove(forwardMostMove)) ||
13061 (gameMode == MachinePlaysBlack &&
13062 WhiteOnMove(forwardMostMove))) {
13073 EditCommentEvent ()
13075 char title[MSG_SIZ];
13077 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
13078 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
13080 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
13081 WhiteOnMove(currentMove - 1) ? " " : ".. ",
13082 parseList[currentMove - 1]);
13085 EditCommentPopUp(currentMove, title, commentList[currentMove]);
13092 char *tags = PGNTags(&gameInfo);
13094 EditTagsPopUp(tags, NULL);
13099 AnalyzeModeEvent ()
13101 if (appData.noChessProgram || gameMode == AnalyzeMode)
13104 if (gameMode != AnalyzeFile) {
13105 if (!appData.icsEngineAnalyze) {
13107 if (gameMode != EditGame) return;
13109 ResurrectChessProgram();
13110 SendToProgram("analyze\n", &first);
13111 first.analyzing = TRUE;
13112 /*first.maybeThinking = TRUE;*/
13113 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13114 EngineOutputPopUp();
13116 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
13121 StartAnalysisClock();
13122 GetTimeMark(&lastNodeCountTime);
13127 AnalyzeFileEvent ()
13129 if (appData.noChessProgram || gameMode == AnalyzeFile)
13132 if (gameMode != AnalyzeMode) {
13134 if (gameMode != EditGame) return;
13135 ResurrectChessProgram();
13136 SendToProgram("analyze\n", &first);
13137 first.analyzing = TRUE;
13138 /*first.maybeThinking = TRUE;*/
13139 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13140 EngineOutputPopUp();
13142 gameMode = AnalyzeFile;
13147 StartAnalysisClock();
13148 GetTimeMark(&lastNodeCountTime);
13150 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
13154 MachineWhiteEvent ()
13157 char *bookHit = NULL;
13159 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
13163 if (gameMode == PlayFromGameFile ||
13164 gameMode == TwoMachinesPlay ||
13165 gameMode == Training ||
13166 gameMode == AnalyzeMode ||
13167 gameMode == EndOfGame)
13170 if (gameMode == EditPosition)
13171 EditPositionDone(TRUE);
13173 if (!WhiteOnMove(currentMove)) {
13174 DisplayError(_("It is not White's turn"), 0);
13178 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13181 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13182 gameMode == AnalyzeFile)
13185 ResurrectChessProgram(); /* in case it isn't running */
13186 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
13187 gameMode = MachinePlaysWhite;
13190 gameMode = MachinePlaysWhite;
13194 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13196 if (first.sendName) {
13197 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
13198 SendToProgram(buf, &first);
13200 if (first.sendTime) {
13201 if (first.useColors) {
13202 SendToProgram("black\n", &first); /*gnu kludge*/
13204 SendTimeRemaining(&first, TRUE);
13206 if (first.useColors) {
13207 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
13209 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13210 SetMachineThinkingEnables();
13211 first.maybeThinking = TRUE;
13215 if (appData.autoFlipView && !flipView) {
13216 flipView = !flipView;
13217 DrawPosition(FALSE, NULL);
13218 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13221 if(bookHit) { // [HGM] book: simulate book reply
13222 static char bookMove[MSG_SIZ]; // a bit generous?
13224 programStats.nodes = programStats.depth = programStats.time =
13225 programStats.score = programStats.got_only_move = 0;
13226 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13228 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13229 strcat(bookMove, bookHit);
13230 HandleMachineMove(bookMove, &first);
13235 MachineBlackEvent ()
13238 char *bookHit = NULL;
13240 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
13244 if (gameMode == PlayFromGameFile ||
13245 gameMode == TwoMachinesPlay ||
13246 gameMode == Training ||
13247 gameMode == AnalyzeMode ||
13248 gameMode == EndOfGame)
13251 if (gameMode == EditPosition)
13252 EditPositionDone(TRUE);
13254 if (WhiteOnMove(currentMove)) {
13255 DisplayError(_("It is not Black's turn"), 0);
13259 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13262 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13263 gameMode == AnalyzeFile)
13266 ResurrectChessProgram(); /* in case it isn't running */
13267 gameMode = MachinePlaysBlack;
13271 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13273 if (first.sendName) {
13274 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
13275 SendToProgram(buf, &first);
13277 if (first.sendTime) {
13278 if (first.useColors) {
13279 SendToProgram("white\n", &first); /*gnu kludge*/
13281 SendTimeRemaining(&first, FALSE);
13283 if (first.useColors) {
13284 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
13286 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13287 SetMachineThinkingEnables();
13288 first.maybeThinking = TRUE;
13291 if (appData.autoFlipView && flipView) {
13292 flipView = !flipView;
13293 DrawPosition(FALSE, NULL);
13294 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13296 if(bookHit) { // [HGM] book: simulate book reply
13297 static char bookMove[MSG_SIZ]; // a bit generous?
13299 programStats.nodes = programStats.depth = programStats.time =
13300 programStats.score = programStats.got_only_move = 0;
13301 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13303 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13304 strcat(bookMove, bookHit);
13305 HandleMachineMove(bookMove, &first);
13311 DisplayTwoMachinesTitle ()
13314 if (appData.matchGames > 0) {
13315 if(appData.tourneyFile[0]) {
13316 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
13317 gameInfo.white, _("vs."), gameInfo.black,
13318 nextGame+1, appData.matchGames+1,
13319 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
13321 if (first.twoMachinesColor[0] == 'w') {
13322 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13323 gameInfo.white, _("vs."), gameInfo.black,
13324 first.matchWins, second.matchWins,
13325 matchGame - 1 - (first.matchWins + second.matchWins));
13327 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13328 gameInfo.white, _("vs."), gameInfo.black,
13329 second.matchWins, first.matchWins,
13330 matchGame - 1 - (first.matchWins + second.matchWins));
13333 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13339 SettingsMenuIfReady ()
13341 if (second.lastPing != second.lastPong) {
13342 DisplayMessage("", _("Waiting for second chess program"));
13343 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
13347 DisplayMessage("", "");
13348 SettingsPopUp(&second);
13352 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
13355 if (cps->pr == NoProc) {
13356 StartChessProgram(cps);
13357 if (cps->protocolVersion == 1) {
13360 /* kludge: allow timeout for initial "feature" command */
13362 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
13363 DisplayMessage("", buf);
13364 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
13372 TwoMachinesEvent P((void))
13376 ChessProgramState *onmove;
13377 char *bookHit = NULL;
13378 static int stalling = 0;
13382 if (appData.noChessProgram) return;
13384 switch (gameMode) {
13385 case TwoMachinesPlay:
13387 case MachinePlaysWhite:
13388 case MachinePlaysBlack:
13389 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13390 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13394 case BeginningOfGame:
13395 case PlayFromGameFile:
13398 if (gameMode != EditGame) return;
13401 EditPositionDone(TRUE);
13412 // forwardMostMove = currentMove;
13413 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
13415 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
13417 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
13418 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
13419 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13423 InitChessProgram(&second, FALSE); // unbalances ping of second engine
13424 SendToProgram("force\n", &second);
13426 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13429 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
13430 if(appData.matchPause>10000 || appData.matchPause<10)
13431 appData.matchPause = 10000; /* [HGM] make pause adjustable */
13432 wait = SubtractTimeMarks(&now, &pauseStart);
13433 if(wait < appData.matchPause) {
13434 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
13437 // we are now committed to starting the game
13439 DisplayMessage("", "");
13440 if (startedFromSetupPosition) {
13441 SendBoard(&second, backwardMostMove);
13442 if (appData.debugMode) {
13443 fprintf(debugFP, "Two Machines\n");
13446 for (i = backwardMostMove; i < forwardMostMove; i++) {
13447 SendMoveToProgram(i, &second);
13450 gameMode = TwoMachinesPlay;
13452 ModeHighlight(); // [HGM] logo: this triggers display update of logos
13454 DisplayTwoMachinesTitle();
13456 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
13461 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
13462 SendToProgram(first.computerString, &first);
13463 if (first.sendName) {
13464 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
13465 SendToProgram(buf, &first);
13467 SendToProgram(second.computerString, &second);
13468 if (second.sendName) {
13469 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
13470 SendToProgram(buf, &second);
13474 if (!first.sendTime || !second.sendTime) {
13475 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13476 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13478 if (onmove->sendTime) {
13479 if (onmove->useColors) {
13480 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
13482 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
13484 if (onmove->useColors) {
13485 SendToProgram(onmove->twoMachinesColor, onmove);
13487 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
13488 // SendToProgram("go\n", onmove);
13489 onmove->maybeThinking = TRUE;
13490 SetMachineThinkingEnables();
13494 if(bookHit) { // [HGM] book: simulate book reply
13495 static char bookMove[MSG_SIZ]; // a bit generous?
13497 programStats.nodes = programStats.depth = programStats.time =
13498 programStats.score = programStats.got_only_move = 0;
13499 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13501 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13502 strcat(bookMove, bookHit);
13503 savedMessage = bookMove; // args for deferred call
13504 savedState = onmove;
13505 ScheduleDelayedEvent(DeferredBookMove, 1);
13512 if (gameMode == Training) {
13513 SetTrainingModeOff();
13514 gameMode = PlayFromGameFile;
13515 DisplayMessage("", _("Training mode off"));
13517 gameMode = Training;
13518 animateTraining = appData.animate;
13520 /* make sure we are not already at the end of the game */
13521 if (currentMove < forwardMostMove) {
13522 SetTrainingModeOn();
13523 DisplayMessage("", _("Training mode on"));
13525 gameMode = PlayFromGameFile;
13526 DisplayError(_("Already at end of game"), 0);
13535 if (!appData.icsActive) return;
13536 switch (gameMode) {
13537 case IcsPlayingWhite:
13538 case IcsPlayingBlack:
13541 case BeginningOfGame:
13549 EditPositionDone(TRUE);
13562 gameMode = IcsIdle;
13572 switch (gameMode) {
13574 SetTrainingModeOff();
13576 case MachinePlaysWhite:
13577 case MachinePlaysBlack:
13578 case BeginningOfGame:
13579 SendToProgram("force\n", &first);
13580 SetUserThinkingEnables();
13582 case PlayFromGameFile:
13583 (void) StopLoadGameTimer();
13584 if (gameFileFP != NULL) {
13589 EditPositionDone(TRUE);
13594 SendToProgram("force\n", &first);
13596 case TwoMachinesPlay:
13597 GameEnds(EndOfFile, NULL, GE_PLAYER);
13598 ResurrectChessProgram();
13599 SetUserThinkingEnables();
13602 ResurrectChessProgram();
13604 case IcsPlayingBlack:
13605 case IcsPlayingWhite:
13606 DisplayError(_("Warning: You are still playing a game"), 0);
13609 DisplayError(_("Warning: You are still observing a game"), 0);
13612 DisplayError(_("Warning: You are still examining a game"), 0);
13623 first.offeredDraw = second.offeredDraw = 0;
13625 if (gameMode == PlayFromGameFile) {
13626 whiteTimeRemaining = timeRemaining[0][currentMove];
13627 blackTimeRemaining = timeRemaining[1][currentMove];
13631 if (gameMode == MachinePlaysWhite ||
13632 gameMode == MachinePlaysBlack ||
13633 gameMode == TwoMachinesPlay ||
13634 gameMode == EndOfGame) {
13635 i = forwardMostMove;
13636 while (i > currentMove) {
13637 SendToProgram("undo\n", &first);
13640 if(!adjustedClock) {
13641 whiteTimeRemaining = timeRemaining[0][currentMove];
13642 blackTimeRemaining = timeRemaining[1][currentMove];
13643 DisplayBothClocks();
13645 if (whiteFlag || blackFlag) {
13646 whiteFlag = blackFlag = 0;
13651 gameMode = EditGame;
13658 EditPositionEvent ()
13660 if (gameMode == EditPosition) {
13666 if (gameMode != EditGame) return;
13668 gameMode = EditPosition;
13671 if (currentMove > 0)
13672 CopyBoard(boards[0], boards[currentMove]);
13674 blackPlaysFirst = !WhiteOnMove(currentMove);
13676 currentMove = forwardMostMove = backwardMostMove = 0;
13677 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13684 /* [DM] icsEngineAnalyze - possible call from other functions */
13685 if (appData.icsEngineAnalyze) {
13686 appData.icsEngineAnalyze = FALSE;
13688 DisplayMessage("",_("Close ICS engine analyze..."));
13690 if (first.analysisSupport && first.analyzing) {
13691 SendToProgram("exit\n", &first);
13692 first.analyzing = FALSE;
13694 thinkOutput[0] = NULLCHAR;
13698 EditPositionDone (Boolean fakeRights)
13700 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
13702 startedFromSetupPosition = TRUE;
13703 InitChessProgram(&first, FALSE);
13704 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
13705 boards[0][EP_STATUS] = EP_NONE;
13706 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
13707 if(boards[0][0][BOARD_WIDTH>>1] == king) {
13708 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
13709 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
13710 } else boards[0][CASTLING][2] = NoRights;
13711 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
13712 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
13713 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
13714 } else boards[0][CASTLING][5] = NoRights;
13716 SendToProgram("force\n", &first);
13717 if (blackPlaysFirst) {
13718 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13719 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13720 currentMove = forwardMostMove = backwardMostMove = 1;
13721 CopyBoard(boards[1], boards[0]);
13723 currentMove = forwardMostMove = backwardMostMove = 0;
13725 SendBoard(&first, forwardMostMove);
13726 if (appData.debugMode) {
13727 fprintf(debugFP, "EditPosDone\n");
13730 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13731 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13732 gameMode = EditGame;
13734 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13735 ClearHighlights(); /* [AS] */
13738 /* Pause for `ms' milliseconds */
13739 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
13741 TimeDelay (long ms)
13748 } while (SubtractTimeMarks(&m2, &m1) < ms);
13751 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
13753 SendMultiLineToICS (char *buf)
13755 char temp[MSG_SIZ+1], *p;
13762 strncpy(temp, buf, len);
13767 if (*p == '\n' || *p == '\r')
13772 strcat(temp, "\n");
13774 SendToPlayer(temp, strlen(temp));
13778 SetWhiteToPlayEvent ()
13780 if (gameMode == EditPosition) {
13781 blackPlaysFirst = FALSE;
13782 DisplayBothClocks(); /* works because currentMove is 0 */
13783 } else if (gameMode == IcsExamining) {
13784 SendToICS(ics_prefix);
13785 SendToICS("tomove white\n");
13790 SetBlackToPlayEvent ()
13792 if (gameMode == EditPosition) {
13793 blackPlaysFirst = TRUE;
13794 currentMove = 1; /* kludge */
13795 DisplayBothClocks();
13797 } else if (gameMode == IcsExamining) {
13798 SendToICS(ics_prefix);
13799 SendToICS("tomove black\n");
13804 EditPositionMenuEvent (ChessSquare selection, int x, int y)
13807 ChessSquare piece = boards[0][y][x];
13809 if (gameMode != EditPosition && gameMode != IcsExamining) return;
13811 switch (selection) {
13813 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
13814 SendToICS(ics_prefix);
13815 SendToICS("bsetup clear\n");
13816 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
13817 SendToICS(ics_prefix);
13818 SendToICS("clearboard\n");
13820 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
13821 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
13822 for (y = 0; y < BOARD_HEIGHT; y++) {
13823 if (gameMode == IcsExamining) {
13824 if (boards[currentMove][y][x] != EmptySquare) {
13825 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
13830 boards[0][y][x] = p;
13835 if (gameMode == EditPosition) {
13836 DrawPosition(FALSE, boards[0]);
13841 SetWhiteToPlayEvent();
13845 SetBlackToPlayEvent();
13849 if (gameMode == IcsExamining) {
13850 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
13851 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
13854 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
13855 if(x == BOARD_LEFT-2) {
13856 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
13857 boards[0][y][1] = 0;
13859 if(x == BOARD_RGHT+1) {
13860 if(y >= gameInfo.holdingsSize) break;
13861 boards[0][y][BOARD_WIDTH-2] = 0;
13864 boards[0][y][x] = EmptySquare;
13865 DrawPosition(FALSE, boards[0]);
13870 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
13871 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
13872 selection = (ChessSquare) (PROMOTED piece);
13873 } else if(piece == EmptySquare) selection = WhiteSilver;
13874 else selection = (ChessSquare)((int)piece - 1);
13878 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
13879 piece > (int)BlackMan && piece <= (int)BlackKing ) {
13880 selection = (ChessSquare) (DEMOTED piece);
13881 } else if(piece == EmptySquare) selection = BlackSilver;
13882 else selection = (ChessSquare)((int)piece + 1);
13887 if(gameInfo.variant == VariantShatranj ||
13888 gameInfo.variant == VariantXiangqi ||
13889 gameInfo.variant == VariantCourier ||
13890 gameInfo.variant == VariantMakruk )
13891 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
13896 if(gameInfo.variant == VariantXiangqi)
13897 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
13898 if(gameInfo.variant == VariantKnightmate)
13899 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
13902 if (gameMode == IcsExamining) {
13903 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
13904 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
13905 PieceToChar(selection), AAA + x, ONE + y);
13908 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
13910 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
13911 n = PieceToNumber(selection - BlackPawn);
13912 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
13913 boards[0][BOARD_HEIGHT-1-n][0] = selection;
13914 boards[0][BOARD_HEIGHT-1-n][1]++;
13916 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
13917 n = PieceToNumber(selection);
13918 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
13919 boards[0][n][BOARD_WIDTH-1] = selection;
13920 boards[0][n][BOARD_WIDTH-2]++;
13923 boards[0][y][x] = selection;
13924 DrawPosition(TRUE, boards[0]);
13926 fromX = fromY = -1;
13934 DropMenuEvent (ChessSquare selection, int x, int y)
13936 ChessMove moveType;
13938 switch (gameMode) {
13939 case IcsPlayingWhite:
13940 case MachinePlaysBlack:
13941 if (!WhiteOnMove(currentMove)) {
13942 DisplayMoveError(_("It is Black's turn"));
13945 moveType = WhiteDrop;
13947 case IcsPlayingBlack:
13948 case MachinePlaysWhite:
13949 if (WhiteOnMove(currentMove)) {
13950 DisplayMoveError(_("It is White's turn"));
13953 moveType = BlackDrop;
13956 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
13962 if (moveType == BlackDrop && selection < BlackPawn) {
13963 selection = (ChessSquare) ((int) selection
13964 + (int) BlackPawn - (int) WhitePawn);
13966 if (boards[currentMove][y][x] != EmptySquare) {
13967 DisplayMoveError(_("That square is occupied"));
13971 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
13977 /* Accept a pending offer of any kind from opponent */
13979 if (appData.icsActive) {
13980 SendToICS(ics_prefix);
13981 SendToICS("accept\n");
13982 } else if (cmailMsgLoaded) {
13983 if (currentMove == cmailOldMove &&
13984 commentList[cmailOldMove] != NULL &&
13985 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
13986 "Black offers a draw" : "White offers a draw")) {
13988 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
13989 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
13991 DisplayError(_("There is no pending offer on this move"), 0);
13992 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
13995 /* Not used for offers from chess program */
14002 /* Decline a pending offer of any kind from opponent */
14004 if (appData.icsActive) {
14005 SendToICS(ics_prefix);
14006 SendToICS("decline\n");
14007 } else if (cmailMsgLoaded) {
14008 if (currentMove == cmailOldMove &&
14009 commentList[cmailOldMove] != NULL &&
14010 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14011 "Black offers a draw" : "White offers a draw")) {
14013 AppendComment(cmailOldMove, "Draw declined", TRUE);
14014 DisplayComment(cmailOldMove - 1, "Draw declined");
14017 DisplayError(_("There is no pending offer on this move"), 0);
14020 /* Not used for offers from chess program */
14027 /* Issue ICS rematch command */
14028 if (appData.icsActive) {
14029 SendToICS(ics_prefix);
14030 SendToICS("rematch\n");
14037 /* Call your opponent's flag (claim a win on time) */
14038 if (appData.icsActive) {
14039 SendToICS(ics_prefix);
14040 SendToICS("flag\n");
14042 switch (gameMode) {
14045 case MachinePlaysWhite:
14048 GameEnds(GameIsDrawn, "Both players ran out of time",
14051 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
14053 DisplayError(_("Your opponent is not out of time"), 0);
14056 case MachinePlaysBlack:
14059 GameEnds(GameIsDrawn, "Both players ran out of time",
14062 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
14064 DisplayError(_("Your opponent is not out of time"), 0);
14072 ClockClick (int which)
14073 { // [HGM] code moved to back-end from winboard.c
14074 if(which) { // black clock
14075 if (gameMode == EditPosition || gameMode == IcsExamining) {
14076 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14077 SetBlackToPlayEvent();
14078 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !blackFlag && WhiteOnMove(currentMove)) {
14079 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
14080 } else if (shiftKey) {
14081 AdjustClock(which, -1);
14082 } else if (gameMode == IcsPlayingWhite ||
14083 gameMode == MachinePlaysBlack) {
14086 } else { // white clock
14087 if (gameMode == EditPosition || gameMode == IcsExamining) {
14088 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14089 SetWhiteToPlayEvent();
14090 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !whiteFlag && !WhiteOnMove(currentMove)) {
14091 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
14092 } else if (shiftKey) {
14093 AdjustClock(which, -1);
14094 } else if (gameMode == IcsPlayingBlack ||
14095 gameMode == MachinePlaysWhite) {
14104 /* Offer draw or accept pending draw offer from opponent */
14106 if (appData.icsActive) {
14107 /* Note: tournament rules require draw offers to be
14108 made after you make your move but before you punch
14109 your clock. Currently ICS doesn't let you do that;
14110 instead, you immediately punch your clock after making
14111 a move, but you can offer a draw at any time. */
14113 SendToICS(ics_prefix);
14114 SendToICS("draw\n");
14115 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
14116 } else if (cmailMsgLoaded) {
14117 if (currentMove == cmailOldMove &&
14118 commentList[cmailOldMove] != NULL &&
14119 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14120 "Black offers a draw" : "White offers a draw")) {
14121 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14122 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14123 } else if (currentMove == cmailOldMove + 1) {
14124 char *offer = WhiteOnMove(cmailOldMove) ?
14125 "White offers a draw" : "Black offers a draw";
14126 AppendComment(currentMove, offer, TRUE);
14127 DisplayComment(currentMove - 1, offer);
14128 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
14130 DisplayError(_("You must make your move before offering a draw"), 0);
14131 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14133 } else if (first.offeredDraw) {
14134 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
14136 if (first.sendDrawOffers) {
14137 SendToProgram("draw\n", &first);
14138 userOfferedDraw = TRUE;
14146 /* Offer Adjourn or accept pending Adjourn offer from opponent */
14148 if (appData.icsActive) {
14149 SendToICS(ics_prefix);
14150 SendToICS("adjourn\n");
14152 /* Currently GNU Chess doesn't offer or accept Adjourns */
14160 /* Offer Abort or accept pending Abort offer from opponent */
14162 if (appData.icsActive) {
14163 SendToICS(ics_prefix);
14164 SendToICS("abort\n");
14166 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
14173 /* Resign. You can do this even if it's not your turn. */
14175 if (appData.icsActive) {
14176 SendToICS(ics_prefix);
14177 SendToICS("resign\n");
14179 switch (gameMode) {
14180 case MachinePlaysWhite:
14181 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14183 case MachinePlaysBlack:
14184 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14187 if (cmailMsgLoaded) {
14189 if (WhiteOnMove(cmailOldMove)) {
14190 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14192 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14194 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
14205 StopObservingEvent ()
14207 /* Stop observing current games */
14208 SendToICS(ics_prefix);
14209 SendToICS("unobserve\n");
14213 StopExaminingEvent ()
14215 /* Stop observing current game */
14216 SendToICS(ics_prefix);
14217 SendToICS("unexamine\n");
14221 ForwardInner (int target)
14223 int limit; int oldSeekGraphUp = seekGraphUp;
14225 if (appData.debugMode)
14226 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
14227 target, currentMove, forwardMostMove);
14229 if (gameMode == EditPosition)
14232 seekGraphUp = FALSE;
14233 MarkTargetSquares(1);
14235 if (gameMode == PlayFromGameFile && !pausing)
14238 if (gameMode == IcsExamining && pausing)
14239 limit = pauseExamForwardMostMove;
14241 limit = forwardMostMove;
14243 if (target > limit) target = limit;
14245 if (target > 0 && moveList[target - 1][0]) {
14246 int fromX, fromY, toX, toY;
14247 toX = moveList[target - 1][2] - AAA;
14248 toY = moveList[target - 1][3] - ONE;
14249 if (moveList[target - 1][1] == '@') {
14250 if (appData.highlightLastMove) {
14251 SetHighlights(-1, -1, toX, toY);
14254 fromX = moveList[target - 1][0] - AAA;
14255 fromY = moveList[target - 1][1] - ONE;
14256 if (target == currentMove + 1) {
14257 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
14259 if (appData.highlightLastMove) {
14260 SetHighlights(fromX, fromY, toX, toY);
14264 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14265 gameMode == Training || gameMode == PlayFromGameFile ||
14266 gameMode == AnalyzeFile) {
14267 while (currentMove < target) {
14268 SendMoveToProgram(currentMove++, &first);
14271 currentMove = target;
14274 if (gameMode == EditGame || gameMode == EndOfGame) {
14275 whiteTimeRemaining = timeRemaining[0][currentMove];
14276 blackTimeRemaining = timeRemaining[1][currentMove];
14278 DisplayBothClocks();
14279 DisplayMove(currentMove - 1);
14280 DrawPosition(oldSeekGraphUp, boards[currentMove]);
14281 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14282 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
14283 DisplayComment(currentMove - 1, commentList[currentMove]);
14291 if (gameMode == IcsExamining && !pausing) {
14292 SendToICS(ics_prefix);
14293 SendToICS("forward\n");
14295 ForwardInner(currentMove + 1);
14302 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14303 /* to optimze, we temporarily turn off analysis mode while we feed
14304 * the remaining moves to the engine. Otherwise we get analysis output
14307 if (first.analysisSupport) {
14308 SendToProgram("exit\nforce\n", &first);
14309 first.analyzing = FALSE;
14313 if (gameMode == IcsExamining && !pausing) {
14314 SendToICS(ics_prefix);
14315 SendToICS("forward 999999\n");
14317 ForwardInner(forwardMostMove);
14320 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14321 /* we have fed all the moves, so reactivate analysis mode */
14322 SendToProgram("analyze\n", &first);
14323 first.analyzing = TRUE;
14324 /*first.maybeThinking = TRUE;*/
14325 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14330 BackwardInner (int target)
14332 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
14334 if (appData.debugMode)
14335 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
14336 target, currentMove, forwardMostMove);
14338 if (gameMode == EditPosition) return;
14339 seekGraphUp = FALSE;
14340 MarkTargetSquares(1);
14341 if (currentMove <= backwardMostMove) {
14343 DrawPosition(full_redraw, boards[currentMove]);
14346 if (gameMode == PlayFromGameFile && !pausing)
14349 if (moveList[target][0]) {
14350 int fromX, fromY, toX, toY;
14351 toX = moveList[target][2] - AAA;
14352 toY = moveList[target][3] - ONE;
14353 if (moveList[target][1] == '@') {
14354 if (appData.highlightLastMove) {
14355 SetHighlights(-1, -1, toX, toY);
14358 fromX = moveList[target][0] - AAA;
14359 fromY = moveList[target][1] - ONE;
14360 if (target == currentMove - 1) {
14361 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
14363 if (appData.highlightLastMove) {
14364 SetHighlights(fromX, fromY, toX, toY);
14368 if (gameMode == EditGame || gameMode==AnalyzeMode ||
14369 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
14370 while (currentMove > target) {
14371 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
14372 // null move cannot be undone. Reload program with move history before it.
14374 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
14375 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
14377 SendBoard(&first, i);
14378 for(currentMove=i; currentMove<target; currentMove++) SendMoveToProgram(currentMove, &first);
14381 SendToProgram("undo\n", &first);
14385 currentMove = target;
14388 if (gameMode == EditGame || gameMode == EndOfGame) {
14389 whiteTimeRemaining = timeRemaining[0][currentMove];
14390 blackTimeRemaining = timeRemaining[1][currentMove];
14392 DisplayBothClocks();
14393 DisplayMove(currentMove - 1);
14394 DrawPosition(full_redraw, boards[currentMove]);
14395 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14396 // [HGM] PV info: routine tests if comment empty
14397 DisplayComment(currentMove - 1, commentList[currentMove]);
14403 if (gameMode == IcsExamining && !pausing) {
14404 SendToICS(ics_prefix);
14405 SendToICS("backward\n");
14407 BackwardInner(currentMove - 1);
14414 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14415 /* to optimize, we temporarily turn off analysis mode while we undo
14416 * all the moves. Otherwise we get analysis output after each undo.
14418 if (first.analysisSupport) {
14419 SendToProgram("exit\nforce\n", &first);
14420 first.analyzing = FALSE;
14424 if (gameMode == IcsExamining && !pausing) {
14425 SendToICS(ics_prefix);
14426 SendToICS("backward 999999\n");
14428 BackwardInner(backwardMostMove);
14431 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14432 /* we have fed all the moves, so reactivate analysis mode */
14433 SendToProgram("analyze\n", &first);
14434 first.analyzing = TRUE;
14435 /*first.maybeThinking = TRUE;*/
14436 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14443 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
14444 if (to >= forwardMostMove) to = forwardMostMove;
14445 if (to <= backwardMostMove) to = backwardMostMove;
14446 if (to < currentMove) {
14454 RevertEvent (Boolean annotate)
14456 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
14459 if (gameMode != IcsExamining) {
14460 DisplayError(_("You are not examining a game"), 0);
14464 DisplayError(_("You can't revert while pausing"), 0);
14467 SendToICS(ics_prefix);
14468 SendToICS("revert\n");
14472 RetractMoveEvent ()
14474 switch (gameMode) {
14475 case MachinePlaysWhite:
14476 case MachinePlaysBlack:
14477 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
14478 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
14481 if (forwardMostMove < 2) return;
14482 currentMove = forwardMostMove = forwardMostMove - 2;
14483 whiteTimeRemaining = timeRemaining[0][currentMove];
14484 blackTimeRemaining = timeRemaining[1][currentMove];
14485 DisplayBothClocks();
14486 DisplayMove(currentMove - 1);
14487 ClearHighlights();/*!! could figure this out*/
14488 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
14489 SendToProgram("remove\n", &first);
14490 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
14493 case BeginningOfGame:
14497 case IcsPlayingWhite:
14498 case IcsPlayingBlack:
14499 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
14500 SendToICS(ics_prefix);
14501 SendToICS("takeback 2\n");
14503 SendToICS(ics_prefix);
14504 SendToICS("takeback 1\n");
14513 ChessProgramState *cps;
14515 switch (gameMode) {
14516 case MachinePlaysWhite:
14517 if (!WhiteOnMove(forwardMostMove)) {
14518 DisplayError(_("It is your turn"), 0);
14523 case MachinePlaysBlack:
14524 if (WhiteOnMove(forwardMostMove)) {
14525 DisplayError(_("It is your turn"), 0);
14530 case TwoMachinesPlay:
14531 if (WhiteOnMove(forwardMostMove) ==
14532 (first.twoMachinesColor[0] == 'w')) {
14538 case BeginningOfGame:
14542 SendToProgram("?\n", cps);
14546 TruncateGameEvent ()
14549 if (gameMode != EditGame) return;
14556 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
14557 if (forwardMostMove > currentMove) {
14558 if (gameInfo.resultDetails != NULL) {
14559 free(gameInfo.resultDetails);
14560 gameInfo.resultDetails = NULL;
14561 gameInfo.result = GameUnfinished;
14563 forwardMostMove = currentMove;
14564 HistorySet(parseList, backwardMostMove, forwardMostMove,
14572 if (appData.noChessProgram) return;
14573 switch (gameMode) {
14574 case MachinePlaysWhite:
14575 if (WhiteOnMove(forwardMostMove)) {
14576 DisplayError(_("Wait until your turn"), 0);
14580 case BeginningOfGame:
14581 case MachinePlaysBlack:
14582 if (!WhiteOnMove(forwardMostMove)) {
14583 DisplayError(_("Wait until your turn"), 0);
14588 DisplayError(_("No hint available"), 0);
14591 SendToProgram("hint\n", &first);
14592 hintRequested = TRUE;
14598 if (appData.noChessProgram) return;
14599 switch (gameMode) {
14600 case MachinePlaysWhite:
14601 if (WhiteOnMove(forwardMostMove)) {
14602 DisplayError(_("Wait until your turn"), 0);
14606 case BeginningOfGame:
14607 case MachinePlaysBlack:
14608 if (!WhiteOnMove(forwardMostMove)) {
14609 DisplayError(_("Wait until your turn"), 0);
14614 EditPositionDone(TRUE);
14616 case TwoMachinesPlay:
14621 SendToProgram("bk\n", &first);
14622 bookOutput[0] = NULLCHAR;
14623 bookRequested = TRUE;
14629 char *tags = PGNTags(&gameInfo);
14630 TagsPopUp(tags, CmailMsg());
14634 /* end button procedures */
14637 PrintPosition (FILE *fp, int move)
14641 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14642 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
14643 char c = PieceToChar(boards[move][i][j]);
14644 fputc(c == 'x' ? '.' : c, fp);
14645 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
14648 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
14649 fprintf(fp, "white to play\n");
14651 fprintf(fp, "black to play\n");
14655 PrintOpponents (FILE *fp)
14657 if (gameInfo.white != NULL) {
14658 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
14664 /* Find last component of program's own name, using some heuristics */
14666 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
14669 int local = (strcmp(host, "localhost") == 0);
14670 while (!local && (p = strchr(prog, ';')) != NULL) {
14672 while (*p == ' ') p++;
14675 if (*prog == '"' || *prog == '\'') {
14676 q = strchr(prog + 1, *prog);
14678 q = strchr(prog, ' ');
14680 if (q == NULL) q = prog + strlen(prog);
14682 while (p >= prog && *p != '/' && *p != '\\') p--;
14684 if(p == prog && *p == '"') p++;
14686 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
14687 memcpy(buf, p, q - p);
14688 buf[q - p] = NULLCHAR;
14696 TimeControlTagValue ()
14699 if (!appData.clockMode) {
14700 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
14701 } else if (movesPerSession > 0) {
14702 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
14703 } else if (timeIncrement == 0) {
14704 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
14706 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
14708 return StrSave(buf);
14714 /* This routine is used only for certain modes */
14715 VariantClass v = gameInfo.variant;
14716 ChessMove r = GameUnfinished;
14719 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
14720 r = gameInfo.result;
14721 p = gameInfo.resultDetails;
14722 gameInfo.resultDetails = NULL;
14724 ClearGameInfo(&gameInfo);
14725 gameInfo.variant = v;
14727 switch (gameMode) {
14728 case MachinePlaysWhite:
14729 gameInfo.event = StrSave( appData.pgnEventHeader );
14730 gameInfo.site = StrSave(HostName());
14731 gameInfo.date = PGNDate();
14732 gameInfo.round = StrSave("-");
14733 gameInfo.white = StrSave(first.tidy);
14734 gameInfo.black = StrSave(UserName());
14735 gameInfo.timeControl = TimeControlTagValue();
14738 case MachinePlaysBlack:
14739 gameInfo.event = StrSave( appData.pgnEventHeader );
14740 gameInfo.site = StrSave(HostName());
14741 gameInfo.date = PGNDate();
14742 gameInfo.round = StrSave("-");
14743 gameInfo.white = StrSave(UserName());
14744 gameInfo.black = StrSave(first.tidy);
14745 gameInfo.timeControl = TimeControlTagValue();
14748 case TwoMachinesPlay:
14749 gameInfo.event = StrSave( appData.pgnEventHeader );
14750 gameInfo.site = StrSave(HostName());
14751 gameInfo.date = PGNDate();
14754 snprintf(buf, MSG_SIZ, "%d", roundNr);
14755 gameInfo.round = StrSave(buf);
14757 gameInfo.round = StrSave("-");
14759 if (first.twoMachinesColor[0] == 'w') {
14760 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
14761 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
14763 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
14764 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
14766 gameInfo.timeControl = TimeControlTagValue();
14770 gameInfo.event = StrSave("Edited game");
14771 gameInfo.site = StrSave(HostName());
14772 gameInfo.date = PGNDate();
14773 gameInfo.round = StrSave("-");
14774 gameInfo.white = StrSave("-");
14775 gameInfo.black = StrSave("-");
14776 gameInfo.result = r;
14777 gameInfo.resultDetails = p;
14781 gameInfo.event = StrSave("Edited position");
14782 gameInfo.site = StrSave(HostName());
14783 gameInfo.date = PGNDate();
14784 gameInfo.round = StrSave("-");
14785 gameInfo.white = StrSave("-");
14786 gameInfo.black = StrSave("-");
14789 case IcsPlayingWhite:
14790 case IcsPlayingBlack:
14795 case PlayFromGameFile:
14796 gameInfo.event = StrSave("Game from non-PGN file");
14797 gameInfo.site = StrSave(HostName());
14798 gameInfo.date = PGNDate();
14799 gameInfo.round = StrSave("-");
14800 gameInfo.white = StrSave("?");
14801 gameInfo.black = StrSave("?");
14810 ReplaceComment (int index, char *text)
14816 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
14817 pvInfoList[index-1].depth == len &&
14818 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
14819 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
14820 while (*text == '\n') text++;
14821 len = strlen(text);
14822 while (len > 0 && text[len - 1] == '\n') len--;
14824 if (commentList[index] != NULL)
14825 free(commentList[index]);
14828 commentList[index] = NULL;
14831 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
14832 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
14833 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
14834 commentList[index] = (char *) malloc(len + 2);
14835 strncpy(commentList[index], text, len);
14836 commentList[index][len] = '\n';
14837 commentList[index][len + 1] = NULLCHAR;
14839 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
14841 commentList[index] = (char *) malloc(len + 7);
14842 safeStrCpy(commentList[index], "{\n", 3);
14843 safeStrCpy(commentList[index]+2, text, len+1);
14844 commentList[index][len+2] = NULLCHAR;
14845 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
14846 strcat(commentList[index], "\n}\n");
14851 CrushCRs (char *text)
14859 if (ch == '\r') continue;
14861 } while (ch != '\0');
14865 AppendComment (int index, char *text, Boolean addBraces)
14866 /* addBraces tells if we should add {} */
14871 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
14872 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
14875 while (*text == '\n') text++;
14876 len = strlen(text);
14877 while (len > 0 && text[len - 1] == '\n') len--;
14878 text[len] = NULLCHAR;
14880 if (len == 0) return;
14882 if (commentList[index] != NULL) {
14883 Boolean addClosingBrace = addBraces;
14884 old = commentList[index];
14885 oldlen = strlen(old);
14886 while(commentList[index][oldlen-1] == '\n')
14887 commentList[index][--oldlen] = NULLCHAR;
14888 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
14889 safeStrCpy(commentList[index], old, oldlen + len + 6);
14891 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
14892 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
14893 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
14894 while (*text == '\n') { text++; len--; }
14895 commentList[index][--oldlen] = NULLCHAR;
14897 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
14898 else strcat(commentList[index], "\n");
14899 strcat(commentList[index], text);
14900 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
14901 else strcat(commentList[index], "\n");
14903 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
14905 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
14906 else commentList[index][0] = NULLCHAR;
14907 strcat(commentList[index], text);
14908 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
14909 if(addBraces == TRUE) strcat(commentList[index], "}\n");
14914 FindStr (char * text, char * sub_text)
14916 char * result = strstr( text, sub_text );
14918 if( result != NULL ) {
14919 result += strlen( sub_text );
14925 /* [AS] Try to extract PV info from PGN comment */
14926 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
14928 GetInfoFromComment (int index, char * text)
14930 char * sep = text, *p;
14932 if( text != NULL && index > 0 ) {
14935 int time = -1, sec = 0, deci;
14936 char * s_eval = FindStr( text, "[%eval " );
14937 char * s_emt = FindStr( text, "[%emt " );
14939 if( s_eval != NULL || s_emt != NULL ) {
14943 if( s_eval != NULL ) {
14944 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
14948 if( delim != ']' ) {
14953 if( s_emt != NULL ) {
14958 /* We expect something like: [+|-]nnn.nn/dd */
14961 if(*text != '{') return text; // [HGM] braces: must be normal comment
14963 sep = strchr( text, '/' );
14964 if( sep == NULL || sep < (text+4) ) {
14969 if(p[1] == '(') { // comment starts with PV
14970 p = strchr(p, ')'); // locate end of PV
14971 if(p == NULL || sep < p+5) return text;
14972 // at this point we have something like "{(.*) +0.23/6 ..."
14973 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
14974 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
14975 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
14977 time = -1; sec = -1; deci = -1;
14978 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
14979 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
14980 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
14981 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
14985 if( score_lo < 0 || score_lo >= 100 ) {
14989 if(sec >= 0) time = 600*time + 10*sec; else
14990 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
14992 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
14994 /* [HGM] PV time: now locate end of PV info */
14995 while( *++sep >= '0' && *sep <= '9'); // strip depth
14997 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
14999 while( *++sep >= '0' && *sep <= '9'); // strip seconds
15001 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
15002 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
15013 pvInfoList[index-1].depth = depth;
15014 pvInfoList[index-1].score = score;
15015 pvInfoList[index-1].time = 10*time; // centi-sec
15016 if(*sep == '}') *sep = 0; else *--sep = '{';
15017 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
15023 SendToProgram (char *message, ChessProgramState *cps)
15025 int count, outCount, error;
15028 if (cps->pr == NoProc) return;
15031 if (appData.debugMode) {
15034 fprintf(debugFP, "%ld >%-6s: %s",
15035 SubtractTimeMarks(&now, &programStartTime),
15036 cps->which, message);
15038 fprintf(serverFP, "%ld >%-6s: %s",
15039 SubtractTimeMarks(&now, &programStartTime),
15040 cps->which, message), fflush(serverFP);
15043 count = strlen(message);
15044 outCount = OutputToProcess(cps->pr, message, count, &error);
15045 if (outCount < count && !exiting
15046 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
15047 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
15048 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
15049 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15050 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15051 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15052 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15053 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15055 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15056 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15057 gameInfo.result = res;
15059 gameInfo.resultDetails = StrSave(buf);
15061 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15062 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15067 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
15071 ChessProgramState *cps = (ChessProgramState *)closure;
15073 if (isr != cps->isr) return; /* Killed intentionally */
15076 RemoveInputSource(cps->isr);
15077 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
15078 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
15079 _(cps->which), cps->program);
15080 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15081 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15082 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15083 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15084 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15086 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15087 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15088 gameInfo.result = res;
15090 gameInfo.resultDetails = StrSave(buf);
15092 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15093 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
15095 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
15096 _(cps->which), cps->program);
15097 RemoveInputSource(cps->isr);
15099 /* [AS] Program is misbehaving badly... kill it */
15100 if( count == -2 ) {
15101 DestroyChildProcess( cps->pr, 9 );
15105 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15110 if ((end_str = strchr(message, '\r')) != NULL)
15111 *end_str = NULLCHAR;
15112 if ((end_str = strchr(message, '\n')) != NULL)
15113 *end_str = NULLCHAR;
15115 if (appData.debugMode) {
15116 TimeMark now; int print = 1;
15117 char *quote = ""; char c; int i;
15119 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
15120 char start = message[0];
15121 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
15122 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
15123 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
15124 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
15125 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
15126 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
15127 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
15128 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
15129 sscanf(message, "hint: %c", &c)!=1 &&
15130 sscanf(message, "pong %c", &c)!=1 && start != '#') {
15131 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
15132 print = (appData.engineComments >= 2);
15134 message[0] = start; // restore original message
15138 fprintf(debugFP, "%ld <%-6s: %s%s\n",
15139 SubtractTimeMarks(&now, &programStartTime), cps->which,
15143 fprintf(serverFP, "%ld <%-6s: %s%s\n",
15144 SubtractTimeMarks(&now, &programStartTime), cps->which,
15146 message), fflush(serverFP);
15150 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
15151 if (appData.icsEngineAnalyze) {
15152 if (strstr(message, "whisper") != NULL ||
15153 strstr(message, "kibitz") != NULL ||
15154 strstr(message, "tellics") != NULL) return;
15157 HandleMachineMove(message, cps);
15162 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
15167 if( timeControl_2 > 0 ) {
15168 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
15169 tc = timeControl_2;
15172 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
15173 inc /= cps->timeOdds;
15174 st /= cps->timeOdds;
15176 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
15179 /* Set exact time per move, normally using st command */
15180 if (cps->stKludge) {
15181 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
15183 if (seconds == 0) {
15184 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
15186 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
15189 snprintf(buf, MSG_SIZ, "st %d\n", st);
15192 /* Set conventional or incremental time control, using level command */
15193 if (seconds == 0) {
15194 /* Note old gnuchess bug -- minutes:seconds used to not work.
15195 Fixed in later versions, but still avoid :seconds
15196 when seconds is 0. */
15197 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
15199 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
15200 seconds, inc/1000.);
15203 SendToProgram(buf, cps);
15205 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
15206 /* Orthogonally, limit search to given depth */
15208 if (cps->sdKludge) {
15209 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
15211 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
15213 SendToProgram(buf, cps);
15216 if(cps->nps >= 0) { /* [HGM] nps */
15217 if(cps->supportsNPS == FALSE)
15218 cps->nps = -1; // don't use if engine explicitly says not supported!
15220 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
15221 SendToProgram(buf, cps);
15226 ChessProgramState *
15228 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
15230 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
15231 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
15237 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
15239 char message[MSG_SIZ];
15242 /* Note: this routine must be called when the clocks are stopped
15243 or when they have *just* been set or switched; otherwise
15244 it will be off by the time since the current tick started.
15246 if (machineWhite) {
15247 time = whiteTimeRemaining / 10;
15248 otime = blackTimeRemaining / 10;
15250 time = blackTimeRemaining / 10;
15251 otime = whiteTimeRemaining / 10;
15253 /* [HGM] translate opponent's time by time-odds factor */
15254 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
15256 if (time <= 0) time = 1;
15257 if (otime <= 0) otime = 1;
15259 snprintf(message, MSG_SIZ, "time %ld\n", time);
15260 SendToProgram(message, cps);
15262 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
15263 SendToProgram(message, cps);
15267 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15270 int len = strlen(name);
15273 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15275 sscanf(*p, "%d", &val);
15277 while (**p && **p != ' ')
15279 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15280 SendToProgram(buf, cps);
15287 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15290 int len = strlen(name);
15291 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15293 sscanf(*p, "%d", loc);
15294 while (**p && **p != ' ') (*p)++;
15295 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15296 SendToProgram(buf, cps);
15303 StringFeature (char **p, char *name, char loc[], ChessProgramState *cps)
15306 int len = strlen(name);
15307 if (strncmp((*p), name, len) == 0
15308 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
15310 sscanf(*p, "%[^\"]", loc);
15311 while (**p && **p != '\"') (*p)++;
15312 if (**p == '\"') (*p)++;
15313 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15314 SendToProgram(buf, cps);
15321 ParseOption (Option *opt, ChessProgramState *cps)
15322 // [HGM] options: process the string that defines an engine option, and determine
15323 // name, type, default value, and allowed value range
15325 char *p, *q, buf[MSG_SIZ];
15326 int n, min = (-1)<<31, max = 1<<31, def;
15328 if(p = strstr(opt->name, " -spin ")) {
15329 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15330 if(max < min) max = min; // enforce consistency
15331 if(def < min) def = min;
15332 if(def > max) def = max;
15337 } else if((p = strstr(opt->name, " -slider "))) {
15338 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
15339 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15340 if(max < min) max = min; // enforce consistency
15341 if(def < min) def = min;
15342 if(def > max) def = max;
15346 opt->type = Spin; // Slider;
15347 } else if((p = strstr(opt->name, " -string "))) {
15348 opt->textValue = p+9;
15349 opt->type = TextBox;
15350 } else if((p = strstr(opt->name, " -file "))) {
15351 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15352 opt->textValue = p+7;
15353 opt->type = FileName; // FileName;
15354 } else if((p = strstr(opt->name, " -path "))) {
15355 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15356 opt->textValue = p+7;
15357 opt->type = PathName; // PathName;
15358 } else if(p = strstr(opt->name, " -check ")) {
15359 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
15360 opt->value = (def != 0);
15361 opt->type = CheckBox;
15362 } else if(p = strstr(opt->name, " -combo ")) {
15363 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
15364 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
15365 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
15366 opt->value = n = 0;
15367 while(q = StrStr(q, " /// ")) {
15368 n++; *q = 0; // count choices, and null-terminate each of them
15370 if(*q == '*') { // remember default, which is marked with * prefix
15374 cps->comboList[cps->comboCnt++] = q;
15376 cps->comboList[cps->comboCnt++] = NULL;
15378 opt->type = ComboBox;
15379 } else if(p = strstr(opt->name, " -button")) {
15380 opt->type = Button;
15381 } else if(p = strstr(opt->name, " -save")) {
15382 opt->type = SaveButton;
15383 } else return FALSE;
15384 *p = 0; // terminate option name
15385 // now look if the command-line options define a setting for this engine option.
15386 if(cps->optionSettings && cps->optionSettings[0])
15387 p = strstr(cps->optionSettings, opt->name); else p = NULL;
15388 if(p && (p == cps->optionSettings || p[-1] == ',')) {
15389 snprintf(buf, MSG_SIZ, "option %s", p);
15390 if(p = strstr(buf, ",")) *p = 0;
15391 if(q = strchr(buf, '=')) switch(opt->type) {
15393 for(n=0; n<opt->max; n++)
15394 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
15397 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
15401 opt->value = atoi(q+1);
15406 SendToProgram(buf, cps);
15412 FeatureDone (ChessProgramState *cps, int val)
15414 DelayedEventCallback cb = GetDelayedEvent();
15415 if ((cb == InitBackEnd3 && cps == &first) ||
15416 (cb == SettingsMenuIfReady && cps == &second) ||
15417 (cb == LoadEngine) ||
15418 (cb == TwoMachinesEventIfReady)) {
15419 CancelDelayedEvent();
15420 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
15422 cps->initDone = val;
15425 /* Parse feature command from engine */
15427 ParseFeatures (char *args, ChessProgramState *cps)
15435 while (*p == ' ') p++;
15436 if (*p == NULLCHAR) return;
15438 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
15439 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
15440 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
15441 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
15442 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
15443 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
15444 if (BoolFeature(&p, "reuse", &val, cps)) {
15445 /* Engine can disable reuse, but can't enable it if user said no */
15446 if (!val) cps->reuse = FALSE;
15449 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
15450 if (StringFeature(&p, "myname", cps->tidy, cps)) {
15451 if (gameMode == TwoMachinesPlay) {
15452 DisplayTwoMachinesTitle();
15458 if (StringFeature(&p, "variants", cps->variants, cps)) continue;
15459 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
15460 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
15461 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
15462 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
15463 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
15464 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
15465 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
15466 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
15467 if (IntFeature(&p, "done", &val, cps)) {
15468 FeatureDone(cps, val);
15471 /* Added by Tord: */
15472 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
15473 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
15474 /* End of additions by Tord */
15476 /* [HGM] added features: */
15477 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
15478 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
15479 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
15480 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
15481 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
15482 if (StringFeature(&p, "egt", cps->egtFormats, cps)) continue;
15483 if (StringFeature(&p, "option", cps->option[cps->nrOptions].name, cps)) {
15484 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
15485 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
15486 SendToProgram(buf, cps);
15489 if(cps->nrOptions >= MAX_OPTIONS) {
15491 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
15492 DisplayError(buf, 0);
15496 /* End of additions by HGM */
15498 /* unknown feature: complain and skip */
15500 while (*q && *q != '=') q++;
15501 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
15502 SendToProgram(buf, cps);
15508 while (*p && *p != '\"') p++;
15509 if (*p == '\"') p++;
15511 while (*p && *p != ' ') p++;
15519 PeriodicUpdatesEvent (int newState)
15521 if (newState == appData.periodicUpdates)
15524 appData.periodicUpdates=newState;
15526 /* Display type changes, so update it now */
15527 // DisplayAnalysis();
15529 /* Get the ball rolling again... */
15531 AnalysisPeriodicEvent(1);
15532 StartAnalysisClock();
15537 PonderNextMoveEvent (int newState)
15539 if (newState == appData.ponderNextMove) return;
15540 if (gameMode == EditPosition) EditPositionDone(TRUE);
15542 SendToProgram("hard\n", &first);
15543 if (gameMode == TwoMachinesPlay) {
15544 SendToProgram("hard\n", &second);
15547 SendToProgram("easy\n", &first);
15548 thinkOutput[0] = NULLCHAR;
15549 if (gameMode == TwoMachinesPlay) {
15550 SendToProgram("easy\n", &second);
15553 appData.ponderNextMove = newState;
15557 NewSettingEvent (int option, int *feature, char *command, int value)
15561 if (gameMode == EditPosition) EditPositionDone(TRUE);
15562 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
15563 if(feature == NULL || *feature) SendToProgram(buf, &first);
15564 if (gameMode == TwoMachinesPlay) {
15565 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
15570 ShowThinkingEvent ()
15571 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
15573 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
15574 int newState = appData.showThinking
15575 // [HGM] thinking: other features now need thinking output as well
15576 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
15578 if (oldState == newState) return;
15579 oldState = newState;
15580 if (gameMode == EditPosition) EditPositionDone(TRUE);
15582 SendToProgram("post\n", &first);
15583 if (gameMode == TwoMachinesPlay) {
15584 SendToProgram("post\n", &second);
15587 SendToProgram("nopost\n", &first);
15588 thinkOutput[0] = NULLCHAR;
15589 if (gameMode == TwoMachinesPlay) {
15590 SendToProgram("nopost\n", &second);
15593 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
15597 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
15599 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
15600 if (pr == NoProc) return;
15601 AskQuestion(title, question, replyPrefix, pr);
15605 TypeInEvent (char firstChar)
15607 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
15608 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
15609 gameMode == AnalyzeMode || gameMode == EditGame ||
15610 gameMode == EditPosition || gameMode == IcsExamining ||
15611 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
15612 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
15613 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
15614 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
15615 gameMode == Training) PopUpMoveDialog(firstChar);
15619 TypeInDoneEvent (char *move)
15622 int n, fromX, fromY, toX, toY;
15624 ChessMove moveType;
15627 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
15628 EditPositionPasteFEN(move);
15631 // [HGM] movenum: allow move number to be typed in any mode
15632 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
15636 // undocumented kludge: allow command-line option to be typed in!
15637 // (potentially fatal, and does not implement the effect of the option.)
15638 // should only be used for options that are values on which future decisions will be made,
15639 // and definitely not on options that would be used during initialization.
15640 if(strstr(move, "!!! -") == move) {
15641 ParseArgsFromString(move+4);
15645 if (gameMode != EditGame && currentMove != forwardMostMove &&
15646 gameMode != Training) {
15647 DisplayMoveError(_("Displayed move is not current"));
15649 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
15650 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
15651 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
15652 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
15653 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
15654 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
15656 DisplayMoveError(_("Could not parse move"));
15662 DisplayMove (int moveNumber)
15664 char message[MSG_SIZ];
15666 char cpThinkOutput[MSG_SIZ];
15668 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
15670 if (moveNumber == forwardMostMove - 1 ||
15671 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15673 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
15675 if (strchr(cpThinkOutput, '\n')) {
15676 *strchr(cpThinkOutput, '\n') = NULLCHAR;
15679 *cpThinkOutput = NULLCHAR;
15682 /* [AS] Hide thinking from human user */
15683 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
15684 *cpThinkOutput = NULLCHAR;
15685 if( thinkOutput[0] != NULLCHAR ) {
15688 for( i=0; i<=hiddenThinkOutputState; i++ ) {
15689 cpThinkOutput[i] = '.';
15691 cpThinkOutput[i] = NULLCHAR;
15692 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
15696 if (moveNumber == forwardMostMove - 1 &&
15697 gameInfo.resultDetails != NULL) {
15698 if (gameInfo.resultDetails[0] == NULLCHAR) {
15699 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
15701 snprintf(res, MSG_SIZ, " {%s} %s",
15702 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
15708 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
15709 DisplayMessage(res, cpThinkOutput);
15711 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
15712 WhiteOnMove(moveNumber) ? " " : ".. ",
15713 parseList[moveNumber], res);
15714 DisplayMessage(message, cpThinkOutput);
15719 DisplayComment (int moveNumber, char *text)
15721 char title[MSG_SIZ];
15723 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
15724 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
15726 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
15727 WhiteOnMove(moveNumber) ? " " : ".. ",
15728 parseList[moveNumber]);
15730 if (text != NULL && (appData.autoDisplayComment || commentUp))
15731 CommentPopUp(title, text);
15734 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
15735 * might be busy thinking or pondering. It can be omitted if your
15736 * gnuchess is configured to stop thinking immediately on any user
15737 * input. However, that gnuchess feature depends on the FIONREAD
15738 * ioctl, which does not work properly on some flavors of Unix.
15741 Attention (ChessProgramState *cps)
15744 if (!cps->useSigint) return;
15745 if (appData.noChessProgram || (cps->pr == NoProc)) return;
15746 switch (gameMode) {
15747 case MachinePlaysWhite:
15748 case MachinePlaysBlack:
15749 case TwoMachinesPlay:
15750 case IcsPlayingWhite:
15751 case IcsPlayingBlack:
15754 /* Skip if we know it isn't thinking */
15755 if (!cps->maybeThinking) return;
15756 if (appData.debugMode)
15757 fprintf(debugFP, "Interrupting %s\n", cps->which);
15758 InterruptChildProcess(cps->pr);
15759 cps->maybeThinking = FALSE;
15764 #endif /*ATTENTION*/
15770 if (whiteTimeRemaining <= 0) {
15773 if (appData.icsActive) {
15774 if (appData.autoCallFlag &&
15775 gameMode == IcsPlayingBlack && !blackFlag) {
15776 SendToICS(ics_prefix);
15777 SendToICS("flag\n");
15781 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
15783 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
15784 if (appData.autoCallFlag) {
15785 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
15792 if (blackTimeRemaining <= 0) {
15795 if (appData.icsActive) {
15796 if (appData.autoCallFlag &&
15797 gameMode == IcsPlayingWhite && !whiteFlag) {
15798 SendToICS(ics_prefix);
15799 SendToICS("flag\n");
15803 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
15805 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
15806 if (appData.autoCallFlag) {
15807 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
15818 CheckTimeControl ()
15820 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
15821 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
15824 * add time to clocks when time control is achieved ([HGM] now also used for increment)
15826 if ( !WhiteOnMove(forwardMostMove) ) {
15827 /* White made time control */
15828 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
15829 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
15830 /* [HGM] time odds: correct new time quota for time odds! */
15831 / WhitePlayer()->timeOdds;
15832 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
15834 lastBlack -= blackTimeRemaining;
15835 /* Black made time control */
15836 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
15837 / WhitePlayer()->other->timeOdds;
15838 lastWhite = whiteTimeRemaining;
15843 DisplayBothClocks ()
15845 int wom = gameMode == EditPosition ?
15846 !blackPlaysFirst : WhiteOnMove(currentMove);
15847 DisplayWhiteClock(whiteTimeRemaining, wom);
15848 DisplayBlackClock(blackTimeRemaining, !wom);
15852 /* Timekeeping seems to be a portability nightmare. I think everyone
15853 has ftime(), but I'm really not sure, so I'm including some ifdefs
15854 to use other calls if you don't. Clocks will be less accurate if
15855 you have neither ftime nor gettimeofday.
15858 /* VS 2008 requires the #include outside of the function */
15859 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
15860 #include <sys/timeb.h>
15863 /* Get the current time as a TimeMark */
15865 GetTimeMark (TimeMark *tm)
15867 #if HAVE_GETTIMEOFDAY
15869 struct timeval timeVal;
15870 struct timezone timeZone;
15872 gettimeofday(&timeVal, &timeZone);
15873 tm->sec = (long) timeVal.tv_sec;
15874 tm->ms = (int) (timeVal.tv_usec / 1000L);
15876 #else /*!HAVE_GETTIMEOFDAY*/
15879 // include <sys/timeb.h> / moved to just above start of function
15880 struct timeb timeB;
15883 tm->sec = (long) timeB.time;
15884 tm->ms = (int) timeB.millitm;
15886 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
15887 tm->sec = (long) time(NULL);
15893 /* Return the difference in milliseconds between two
15894 time marks. We assume the difference will fit in a long!
15897 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
15899 return 1000L*(tm2->sec - tm1->sec) +
15900 (long) (tm2->ms - tm1->ms);
15905 * Code to manage the game clocks.
15907 * In tournament play, black starts the clock and then white makes a move.
15908 * We give the human user a slight advantage if he is playing white---the
15909 * clocks don't run until he makes his first move, so it takes zero time.
15910 * Also, we don't account for network lag, so we could get out of sync
15911 * with GNU Chess's clock -- but then, referees are always right.
15914 static TimeMark tickStartTM;
15915 static long intendedTickLength;
15918 NextTickLength (long timeRemaining)
15920 long nominalTickLength, nextTickLength;
15922 if (timeRemaining > 0L && timeRemaining <= 10000L)
15923 nominalTickLength = 100L;
15925 nominalTickLength = 1000L;
15926 nextTickLength = timeRemaining % nominalTickLength;
15927 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
15929 return nextTickLength;
15932 /* Adjust clock one minute up or down */
15934 AdjustClock (Boolean which, int dir)
15936 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
15937 if(which) blackTimeRemaining += 60000*dir;
15938 else whiteTimeRemaining += 60000*dir;
15939 DisplayBothClocks();
15940 adjustedClock = TRUE;
15943 /* Stop clocks and reset to a fresh time control */
15947 (void) StopClockTimer();
15948 if (appData.icsActive) {
15949 whiteTimeRemaining = blackTimeRemaining = 0;
15950 } else if (searchTime) {
15951 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
15952 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
15953 } else { /* [HGM] correct new time quote for time odds */
15954 whiteTC = blackTC = fullTimeControlString;
15955 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
15956 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
15958 if (whiteFlag || blackFlag) {
15960 whiteFlag = blackFlag = FALSE;
15962 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
15963 DisplayBothClocks();
15964 adjustedClock = FALSE;
15967 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
15969 /* Decrement running clock by amount of time that has passed */
15973 long timeRemaining;
15974 long lastTickLength, fudge;
15977 if (!appData.clockMode) return;
15978 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
15982 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
15984 /* Fudge if we woke up a little too soon */
15985 fudge = intendedTickLength - lastTickLength;
15986 if (fudge < 0 || fudge > FUDGE) fudge = 0;
15988 if (WhiteOnMove(forwardMostMove)) {
15989 if(whiteNPS >= 0) lastTickLength = 0;
15990 timeRemaining = whiteTimeRemaining -= lastTickLength;
15991 if(timeRemaining < 0 && !appData.icsActive) {
15992 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
15993 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
15994 whiteStartMove = forwardMostMove; whiteTC = nextSession;
15995 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
15998 DisplayWhiteClock(whiteTimeRemaining - fudge,
15999 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16001 if(blackNPS >= 0) lastTickLength = 0;
16002 timeRemaining = blackTimeRemaining -= lastTickLength;
16003 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
16004 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
16006 blackStartMove = forwardMostMove;
16007 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
16010 DisplayBlackClock(blackTimeRemaining - fudge,
16011 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16013 if (CheckFlags()) return;
16016 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
16017 StartClockTimer(intendedTickLength);
16019 /* if the time remaining has fallen below the alarm threshold, sound the
16020 * alarm. if the alarm has sounded and (due to a takeback or time control
16021 * with increment) the time remaining has increased to a level above the
16022 * threshold, reset the alarm so it can sound again.
16025 if (appData.icsActive && appData.icsAlarm) {
16027 /* make sure we are dealing with the user's clock */
16028 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
16029 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
16032 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
16033 alarmSounded = FALSE;
16034 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
16036 alarmSounded = TRUE;
16042 /* A player has just moved, so stop the previously running
16043 clock and (if in clock mode) start the other one.
16044 We redisplay both clocks in case we're in ICS mode, because
16045 ICS gives us an update to both clocks after every move.
16046 Note that this routine is called *after* forwardMostMove
16047 is updated, so the last fractional tick must be subtracted
16048 from the color that is *not* on move now.
16051 SwitchClocks (int newMoveNr)
16053 long lastTickLength;
16055 int flagged = FALSE;
16059 if (StopClockTimer() && appData.clockMode) {
16060 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16061 if (!WhiteOnMove(forwardMostMove)) {
16062 if(blackNPS >= 0) lastTickLength = 0;
16063 blackTimeRemaining -= lastTickLength;
16064 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16065 // if(pvInfoList[forwardMostMove].time == -1)
16066 pvInfoList[forwardMostMove].time = // use GUI time
16067 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
16069 if(whiteNPS >= 0) lastTickLength = 0;
16070 whiteTimeRemaining -= lastTickLength;
16071 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16072 // if(pvInfoList[forwardMostMove].time == -1)
16073 pvInfoList[forwardMostMove].time =
16074 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
16076 flagged = CheckFlags();
16078 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
16079 CheckTimeControl();
16081 if (flagged || !appData.clockMode) return;
16083 switch (gameMode) {
16084 case MachinePlaysBlack:
16085 case MachinePlaysWhite:
16086 case BeginningOfGame:
16087 if (pausing) return;
16091 case PlayFromGameFile:
16099 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
16100 if(WhiteOnMove(forwardMostMove))
16101 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16102 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16106 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16107 whiteTimeRemaining : blackTimeRemaining);
16108 StartClockTimer(intendedTickLength);
16112 /* Stop both clocks */
16116 long lastTickLength;
16119 if (!StopClockTimer()) return;
16120 if (!appData.clockMode) return;
16124 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16125 if (WhiteOnMove(forwardMostMove)) {
16126 if(whiteNPS >= 0) lastTickLength = 0;
16127 whiteTimeRemaining -= lastTickLength;
16128 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
16130 if(blackNPS >= 0) lastTickLength = 0;
16131 blackTimeRemaining -= lastTickLength;
16132 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
16137 /* Start clock of player on move. Time may have been reset, so
16138 if clock is already running, stop and restart it. */
16142 (void) StopClockTimer(); /* in case it was running already */
16143 DisplayBothClocks();
16144 if (CheckFlags()) return;
16146 if (!appData.clockMode) return;
16147 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
16149 GetTimeMark(&tickStartTM);
16150 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16151 whiteTimeRemaining : blackTimeRemaining);
16153 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
16154 whiteNPS = blackNPS = -1;
16155 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
16156 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
16157 whiteNPS = first.nps;
16158 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
16159 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
16160 blackNPS = first.nps;
16161 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
16162 whiteNPS = second.nps;
16163 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
16164 blackNPS = second.nps;
16165 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
16167 StartClockTimer(intendedTickLength);
16171 TimeString (long ms)
16173 long second, minute, hour, day;
16175 static char buf[32];
16177 if (ms > 0 && ms <= 9900) {
16178 /* convert milliseconds to tenths, rounding up */
16179 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
16181 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
16185 /* convert milliseconds to seconds, rounding up */
16186 /* use floating point to avoid strangeness of integer division
16187 with negative dividends on many machines */
16188 second = (long) floor(((double) (ms + 999L)) / 1000.0);
16195 day = second / (60 * 60 * 24);
16196 second = second % (60 * 60 * 24);
16197 hour = second / (60 * 60);
16198 second = second % (60 * 60);
16199 minute = second / 60;
16200 second = second % 60;
16203 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
16204 sign, day, hour, minute, second);
16206 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
16208 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
16215 * This is necessary because some C libraries aren't ANSI C compliant yet.
16218 StrStr (char *string, char *match)
16222 length = strlen(match);
16224 for (i = strlen(string) - length; i >= 0; i--, string++)
16225 if (!strncmp(match, string, length))
16232 StrCaseStr (char *string, char *match)
16236 length = strlen(match);
16238 for (i = strlen(string) - length; i >= 0; i--, string++) {
16239 for (j = 0; j < length; j++) {
16240 if (ToLower(match[j]) != ToLower(string[j]))
16243 if (j == length) return string;
16251 StrCaseCmp (char *s1, char *s2)
16256 c1 = ToLower(*s1++);
16257 c2 = ToLower(*s2++);
16258 if (c1 > c2) return 1;
16259 if (c1 < c2) return -1;
16260 if (c1 == NULLCHAR) return 0;
16268 return isupper(c) ? tolower(c) : c;
16275 return islower(c) ? toupper(c) : c;
16277 #endif /* !_amigados */
16284 if ((ret = (char *) malloc(strlen(s) + 1)))
16286 safeStrCpy(ret, s, strlen(s)+1);
16292 StrSavePtr (char *s, char **savePtr)
16297 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
16298 safeStrCpy(*savePtr, s, strlen(s)+1);
16310 clock = time((time_t *)NULL);
16311 tm = localtime(&clock);
16312 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
16313 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
16314 return StrSave(buf);
16319 PositionToFEN (int move, char *overrideCastling)
16321 int i, j, fromX, fromY, toX, toY;
16328 whiteToPlay = (gameMode == EditPosition) ?
16329 !blackPlaysFirst : (move % 2 == 0);
16332 /* Piece placement data */
16333 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16334 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
16336 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16337 if (boards[move][i][j] == EmptySquare) {
16339 } else { ChessSquare piece = boards[move][i][j];
16340 if (emptycount > 0) {
16341 if(emptycount<10) /* [HGM] can be >= 10 */
16342 *p++ = '0' + emptycount;
16343 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16346 if(PieceToChar(piece) == '+') {
16347 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
16349 piece = (ChessSquare)(DEMOTED piece);
16351 *p++ = PieceToChar(piece);
16353 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
16354 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
16359 if (emptycount > 0) {
16360 if(emptycount<10) /* [HGM] can be >= 10 */
16361 *p++ = '0' + emptycount;
16362 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16369 /* [HGM] print Crazyhouse or Shogi holdings */
16370 if( gameInfo.holdingsWidth ) {
16371 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
16373 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
16374 piece = boards[move][i][BOARD_WIDTH-1];
16375 if( piece != EmptySquare )
16376 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
16377 *p++ = PieceToChar(piece);
16379 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
16380 piece = boards[move][BOARD_HEIGHT-i-1][0];
16381 if( piece != EmptySquare )
16382 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
16383 *p++ = PieceToChar(piece);
16386 if( q == p ) *p++ = '-';
16392 *p++ = whiteToPlay ? 'w' : 'b';
16395 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
16396 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
16398 if(nrCastlingRights) {
16400 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
16401 /* [HGM] write directly from rights */
16402 if(boards[move][CASTLING][2] != NoRights &&
16403 boards[move][CASTLING][0] != NoRights )
16404 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
16405 if(boards[move][CASTLING][2] != NoRights &&
16406 boards[move][CASTLING][1] != NoRights )
16407 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
16408 if(boards[move][CASTLING][5] != NoRights &&
16409 boards[move][CASTLING][3] != NoRights )
16410 *p++ = boards[move][CASTLING][3] + AAA;
16411 if(boards[move][CASTLING][5] != NoRights &&
16412 boards[move][CASTLING][4] != NoRights )
16413 *p++ = boards[move][CASTLING][4] + AAA;
16416 /* [HGM] write true castling rights */
16417 if( nrCastlingRights == 6 ) {
16418 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
16419 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
16420 if(boards[move][CASTLING][1] == BOARD_LEFT &&
16421 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
16422 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
16423 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
16424 if(boards[move][CASTLING][4] == BOARD_LEFT &&
16425 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
16428 if (q == p) *p++ = '-'; /* No castling rights */
16432 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
16433 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
16434 /* En passant target square */
16435 if (move > backwardMostMove) {
16436 fromX = moveList[move - 1][0] - AAA;
16437 fromY = moveList[move - 1][1] - ONE;
16438 toX = moveList[move - 1][2] - AAA;
16439 toY = moveList[move - 1][3] - ONE;
16440 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
16441 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
16442 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
16444 /* 2-square pawn move just happened */
16446 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16450 } else if(move == backwardMostMove) {
16451 // [HGM] perhaps we should always do it like this, and forget the above?
16452 if((signed char)boards[move][EP_STATUS] >= 0) {
16453 *p++ = boards[move][EP_STATUS] + AAA;
16454 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16465 /* [HGM] find reversible plies */
16466 { int i = 0, j=move;
16468 if (appData.debugMode) { int k;
16469 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
16470 for(k=backwardMostMove; k<=forwardMostMove; k++)
16471 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
16475 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
16476 if( j == backwardMostMove ) i += initialRulePlies;
16477 sprintf(p, "%d ", i);
16478 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
16480 /* Fullmove number */
16481 sprintf(p, "%d", (move / 2) + 1);
16483 return StrSave(buf);
16487 ParseFEN (Board board, int *blackPlaysFirst, char *fen)
16496 /* [HGM] by default clear Crazyhouse holdings, if present */
16497 if(gameInfo.holdingsWidth) {
16498 for(i=0; i<BOARD_HEIGHT; i++) {
16499 board[i][0] = EmptySquare; /* black holdings */
16500 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
16501 board[i][1] = (ChessSquare) 0; /* black counts */
16502 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
16506 /* Piece placement data */
16507 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16510 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
16511 if (*p == '/') p++;
16512 emptycount = gameInfo.boardWidth - j;
16513 while (emptycount--)
16514 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16516 #if(BOARD_FILES >= 10)
16517 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
16518 p++; emptycount=10;
16519 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16520 while (emptycount--)
16521 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16523 } else if (isdigit(*p)) {
16524 emptycount = *p++ - '0';
16525 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
16526 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16527 while (emptycount--)
16528 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16529 } else if (*p == '+' || isalpha(*p)) {
16530 if (j >= gameInfo.boardWidth) return FALSE;
16532 piece = CharToPiece(*++p);
16533 if(piece == EmptySquare) return FALSE; /* unknown piece */
16534 piece = (ChessSquare) (PROMOTED piece ); p++;
16535 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
16536 } else piece = CharToPiece(*p++);
16538 if(piece==EmptySquare) return FALSE; /* unknown piece */
16539 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
16540 piece = (ChessSquare) (PROMOTED piece);
16541 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
16544 board[i][(j++)+gameInfo.holdingsWidth] = piece;
16550 while (*p == '/' || *p == ' ') p++;
16552 /* [HGM] look for Crazyhouse holdings here */
16553 while(*p==' ') p++;
16554 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
16556 if(*p == '-' ) p++; /* empty holdings */ else {
16557 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
16558 /* if we would allow FEN reading to set board size, we would */
16559 /* have to add holdings and shift the board read so far here */
16560 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
16562 if((int) piece >= (int) BlackPawn ) {
16563 i = (int)piece - (int)BlackPawn;
16564 i = PieceToNumber((ChessSquare)i);
16565 if( i >= gameInfo.holdingsSize ) return FALSE;
16566 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
16567 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
16569 i = (int)piece - (int)WhitePawn;
16570 i = PieceToNumber((ChessSquare)i);
16571 if( i >= gameInfo.holdingsSize ) return FALSE;
16572 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
16573 board[i][BOARD_WIDTH-2]++; /* black holdings */
16580 while(*p == ' ') p++;
16584 if(appData.colorNickNames) {
16585 if( c == appData.colorNickNames[0] ) c = 'w'; else
16586 if( c == appData.colorNickNames[1] ) c = 'b';
16590 *blackPlaysFirst = FALSE;
16593 *blackPlaysFirst = TRUE;
16599 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
16600 /* return the extra info in global variiables */
16602 /* set defaults in case FEN is incomplete */
16603 board[EP_STATUS] = EP_UNKNOWN;
16604 for(i=0; i<nrCastlingRights; i++ ) {
16605 board[CASTLING][i] =
16606 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
16607 } /* assume possible unless obviously impossible */
16608 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
16609 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
16610 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
16611 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
16612 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
16613 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
16614 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
16615 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
16618 while(*p==' ') p++;
16619 if(nrCastlingRights) {
16620 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
16621 /* castling indicator present, so default becomes no castlings */
16622 for(i=0; i<nrCastlingRights; i++ ) {
16623 board[CASTLING][i] = NoRights;
16626 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
16627 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
16628 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
16629 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
16630 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
16632 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
16633 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
16634 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
16636 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
16637 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
16638 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
16639 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
16640 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
16641 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
16644 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
16645 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
16646 board[CASTLING][2] = whiteKingFile;
16649 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
16650 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
16651 board[CASTLING][2] = whiteKingFile;
16654 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
16655 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
16656 board[CASTLING][5] = blackKingFile;
16659 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
16660 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
16661 board[CASTLING][5] = blackKingFile;
16664 default: /* FRC castlings */
16665 if(c >= 'a') { /* black rights */
16666 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
16667 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
16668 if(i == BOARD_RGHT) break;
16669 board[CASTLING][5] = i;
16671 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
16672 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
16674 board[CASTLING][3] = c;
16676 board[CASTLING][4] = c;
16677 } else { /* white rights */
16678 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
16679 if(board[0][i] == WhiteKing) break;
16680 if(i == BOARD_RGHT) break;
16681 board[CASTLING][2] = i;
16682 c -= AAA - 'a' + 'A';
16683 if(board[0][c] >= WhiteKing) break;
16685 board[CASTLING][0] = c;
16687 board[CASTLING][1] = c;
16691 for(i=0; i<nrCastlingRights; i++)
16692 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
16693 if (appData.debugMode) {
16694 fprintf(debugFP, "FEN castling rights:");
16695 for(i=0; i<nrCastlingRights; i++)
16696 fprintf(debugFP, " %d", board[CASTLING][i]);
16697 fprintf(debugFP, "\n");
16700 while(*p==' ') p++;
16703 /* read e.p. field in games that know e.p. capture */
16704 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
16705 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
16707 p++; board[EP_STATUS] = EP_NONE;
16709 char c = *p++ - AAA;
16711 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
16712 if(*p >= '0' && *p <='9') p++;
16713 board[EP_STATUS] = c;
16718 if(sscanf(p, "%d", &i) == 1) {
16719 FENrulePlies = i; /* 50-move ply counter */
16720 /* (The move number is still ignored) */
16727 EditPositionPasteFEN (char *fen)
16730 Board initial_position;
16732 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
16733 DisplayError(_("Bad FEN position in clipboard"), 0);
16736 int savedBlackPlaysFirst = blackPlaysFirst;
16737 EditPositionEvent();
16738 blackPlaysFirst = savedBlackPlaysFirst;
16739 CopyBoard(boards[0], initial_position);
16740 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
16741 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
16742 DisplayBothClocks();
16743 DrawPosition(FALSE, boards[currentMove]);
16748 static char cseq[12] = "\\ ";
16751 set_cont_sequence (char *new_seq)
16756 // handle bad attempts to set the sequence
16758 return 0; // acceptable error - no debug
16760 len = strlen(new_seq);
16761 ret = (len > 0) && (len < sizeof(cseq));
16763 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
16764 else if (appData.debugMode)
16765 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
16770 reformat a source message so words don't cross the width boundary. internal
16771 newlines are not removed. returns the wrapped size (no null character unless
16772 included in source message). If dest is NULL, only calculate the size required
16773 for the dest buffer. lp argument indicats line position upon entry, and it's
16774 passed back upon exit.
16777 wrap (char *dest, char *src, int count, int width, int *lp)
16779 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
16781 cseq_len = strlen(cseq);
16782 old_line = line = *lp;
16783 ansi = len = clen = 0;
16785 for (i=0; i < count; i++)
16787 if (src[i] == '\033')
16790 // if we hit the width, back up
16791 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
16793 // store i & len in case the word is too long
16794 old_i = i, old_len = len;
16796 // find the end of the last word
16797 while (i && src[i] != ' ' && src[i] != '\n')
16803 // word too long? restore i & len before splitting it
16804 if ((old_i-i+clen) >= width)
16811 if (i && src[i-1] == ' ')
16814 if (src[i] != ' ' && src[i] != '\n')
16821 // now append the newline and continuation sequence
16826 strncpy(dest+len, cseq, cseq_len);
16834 dest[len] = src[i];
16838 if (src[i] == '\n')
16843 if (dest && appData.debugMode)
16845 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
16846 count, width, line, len, *lp);
16847 show_bytes(debugFP, src, count);
16848 fprintf(debugFP, "\ndest: ");
16849 show_bytes(debugFP, dest, len);
16850 fprintf(debugFP, "\n");
16852 *lp = dest ? line : old_line;
16857 // [HGM] vari: routines for shelving variations
16858 Boolean modeRestore = FALSE;
16861 PushInner (int firstMove, int lastMove)
16863 int i, j, nrMoves = lastMove - firstMove;
16865 // push current tail of game on stack
16866 savedResult[storedGames] = gameInfo.result;
16867 savedDetails[storedGames] = gameInfo.resultDetails;
16868 gameInfo.resultDetails = NULL;
16869 savedFirst[storedGames] = firstMove;
16870 savedLast [storedGames] = lastMove;
16871 savedFramePtr[storedGames] = framePtr;
16872 framePtr -= nrMoves; // reserve space for the boards
16873 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
16874 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
16875 for(j=0; j<MOVE_LEN; j++)
16876 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
16877 for(j=0; j<2*MOVE_LEN; j++)
16878 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
16879 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
16880 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
16881 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
16882 pvInfoList[firstMove+i-1].depth = 0;
16883 commentList[framePtr+i] = commentList[firstMove+i];
16884 commentList[firstMove+i] = NULL;
16888 forwardMostMove = firstMove; // truncate game so we can start variation
16892 PushTail (int firstMove, int lastMove)
16894 if(appData.icsActive) { // only in local mode
16895 forwardMostMove = currentMove; // mimic old ICS behavior
16898 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
16900 PushInner(firstMove, lastMove);
16901 if(storedGames == 1) GreyRevert(FALSE);
16902 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
16906 PopInner (Boolean annotate)
16909 char buf[8000], moveBuf[20];
16911 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
16912 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
16913 nrMoves = savedLast[storedGames] - currentMove;
16916 if(!WhiteOnMove(currentMove))
16917 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
16918 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
16919 for(i=currentMove; i<forwardMostMove; i++) {
16921 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
16922 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
16923 strcat(buf, moveBuf);
16924 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
16925 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
16929 for(i=1; i<=nrMoves; i++) { // copy last variation back
16930 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
16931 for(j=0; j<MOVE_LEN; j++)
16932 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
16933 for(j=0; j<2*MOVE_LEN; j++)
16934 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
16935 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
16936 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
16937 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
16938 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
16939 commentList[currentMove+i] = commentList[framePtr+i];
16940 commentList[framePtr+i] = NULL;
16942 if(annotate) AppendComment(currentMove+1, buf, FALSE);
16943 framePtr = savedFramePtr[storedGames];
16944 gameInfo.result = savedResult[storedGames];
16945 if(gameInfo.resultDetails != NULL) {
16946 free(gameInfo.resultDetails);
16948 gameInfo.resultDetails = savedDetails[storedGames];
16949 forwardMostMove = currentMove + nrMoves;
16953 PopTail (Boolean annotate)
16955 if(appData.icsActive) return FALSE; // only in local mode
16956 if(!storedGames) return FALSE; // sanity
16957 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
16959 PopInner(annotate);
16960 if(currentMove < forwardMostMove) ForwardEvent(); else
16961 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
16963 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
16969 { // remove all shelved variations
16971 for(i=0; i<storedGames; i++) {
16972 if(savedDetails[i])
16973 free(savedDetails[i]);
16974 savedDetails[i] = NULL;
16976 for(i=framePtr; i<MAX_MOVES; i++) {
16977 if(commentList[i]) free(commentList[i]);
16978 commentList[i] = NULL;
16980 framePtr = MAX_MOVES-1;
16985 LoadVariation (int index, char *text)
16986 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
16987 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
16988 int level = 0, move;
16990 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
16991 // first find outermost bracketing variation
16992 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
16993 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
16994 if(*p == '{') wait = '}'; else
16995 if(*p == '[') wait = ']'; else
16996 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
16997 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
16999 if(*p == wait) wait = NULLCHAR; // closing ]} found
17002 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
17003 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
17004 end[1] = NULLCHAR; // clip off comment beyond variation
17005 ToNrEvent(currentMove-1);
17006 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
17007 // kludge: use ParsePV() to append variation to game
17008 move = currentMove;
17009 ParsePV(start, TRUE, TRUE);
17010 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
17011 ClearPremoveHighlights();
17013 ToNrEvent(currentMove+1);