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 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 #define DoSleep( n ) if( (n) != 0 ) Sleep( (n) );
60 int flock(int f, int code);
67 #define DoSleep( n ) if( (n) >= 0) sleep(n)
78 #include <sys/types.h>
87 #else /* not STDC_HEADERS */
90 # else /* not HAVE_STRING_H */
92 # endif /* not HAVE_STRING_H */
93 #endif /* not STDC_HEADERS */
96 # include <sys/fcntl.h>
97 #else /* not HAVE_SYS_FCNTL_H */
100 # endif /* HAVE_FCNTL_H */
101 #endif /* not HAVE_SYS_FCNTL_H */
103 #if TIME_WITH_SYS_TIME
104 # include <sys/time.h>
108 # include <sys/time.h>
114 #if defined(_amigados) && !defined(__GNUC__)
119 extern int gettimeofday(struct timeval *, struct timezone *);
127 #include "frontend.h"
134 #include "backendz.h"
138 # define _(s) gettext (s)
139 # define N_(s) gettext_noop (s)
140 # define T_(s) gettext(s)
153 /* A point in time */
155 long sec; /* Assuming this is >= 32 bits */
156 int ms; /* Assuming this is >= 16 bits */
159 int establish P((void));
160 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
161 char *buf, int count, int error));
162 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
163 char *buf, int count, int error));
164 void ics_printf P((char *format, ...));
165 void SendToICS P((char *s));
166 void SendToICSDelayed P((char *s, long msdelay));
167 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
168 void HandleMachineMove P((char *message, ChessProgramState *cps));
169 int AutoPlayOneMove P((void));
170 int LoadGameOneMove P((ChessMove readAhead));
171 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
172 int LoadPositionFromFile P((char *filename, int n, char *title));
173 int SavePositionToFile P((char *filename));
174 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
176 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
177 void ShowMove P((int fromX, int fromY, int toX, int toY));
178 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
179 /*char*/int promoChar));
180 void BackwardInner P((int target));
181 void ForwardInner P((int target));
182 int Adjudicate P((ChessProgramState *cps));
183 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
184 void EditPositionDone P((Boolean fakeRights));
185 void PrintOpponents P((FILE *fp));
186 void PrintPosition P((FILE *fp, int move));
187 void StartChessProgram P((ChessProgramState *cps));
188 void SendToProgram P((char *message, ChessProgramState *cps));
189 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
190 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
191 char *buf, int count, int error));
192 void SendTimeControl P((ChessProgramState *cps,
193 int mps, long tc, int inc, int sd, int st));
194 char *TimeControlTagValue P((void));
195 void Attention P((ChessProgramState *cps));
196 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
197 int ResurrectChessProgram P((void));
198 void DisplayComment P((int moveNumber, char *text));
199 void DisplayMove P((int moveNumber));
201 void ParseGameHistory P((char *game));
202 void ParseBoard12 P((char *string));
203 void KeepAlive P((void));
204 void StartClocks P((void));
205 void SwitchClocks P((int nr));
206 void StopClocks P((void));
207 void ResetClocks P((void));
208 char *PGNDate P((void));
209 void SetGameInfo P((void));
210 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
211 int RegisterMove P((void));
212 void MakeRegisteredMove P((void));
213 void TruncateGame P((void));
214 int looking_at P((char *, int *, char *));
215 void CopyPlayerNameIntoFileName P((char **, char *));
216 char *SavePart P((char *));
217 int SaveGameOldStyle P((FILE *));
218 int SaveGamePGN P((FILE *));
219 void GetTimeMark P((TimeMark *));
220 long SubtractTimeMarks P((TimeMark *, TimeMark *));
221 int CheckFlags P((void));
222 long NextTickLength P((long));
223 void CheckTimeControl P((void));
224 void show_bytes P((FILE *, char *, int));
225 int string_to_rating P((char *str));
226 void ParseFeatures P((char* args, ChessProgramState *cps));
227 void InitBackEnd3 P((void));
228 void FeatureDone P((ChessProgramState* cps, int val));
229 void InitChessProgram P((ChessProgramState *cps, int setup));
230 void OutputKibitz(int window, char *text);
231 int PerpetualChase(int first, int last);
232 int EngineOutputIsUp();
233 void InitDrawingSizes(int x, int y);
234 void NextMatchGame P((void));
235 int NextTourneyGame P((int nr, int *swap));
236 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
237 FILE *WriteTourneyFile P((char *results, FILE *f));
238 void DisplayTwoMachinesTitle P(());
241 extern void ConsoleCreate();
244 ChessProgramState *WhitePlayer();
245 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
246 int VerifyDisplayMode P(());
248 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
249 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
250 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
251 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
252 void ics_update_width P((int new_width));
253 extern char installDir[MSG_SIZ];
254 VariantClass startVariant; /* [HGM] nicks: initial variant */
257 extern int tinyLayout, smallLayout;
258 ChessProgramStats programStats;
259 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
261 static int exiting = 0; /* [HGM] moved to top */
262 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
263 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
264 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
265 int partnerHighlight[2];
266 Boolean partnerBoardValid = 0;
267 char partnerStatus[MSG_SIZ];
269 Boolean originalFlip;
270 Boolean twoBoards = 0;
271 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
272 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
273 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
274 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
275 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
276 int opponentKibitzes;
277 int lastSavedGame; /* [HGM] save: ID of game */
278 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
279 extern int chatCount;
281 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
282 char lastMsg[MSG_SIZ];
283 ChessSquare pieceSweep = EmptySquare;
284 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
285 int promoDefaultAltered;
287 /* States for ics_getting_history */
289 #define H_REQUESTED 1
290 #define H_GOT_REQ_HEADER 2
291 #define H_GOT_UNREQ_HEADER 3
292 #define H_GETTING_MOVES 4
293 #define H_GOT_UNWANTED_HEADER 5
295 /* whosays values for GameEnds */
304 /* Maximum number of games in a cmail message */
305 #define CMAIL_MAX_GAMES 20
307 /* Different types of move when calling RegisterMove */
309 #define CMAIL_RESIGN 1
311 #define CMAIL_ACCEPT 3
313 /* Different types of result to remember for each game */
314 #define CMAIL_NOT_RESULT 0
315 #define CMAIL_OLD_RESULT 1
316 #define CMAIL_NEW_RESULT 2
318 /* Telnet protocol constants */
329 safeStrCpy( char *dst, const char *src, size_t count )
332 assert( dst != NULL );
333 assert( src != NULL );
336 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
337 if( i == count && dst[count-1] != NULLCHAR)
339 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
340 if(appData.debugMode)
341 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
347 /* Some compiler can't cast u64 to double
348 * This function do the job for us:
350 * We use the highest bit for cast, this only
351 * works if the highest bit is not
352 * in use (This should not happen)
354 * We used this for all compiler
357 u64ToDouble(u64 value)
360 u64 tmp = value & u64Const(0x7fffffffffffffff);
361 r = (double)(s64)tmp;
362 if (value & u64Const(0x8000000000000000))
363 r += 9.2233720368547758080e18; /* 2^63 */
367 /* Fake up flags for now, as we aren't keeping track of castling
368 availability yet. [HGM] Change of logic: the flag now only
369 indicates the type of castlings allowed by the rule of the game.
370 The actual rights themselves are maintained in the array
371 castlingRights, as part of the game history, and are not probed
377 int flags = F_ALL_CASTLE_OK;
378 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
379 switch (gameInfo.variant) {
381 flags &= ~F_ALL_CASTLE_OK;
382 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
383 flags |= F_IGNORE_CHECK;
385 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
388 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
390 case VariantKriegspiel:
391 flags |= F_KRIEGSPIEL_CAPTURE;
393 case VariantCapaRandom:
394 case VariantFischeRandom:
395 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
396 case VariantNoCastle:
397 case VariantShatranj:
401 flags &= ~F_ALL_CASTLE_OK;
409 FILE *gameFileFP, *debugFP;
412 [AS] Note: sometimes, the sscanf() function is used to parse the input
413 into a fixed-size buffer. Because of this, we must be prepared to
414 receive strings as long as the size of the input buffer, which is currently
415 set to 4K for Windows and 8K for the rest.
416 So, we must either allocate sufficiently large buffers here, or
417 reduce the size of the input buffer in the input reading part.
420 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
421 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
422 char thinkOutput1[MSG_SIZ*10];
424 ChessProgramState first, second, pairing;
426 /* premove variables */
429 int premoveFromX = 0;
430 int premoveFromY = 0;
431 int premovePromoChar = 0;
433 Boolean alarmSounded;
434 /* end premove variables */
436 char *ics_prefix = "$";
437 int ics_type = ICS_GENERIC;
439 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
440 int pauseExamForwardMostMove = 0;
441 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
442 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
443 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
444 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
445 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
446 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
447 int whiteFlag = FALSE, blackFlag = FALSE;
448 int userOfferedDraw = FALSE;
449 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
450 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
451 int cmailMoveType[CMAIL_MAX_GAMES];
452 long ics_clock_paused = 0;
453 ProcRef icsPR = NoProc, cmailPR = NoProc;
454 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
455 GameMode gameMode = BeginningOfGame;
456 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
457 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
458 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
459 int hiddenThinkOutputState = 0; /* [AS] */
460 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
461 int adjudicateLossPlies = 6;
462 char white_holding[64], black_holding[64];
463 TimeMark lastNodeCountTime;
464 long lastNodeCount=0;
465 int shiftKey; // [HGM] set by mouse handler
467 int have_sent_ICS_logon = 0;
469 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
470 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack;
471 long timeControl_2; /* [AS] Allow separate time controls */
472 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC; /* [HGM] secondary TC: merge of MPS, TC and inc */
473 long timeRemaining[2][MAX_MOVES];
474 int matchGame = 0, nextGame = 0, roundNr = 0;
475 Boolean waitingForGame = FALSE;
476 TimeMark programStartTime, pauseStart;
477 char ics_handle[MSG_SIZ];
478 int have_set_title = 0;
480 /* animateTraining preserves the state of appData.animate
481 * when Training mode is activated. This allows the
482 * response to be animated when appData.animate == TRUE and
483 * appData.animateDragging == TRUE.
485 Boolean animateTraining;
491 Board boards[MAX_MOVES];
492 /* [HGM] Following 7 needed for accurate legality tests: */
493 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
494 signed char initialRights[BOARD_FILES];
495 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
496 int initialRulePlies, FENrulePlies;
497 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
499 Boolean shuffleOpenings;
500 int mute; // mute all sounds
502 // [HGM] vari: next 12 to save and restore variations
503 #define MAX_VARIATIONS 10
504 int framePtr = MAX_MOVES-1; // points to free stack entry
506 int savedFirst[MAX_VARIATIONS];
507 int savedLast[MAX_VARIATIONS];
508 int savedFramePtr[MAX_VARIATIONS];
509 char *savedDetails[MAX_VARIATIONS];
510 ChessMove savedResult[MAX_VARIATIONS];
512 void PushTail P((int firstMove, int lastMove));
513 Boolean PopTail P((Boolean annotate));
514 void PushInner P((int firstMove, int lastMove));
515 void PopInner P((Boolean annotate));
516 void CleanupTail P((void));
518 ChessSquare FIDEArray[2][BOARD_FILES] = {
519 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
520 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
521 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
522 BlackKing, BlackBishop, BlackKnight, BlackRook }
525 ChessSquare twoKingsArray[2][BOARD_FILES] = {
526 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
527 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
528 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
529 BlackKing, BlackKing, BlackKnight, BlackRook }
532 ChessSquare KnightmateArray[2][BOARD_FILES] = {
533 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
534 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
535 { BlackRook, BlackMan, BlackBishop, BlackQueen,
536 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
539 ChessSquare SpartanArray[2][BOARD_FILES] = {
540 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
541 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
542 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
543 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
546 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
547 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
548 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
549 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
550 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
553 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
554 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
555 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
556 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
557 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
560 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
561 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
562 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
563 { BlackRook, BlackKnight, BlackMan, BlackFerz,
564 BlackKing, BlackMan, BlackKnight, BlackRook }
568 #if (BOARD_FILES>=10)
569 ChessSquare ShogiArray[2][BOARD_FILES] = {
570 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
571 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
572 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
573 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
576 ChessSquare XiangqiArray[2][BOARD_FILES] = {
577 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
578 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
579 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
580 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
583 ChessSquare CapablancaArray[2][BOARD_FILES] = {
584 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
585 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
586 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
587 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
590 ChessSquare GreatArray[2][BOARD_FILES] = {
591 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
592 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
593 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
594 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
597 ChessSquare JanusArray[2][BOARD_FILES] = {
598 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
599 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
600 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
601 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
604 ChessSquare GrandArray[2][BOARD_FILES] = {
605 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
606 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
607 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
608 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
612 ChessSquare GothicArray[2][BOARD_FILES] = {
613 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
614 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
615 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
616 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
619 #define GothicArray CapablancaArray
623 ChessSquare FalconArray[2][BOARD_FILES] = {
624 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
625 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
626 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
627 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
630 #define FalconArray CapablancaArray
633 #else // !(BOARD_FILES>=10)
634 #define XiangqiPosition FIDEArray
635 #define CapablancaArray FIDEArray
636 #define GothicArray FIDEArray
637 #define GreatArray FIDEArray
638 #endif // !(BOARD_FILES>=10)
640 #if (BOARD_FILES>=12)
641 ChessSquare CourierArray[2][BOARD_FILES] = {
642 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
643 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
644 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
645 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
647 #else // !(BOARD_FILES>=12)
648 #define CourierArray CapablancaArray
649 #endif // !(BOARD_FILES>=12)
652 Board initialPosition;
655 /* Convert str to a rating. Checks for special cases of "----",
657 "++++", etc. Also strips ()'s */
659 string_to_rating(str)
662 while(*str && !isdigit(*str)) ++str;
664 return 0; /* One of the special "no rating" cases */
672 /* Init programStats */
673 programStats.movelist[0] = 0;
674 programStats.depth = 0;
675 programStats.nr_moves = 0;
676 programStats.moves_left = 0;
677 programStats.nodes = 0;
678 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
679 programStats.score = 0;
680 programStats.got_only_move = 0;
681 programStats.got_fail = 0;
682 programStats.line_is_book = 0;
687 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
688 if (appData.firstPlaysBlack) {
689 first.twoMachinesColor = "black\n";
690 second.twoMachinesColor = "white\n";
692 first.twoMachinesColor = "white\n";
693 second.twoMachinesColor = "black\n";
696 first.other = &second;
697 second.other = &first;
700 if(appData.timeOddsMode) {
701 norm = appData.timeOdds[0];
702 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
704 first.timeOdds = appData.timeOdds[0]/norm;
705 second.timeOdds = appData.timeOdds[1]/norm;
708 if(programVersion) free(programVersion);
709 if (appData.noChessProgram) {
710 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
711 sprintf(programVersion, "%s", PACKAGE_STRING);
713 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
714 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
715 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
720 UnloadEngine(ChessProgramState *cps)
722 /* Kill off first chess program */
723 if (cps->isr != NULL)
724 RemoveInputSource(cps->isr);
727 if (cps->pr != NoProc) {
729 DoSleep( appData.delayBeforeQuit );
730 SendToProgram("quit\n", cps);
731 DoSleep( appData.delayAfterQuit );
732 DestroyChildProcess(cps->pr, cps->useSigterm);
735 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
739 ClearOptions(ChessProgramState *cps)
742 cps->nrOptions = cps->comboCnt = 0;
743 for(i=0; i<MAX_OPTIONS; i++) {
744 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
745 cps->option[i].textValue = 0;
749 char *engineNames[] = {
755 InitEngine(ChessProgramState *cps, int n)
756 { // [HGM] all engine initialiation put in a function that does one engine
760 cps->which = engineNames[n];
761 cps->maybeThinking = FALSE;
765 cps->sendDrawOffers = 1;
767 cps->program = appData.chessProgram[n];
768 cps->host = appData.host[n];
769 cps->dir = appData.directory[n];
770 cps->initString = appData.engInitString[n];
771 cps->computerString = appData.computerString[n];
772 cps->useSigint = TRUE;
773 cps->useSigterm = TRUE;
774 cps->reuse = appData.reuse[n];
775 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
776 cps->useSetboard = FALSE;
778 cps->usePing = FALSE;
781 cps->usePlayother = FALSE;
782 cps->useColors = TRUE;
783 cps->useUsermove = FALSE;
784 cps->sendICS = FALSE;
785 cps->sendName = appData.icsActive;
786 cps->sdKludge = FALSE;
787 cps->stKludge = FALSE;
788 TidyProgramName(cps->program, cps->host, cps->tidy);
790 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
791 cps->analysisSupport = 2; /* detect */
792 cps->analyzing = FALSE;
793 cps->initDone = FALSE;
795 /* New features added by Tord: */
796 cps->useFEN960 = FALSE;
797 cps->useOOCastle = TRUE;
798 /* End of new features added by Tord. */
799 cps->fenOverride = appData.fenOverride[n];
801 /* [HGM] time odds: set factor for each machine */
802 cps->timeOdds = appData.timeOdds[n];
804 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
805 cps->accumulateTC = appData.accumulateTC[n];
806 cps->maxNrOfSessions = 1;
811 cps->supportsNPS = UNKNOWN;
812 cps->memSize = FALSE;
813 cps->maxCores = FALSE;
814 cps->egtFormats[0] = NULLCHAR;
817 cps->optionSettings = appData.engOptions[n];
819 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
820 cps->isUCI = appData.isUCI[n]; /* [AS] */
821 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
823 if (appData.protocolVersion[n] > PROTOVER
824 || appData.protocolVersion[n] < 1)
829 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
830 appData.protocolVersion[n]);
831 if( (len > MSG_SIZ) && appData.debugMode )
832 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
834 DisplayFatalError(buf, 0, 2);
838 cps->protocolVersion = appData.protocolVersion[n];
841 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
844 ChessProgramState *savCps;
850 if(WaitForEngine(savCps, LoadEngine)) return;
851 CommonEngineInit(); // recalculate time odds
852 if(gameInfo.variant != StringToVariant(appData.variant)) {
853 // we changed variant when loading the engine; this forces us to reset
854 Reset(TRUE, savCps != &first);
855 EditGameEvent(); // for consistency with other path, as Reset changes mode
857 InitChessProgram(savCps, FALSE);
858 SendToProgram("force\n", savCps);
859 DisplayMessage("", "");
860 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
861 for (i = backwardMostMove; i < forwardMostMove; i++) SendMoveToProgram(i, savCps);
867 ReplaceEngine(ChessProgramState *cps, int n)
871 appData.noChessProgram = FALSE;
872 appData.clockMode = TRUE;
875 if(n) return; // only startup first engine immediately; second can wait
876 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
880 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
881 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
883 static char resetOptions[] =
884 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
885 "-firstOptions \"\" -firstNPS -1 -fn \"\"";
888 Load(ChessProgramState *cps, int i)
890 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ];
891 if(engineLine[0]) { // an engine was selected from the combo box
892 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
893 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
894 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL;
895 ParseArgsFromString(buf);
897 ReplaceEngine(cps, i);
901 while(q = strchr(p, SLASH)) p = q+1;
902 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
903 if(engineDir[0] != NULLCHAR)
904 appData.directory[i] = engineDir;
905 else if(p != engineName) { // derive directory from engine path, when not given
907 appData.directory[i] = strdup(engineName);
909 } else appData.directory[i] = ".";
910 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
912 snprintf(command, MSG_SIZ, "%s %s", p, params);
915 appData.chessProgram[i] = strdup(p);
916 appData.isUCI[i] = isUCI;
917 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
918 appData.hasOwnBookUCI[i] = hasBook;
919 if(!nickName[0]) useNick = FALSE;
920 if(useNick) ASSIGN(appData.pgnName[i], nickName);
924 q = firstChessProgramNames;
925 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
926 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
927 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
928 quote, p, quote, appData.directory[i],
929 useNick ? " -fn \"" : "",
930 useNick ? nickName : "",
932 v1 ? " -firstProtocolVersion 1" : "",
933 hasBook ? "" : " -fNoOwnBookUCI",
934 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
935 storeVariant ? " -variant " : "",
936 storeVariant ? VariantName(gameInfo.variant) : "");
937 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
938 snprintf(firstChessProgramNames, len, "%s%s", q, buf);
941 ReplaceEngine(cps, i);
947 int matched, min, sec;
949 * Parse timeControl resource
951 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
952 appData.movesPerSession)) {
954 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
955 DisplayFatalError(buf, 0, 2);
959 * Parse searchTime resource
961 if (*appData.searchTime != NULLCHAR) {
962 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
964 searchTime = min * 60;
965 } else if (matched == 2) {
966 searchTime = min * 60 + sec;
969 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
970 DisplayFatalError(buf, 0, 2);
979 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
980 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
982 GetTimeMark(&programStartTime);
983 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
984 appData.seedBase = random() + (random()<<15);
985 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
988 programStats.ok_to_send = 1;
989 programStats.seen_stat = 0;
992 * Initialize game list
998 * Internet chess server status
1000 if (appData.icsActive) {
1001 appData.matchMode = FALSE;
1002 appData.matchGames = 0;
1004 appData.noChessProgram = !appData.zippyPlay;
1006 appData.zippyPlay = FALSE;
1007 appData.zippyTalk = FALSE;
1008 appData.noChessProgram = TRUE;
1010 if (*appData.icsHelper != NULLCHAR) {
1011 appData.useTelnet = TRUE;
1012 appData.telnetProgram = appData.icsHelper;
1015 appData.zippyTalk = appData.zippyPlay = FALSE;
1018 /* [AS] Initialize pv info list [HGM] and game state */
1022 for( i=0; i<=framePtr; i++ ) {
1023 pvInfoList[i].depth = -1;
1024 boards[i][EP_STATUS] = EP_NONE;
1025 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1031 /* [AS] Adjudication threshold */
1032 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1034 InitEngine(&first, 0);
1035 InitEngine(&second, 1);
1038 pairing.which = "pairing"; // pairing engine
1039 pairing.pr = NoProc;
1041 pairing.program = appData.pairingEngine;
1042 pairing.host = "localhost";
1045 if (appData.icsActive) {
1046 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1047 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1048 appData.clockMode = FALSE;
1049 first.sendTime = second.sendTime = 0;
1053 /* Override some settings from environment variables, for backward
1054 compatibility. Unfortunately it's not feasible to have the env
1055 vars just set defaults, at least in xboard. Ugh.
1057 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1062 if (!appData.icsActive) {
1066 /* Check for variants that are supported only in ICS mode,
1067 or not at all. Some that are accepted here nevertheless
1068 have bugs; see comments below.
1070 VariantClass variant = StringToVariant(appData.variant);
1072 case VariantBughouse: /* need four players and two boards */
1073 case VariantKriegspiel: /* need to hide pieces and move details */
1074 /* case VariantFischeRandom: (Fabien: moved below) */
1075 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1076 if( (len > MSG_SIZ) && appData.debugMode )
1077 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1079 DisplayFatalError(buf, 0, 2);
1082 case VariantUnknown:
1083 case VariantLoadable:
1093 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1094 if( (len > MSG_SIZ) && appData.debugMode )
1095 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1097 DisplayFatalError(buf, 0, 2);
1100 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1101 case VariantFairy: /* [HGM] TestLegality definitely off! */
1102 case VariantGothic: /* [HGM] should work */
1103 case VariantCapablanca: /* [HGM] should work */
1104 case VariantCourier: /* [HGM] initial forced moves not implemented */
1105 case VariantShogi: /* [HGM] could still mate with pawn drop */
1106 case VariantKnightmate: /* [HGM] should work */
1107 case VariantCylinder: /* [HGM] untested */
1108 case VariantFalcon: /* [HGM] untested */
1109 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1110 offboard interposition not understood */
1111 case VariantNormal: /* definitely works! */
1112 case VariantWildCastle: /* pieces not automatically shuffled */
1113 case VariantNoCastle: /* pieces not automatically shuffled */
1114 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1115 case VariantLosers: /* should work except for win condition,
1116 and doesn't know captures are mandatory */
1117 case VariantSuicide: /* should work except for win condition,
1118 and doesn't know captures are mandatory */
1119 case VariantGiveaway: /* should work except for win condition,
1120 and doesn't know captures are mandatory */
1121 case VariantTwoKings: /* should work */
1122 case VariantAtomic: /* should work except for win condition */
1123 case Variant3Check: /* should work except for win condition */
1124 case VariantShatranj: /* should work except for all win conditions */
1125 case VariantMakruk: /* should work except for draw countdown */
1126 case VariantBerolina: /* might work if TestLegality is off */
1127 case VariantCapaRandom: /* should work */
1128 case VariantJanus: /* should work */
1129 case VariantSuper: /* experimental */
1130 case VariantGreat: /* experimental, requires legality testing to be off */
1131 case VariantSChess: /* S-Chess, should work */
1132 case VariantGrand: /* should work */
1133 case VariantSpartan: /* should work */
1140 int NextIntegerFromString( char ** str, long * value )
1145 while( *s == ' ' || *s == '\t' ) {
1151 if( *s >= '0' && *s <= '9' ) {
1152 while( *s >= '0' && *s <= '9' ) {
1153 *value = *value * 10 + (*s - '0');
1165 int NextTimeControlFromString( char ** str, long * value )
1168 int result = NextIntegerFromString( str, &temp );
1171 *value = temp * 60; /* Minutes */
1172 if( **str == ':' ) {
1174 result = NextIntegerFromString( str, &temp );
1175 *value += temp; /* Seconds */
1182 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc, int *incType)
1183 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1184 int result = -1, type = 0; long temp, temp2;
1186 if(**str != ':') return -1; // old params remain in force!
1188 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1189 if( NextIntegerFromString( str, &temp ) ) return -1;
1190 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1193 /* time only: incremental or sudden-death time control */
1194 if(**str == '+') { /* increment follows; read it */
1196 if(**str == '!') type = *(*str)++; // Bronstein TC
1197 if(result = NextIntegerFromString( str, &temp2)) return -1;
1198 *inc = temp2 * 1000;
1199 if(**str == '.') { // read fraction of increment
1200 char *start = ++(*str);
1201 if(result = NextIntegerFromString( str, &temp2)) return -1;
1203 while(start++ < *str) temp2 /= 10;
1207 *moves = 0; *tc = temp * 1000; *incType = type;
1211 (*str)++; /* classical time control */
1212 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1223 int GetTimeQuota(int movenr, int lastUsed, char *tcString)
1224 { /* [HGM] get time to add from the multi-session time-control string */
1225 int incType, moves=1; /* kludge to force reading of first session */
1226 long time, increment;
1229 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1230 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", tcString);
1232 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1233 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1234 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1235 if(movenr == -1) return time; /* last move before new session */
1236 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1237 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1238 if(!moves) return increment; /* current session is incremental */
1239 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1240 } while(movenr >= -1); /* try again for next session */
1242 return 0; // no new time quota on this move
1246 ParseTimeControl(tc, ti, mps)
1253 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1256 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1257 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1258 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1262 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1264 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1267 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1269 snprintf(buf, MSG_SIZ, ":%s", mytc);
1271 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1273 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1278 /* Parse second time control */
1281 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1289 timeControl_2 = tc2 * 1000;
1299 timeControl = tc1 * 1000;
1302 timeIncrement = ti * 1000; /* convert to ms */
1303 movesPerSession = 0;
1306 movesPerSession = mps;
1314 if (appData.debugMode) {
1315 fprintf(debugFP, "%s\n", programVersion);
1318 set_cont_sequence(appData.wrapContSeq);
1319 if (appData.matchGames > 0) {
1320 appData.matchMode = TRUE;
1321 } else if (appData.matchMode) {
1322 appData.matchGames = 1;
1324 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1325 appData.matchGames = appData.sameColorGames;
1326 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1327 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1328 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1331 if (appData.noChessProgram || first.protocolVersion == 1) {
1334 /* kludge: allow timeout for initial "feature" commands */
1336 DisplayMessage("", _("Starting chess program"));
1337 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1342 CalculateIndex(int index, int gameNr)
1343 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1345 if(index > 0) return index; // fixed nmber
1346 if(index == 0) return 1;
1347 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1348 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1353 LoadGameOrPosition(int gameNr)
1354 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1355 if (*appData.loadGameFile != NULLCHAR) {
1356 if (!LoadGameFromFile(appData.loadGameFile,
1357 CalculateIndex(appData.loadGameIndex, gameNr),
1358 appData.loadGameFile, FALSE)) {
1359 DisplayFatalError(_("Bad game file"), 0, 1);
1362 } else if (*appData.loadPositionFile != NULLCHAR) {
1363 if (!LoadPositionFromFile(appData.loadPositionFile,
1364 CalculateIndex(appData.loadPositionIndex, gameNr),
1365 appData.loadPositionFile)) {
1366 DisplayFatalError(_("Bad position file"), 0, 1);
1374 ReserveGame(int gameNr, char resChar)
1376 FILE *tf = fopen(appData.tourneyFile, "r+");
1377 char *p, *q, c, buf[MSG_SIZ];
1378 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1379 safeStrCpy(buf, lastMsg, MSG_SIZ);
1380 DisplayMessage(_("Pick new game"), "");
1381 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1382 ParseArgsFromFile(tf);
1383 p = q = appData.results;
1384 if(appData.debugMode) {
1385 char *r = appData.participants;
1386 fprintf(debugFP, "results = '%s'\n", p);
1387 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1388 fprintf(debugFP, "\n");
1390 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1392 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1393 safeStrCpy(q, p, strlen(p) + 2);
1394 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1395 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1396 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1397 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1400 fseek(tf, -(strlen(p)+4), SEEK_END);
1402 if(c != '"') // depending on DOS or Unix line endings we can be one off
1403 fseek(tf, -(strlen(p)+2), SEEK_END);
1404 else fseek(tf, -(strlen(p)+3), SEEK_END);
1405 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1406 DisplayMessage(buf, "");
1407 free(p); appData.results = q;
1408 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1409 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1410 UnloadEngine(&first); // next game belongs to other pairing;
1411 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1416 MatchEvent(int mode)
1417 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1419 if(matchMode) { // already in match mode: switch it off
1421 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1424 // if(gameMode != BeginningOfGame) {
1425 // DisplayError(_("You can only start a match from the initial position."), 0);
1429 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1430 /* Set up machine vs. machine match */
1432 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1433 if(appData.tourneyFile[0]) {
1435 if(nextGame > appData.matchGames) {
1437 if(strchr(appData.results, '*') == NULL) {
1439 appData.tourneyCycles++;
1440 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1442 NextTourneyGame(-1, &dummy);
1444 if(nextGame <= appData.matchGames) {
1445 DisplayNote(_("You restarted an already completed tourney\nOne more cycle will now be added to it\nGames commence in 10 sec"));
1447 ScheduleDelayedEvent(NextMatchGame, 10000);
1452 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1453 DisplayError(buf, 0);
1454 appData.tourneyFile[0] = 0;
1458 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1459 DisplayFatalError(_("Can't have a match with no chess programs"),
1464 matchGame = roundNr = 1;
1465 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1470 InitBackEnd3 P((void))
1472 GameMode initialMode;
1476 InitChessProgram(&first, startedFromSetupPosition);
1478 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1479 free(programVersion);
1480 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1481 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1484 if (appData.icsActive) {
1486 /* [DM] Make a console window if needed [HGM] merged ifs */
1492 if (*appData.icsCommPort != NULLCHAR)
1493 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1494 appData.icsCommPort);
1496 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1497 appData.icsHost, appData.icsPort);
1499 if( (len > MSG_SIZ) && appData.debugMode )
1500 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1502 DisplayFatalError(buf, err, 1);
1507 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1509 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1510 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1511 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1512 } else if (appData.noChessProgram) {
1518 if (*appData.cmailGameName != NULLCHAR) {
1520 OpenLoopback(&cmailPR);
1522 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1526 DisplayMessage("", "");
1527 if (StrCaseCmp(appData.initialMode, "") == 0) {
1528 initialMode = BeginningOfGame;
1529 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1530 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1531 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1532 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1535 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1536 initialMode = TwoMachinesPlay;
1537 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1538 initialMode = AnalyzeFile;
1539 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1540 initialMode = AnalyzeMode;
1541 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1542 initialMode = MachinePlaysWhite;
1543 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1544 initialMode = MachinePlaysBlack;
1545 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1546 initialMode = EditGame;
1547 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1548 initialMode = EditPosition;
1549 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1550 initialMode = Training;
1552 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1553 if( (len > MSG_SIZ) && appData.debugMode )
1554 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1556 DisplayFatalError(buf, 0, 2);
1560 if (appData.matchMode) {
1561 if(appData.tourneyFile[0]) { // start tourney from command line
1563 if(f = fopen(appData.tourneyFile, "r")) {
1564 ParseArgsFromFile(f); // make sure tourney parmeters re known
1566 appData.clockMode = TRUE;
1568 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1571 } else if (*appData.cmailGameName != NULLCHAR) {
1572 /* Set up cmail mode */
1573 ReloadCmailMsgEvent(TRUE);
1575 /* Set up other modes */
1576 if (initialMode == AnalyzeFile) {
1577 if (*appData.loadGameFile == NULLCHAR) {
1578 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1582 if (*appData.loadGameFile != NULLCHAR) {
1583 (void) LoadGameFromFile(appData.loadGameFile,
1584 appData.loadGameIndex,
1585 appData.loadGameFile, TRUE);
1586 } else if (*appData.loadPositionFile != NULLCHAR) {
1587 (void) LoadPositionFromFile(appData.loadPositionFile,
1588 appData.loadPositionIndex,
1589 appData.loadPositionFile);
1590 /* [HGM] try to make self-starting even after FEN load */
1591 /* to allow automatic setup of fairy variants with wtm */
1592 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1593 gameMode = BeginningOfGame;
1594 setboardSpoiledMachineBlack = 1;
1596 /* [HGM] loadPos: make that every new game uses the setup */
1597 /* from file as long as we do not switch variant */
1598 if(!blackPlaysFirst) {
1599 startedFromPositionFile = TRUE;
1600 CopyBoard(filePosition, boards[0]);
1603 if (initialMode == AnalyzeMode) {
1604 if (appData.noChessProgram) {
1605 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1608 if (appData.icsActive) {
1609 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1613 } else if (initialMode == AnalyzeFile) {
1614 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1615 ShowThinkingEvent();
1617 AnalysisPeriodicEvent(1);
1618 } else if (initialMode == MachinePlaysWhite) {
1619 if (appData.noChessProgram) {
1620 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1624 if (appData.icsActive) {
1625 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1629 MachineWhiteEvent();
1630 } else if (initialMode == MachinePlaysBlack) {
1631 if (appData.noChessProgram) {
1632 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1636 if (appData.icsActive) {
1637 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1641 MachineBlackEvent();
1642 } else if (initialMode == TwoMachinesPlay) {
1643 if (appData.noChessProgram) {
1644 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1648 if (appData.icsActive) {
1649 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1654 } else if (initialMode == EditGame) {
1656 } else if (initialMode == EditPosition) {
1657 EditPositionEvent();
1658 } else if (initialMode == Training) {
1659 if (*appData.loadGameFile == NULLCHAR) {
1660 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1669 * Establish will establish a contact to a remote host.port.
1670 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1671 * used to talk to the host.
1672 * Returns 0 if okay, error code if not.
1679 if (*appData.icsCommPort != NULLCHAR) {
1680 /* Talk to the host through a serial comm port */
1681 return OpenCommPort(appData.icsCommPort, &icsPR);
1683 } else if (*appData.gateway != NULLCHAR) {
1684 if (*appData.remoteShell == NULLCHAR) {
1685 /* Use the rcmd protocol to run telnet program on a gateway host */
1686 snprintf(buf, sizeof(buf), "%s %s %s",
1687 appData.telnetProgram, appData.icsHost, appData.icsPort);
1688 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1691 /* Use the rsh program to run telnet program on a gateway host */
1692 if (*appData.remoteUser == NULLCHAR) {
1693 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1694 appData.gateway, appData.telnetProgram,
1695 appData.icsHost, appData.icsPort);
1697 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1698 appData.remoteShell, appData.gateway,
1699 appData.remoteUser, appData.telnetProgram,
1700 appData.icsHost, appData.icsPort);
1702 return StartChildProcess(buf, "", &icsPR);
1705 } else if (appData.useTelnet) {
1706 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1709 /* TCP socket interface differs somewhat between
1710 Unix and NT; handle details in the front end.
1712 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1716 void EscapeExpand(char *p, char *q)
1717 { // [HGM] initstring: routine to shape up string arguments
1718 while(*p++ = *q++) if(p[-1] == '\\')
1720 case 'n': p[-1] = '\n'; break;
1721 case 'r': p[-1] = '\r'; break;
1722 case 't': p[-1] = '\t'; break;
1723 case '\\': p[-1] = '\\'; break;
1724 case 0: *p = 0; return;
1725 default: p[-1] = q[-1]; break;
1730 show_bytes(fp, buf, count)
1736 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1737 fprintf(fp, "\\%03o", *buf & 0xff);
1746 /* Returns an errno value */
1748 OutputMaybeTelnet(pr, message, count, outError)
1754 char buf[8192], *p, *q, *buflim;
1755 int left, newcount, outcount;
1757 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1758 *appData.gateway != NULLCHAR) {
1759 if (appData.debugMode) {
1760 fprintf(debugFP, ">ICS: ");
1761 show_bytes(debugFP, message, count);
1762 fprintf(debugFP, "\n");
1764 return OutputToProcess(pr, message, count, outError);
1767 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1774 if (appData.debugMode) {
1775 fprintf(debugFP, ">ICS: ");
1776 show_bytes(debugFP, buf, newcount);
1777 fprintf(debugFP, "\n");
1779 outcount = OutputToProcess(pr, buf, newcount, outError);
1780 if (outcount < newcount) return -1; /* to be sure */
1787 } else if (((unsigned char) *p) == TN_IAC) {
1788 *q++ = (char) TN_IAC;
1795 if (appData.debugMode) {
1796 fprintf(debugFP, ">ICS: ");
1797 show_bytes(debugFP, buf, newcount);
1798 fprintf(debugFP, "\n");
1800 outcount = OutputToProcess(pr, buf, newcount, outError);
1801 if (outcount < newcount) return -1; /* to be sure */
1806 read_from_player(isr, closure, message, count, error)
1813 int outError, outCount;
1814 static int gotEof = 0;
1816 /* Pass data read from player on to ICS */
1819 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1820 if (outCount < count) {
1821 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1823 } else if (count < 0) {
1824 RemoveInputSource(isr);
1825 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1826 } else if (gotEof++ > 0) {
1827 RemoveInputSource(isr);
1828 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1834 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1835 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1836 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1837 SendToICS("date\n");
1838 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1841 /* added routine for printf style output to ics */
1842 void ics_printf(char *format, ...)
1844 char buffer[MSG_SIZ];
1847 va_start(args, format);
1848 vsnprintf(buffer, sizeof(buffer), format, args);
1849 buffer[sizeof(buffer)-1] = '\0';
1858 int count, outCount, outError;
1860 if (icsPR == NULL) return;
1863 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1864 if (outCount < count) {
1865 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1869 /* This is used for sending logon scripts to the ICS. Sending
1870 without a delay causes problems when using timestamp on ICC
1871 (at least on my machine). */
1873 SendToICSDelayed(s,msdelay)
1877 int count, outCount, outError;
1879 if (icsPR == NULL) return;
1882 if (appData.debugMode) {
1883 fprintf(debugFP, ">ICS: ");
1884 show_bytes(debugFP, s, count);
1885 fprintf(debugFP, "\n");
1887 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1889 if (outCount < count) {
1890 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1895 /* Remove all highlighting escape sequences in s
1896 Also deletes any suffix starting with '('
1899 StripHighlightAndTitle(s)
1902 static char retbuf[MSG_SIZ];
1905 while (*s != NULLCHAR) {
1906 while (*s == '\033') {
1907 while (*s != NULLCHAR && !isalpha(*s)) s++;
1908 if (*s != NULLCHAR) s++;
1910 while (*s != NULLCHAR && *s != '\033') {
1911 if (*s == '(' || *s == '[') {
1922 /* Remove all highlighting escape sequences in s */
1927 static char retbuf[MSG_SIZ];
1930 while (*s != NULLCHAR) {
1931 while (*s == '\033') {
1932 while (*s != NULLCHAR && !isalpha(*s)) s++;
1933 if (*s != NULLCHAR) s++;
1935 while (*s != NULLCHAR && *s != '\033') {
1943 char *variantNames[] = VARIANT_NAMES;
1948 return variantNames[v];
1952 /* Identify a variant from the strings the chess servers use or the
1953 PGN Variant tag names we use. */
1960 VariantClass v = VariantNormal;
1961 int i, found = FALSE;
1967 /* [HGM] skip over optional board-size prefixes */
1968 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1969 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1970 while( *e++ != '_');
1973 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1977 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1978 if (StrCaseStr(e, variantNames[i])) {
1979 v = (VariantClass) i;
1986 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1987 || StrCaseStr(e, "wild/fr")
1988 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1989 v = VariantFischeRandom;
1990 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1991 (i = 1, p = StrCaseStr(e, "w"))) {
1993 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2000 case 0: /* FICS only, actually */
2002 /* Castling legal even if K starts on d-file */
2003 v = VariantWildCastle;
2008 /* Castling illegal even if K & R happen to start in
2009 normal positions. */
2010 v = VariantNoCastle;
2023 /* Castling legal iff K & R start in normal positions */
2029 /* Special wilds for position setup; unclear what to do here */
2030 v = VariantLoadable;
2033 /* Bizarre ICC game */
2034 v = VariantTwoKings;
2037 v = VariantKriegspiel;
2043 v = VariantFischeRandom;
2046 v = VariantCrazyhouse;
2049 v = VariantBughouse;
2055 /* Not quite the same as FICS suicide! */
2056 v = VariantGiveaway;
2062 v = VariantShatranj;
2065 /* Temporary names for future ICC types. The name *will* change in
2066 the next xboard/WinBoard release after ICC defines it. */
2104 v = VariantCapablanca;
2107 v = VariantKnightmate;
2113 v = VariantCylinder;
2119 v = VariantCapaRandom;
2122 v = VariantBerolina;
2134 /* Found "wild" or "w" in the string but no number;
2135 must assume it's normal chess. */
2139 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2140 if( (len > MSG_SIZ) && appData.debugMode )
2141 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2143 DisplayError(buf, 0);
2149 if (appData.debugMode) {
2150 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
2151 e, wnum, VariantName(v));
2156 static int leftover_start = 0, leftover_len = 0;
2157 char star_match[STAR_MATCH_N][MSG_SIZ];
2159 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2160 advance *index beyond it, and set leftover_start to the new value of
2161 *index; else return FALSE. If pattern contains the character '*', it
2162 matches any sequence of characters not containing '\r', '\n', or the
2163 character following the '*' (if any), and the matched sequence(s) are
2164 copied into star_match.
2167 looking_at(buf, index, pattern)
2172 char *bufp = &buf[*index], *patternp = pattern;
2174 char *matchp = star_match[0];
2177 if (*patternp == NULLCHAR) {
2178 *index = leftover_start = bufp - buf;
2182 if (*bufp == NULLCHAR) return FALSE;
2183 if (*patternp == '*') {
2184 if (*bufp == *(patternp + 1)) {
2186 matchp = star_match[++star_count];
2190 } else if (*bufp == '\n' || *bufp == '\r') {
2192 if (*patternp == NULLCHAR)
2197 *matchp++ = *bufp++;
2201 if (*patternp != *bufp) return FALSE;
2208 SendToPlayer(data, length)
2212 int error, outCount;
2213 outCount = OutputToProcess(NoProc, data, length, &error);
2214 if (outCount < length) {
2215 DisplayFatalError(_("Error writing to display"), error, 1);
2220 PackHolding(packed, holding)
2232 switch (runlength) {
2243 sprintf(q, "%d", runlength);
2255 /* Telnet protocol requests from the front end */
2257 TelnetRequest(ddww, option)
2258 unsigned char ddww, option;
2260 unsigned char msg[3];
2261 int outCount, outError;
2263 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2265 if (appData.debugMode) {
2266 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2282 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2291 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2294 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2299 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2301 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2308 if (!appData.icsActive) return;
2309 TelnetRequest(TN_DO, TN_ECHO);
2315 if (!appData.icsActive) return;
2316 TelnetRequest(TN_DONT, TN_ECHO);
2320 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2322 /* put the holdings sent to us by the server on the board holdings area */
2323 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2327 if(gameInfo.holdingsWidth < 2) return;
2328 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2329 return; // prevent overwriting by pre-board holdings
2331 if( (int)lowestPiece >= BlackPawn ) {
2334 holdingsStartRow = BOARD_HEIGHT-1;
2337 holdingsColumn = BOARD_WIDTH-1;
2338 countsColumn = BOARD_WIDTH-2;
2339 holdingsStartRow = 0;
2343 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2344 board[i][holdingsColumn] = EmptySquare;
2345 board[i][countsColumn] = (ChessSquare) 0;
2347 while( (p=*holdings++) != NULLCHAR ) {
2348 piece = CharToPiece( ToUpper(p) );
2349 if(piece == EmptySquare) continue;
2350 /*j = (int) piece - (int) WhitePawn;*/
2351 j = PieceToNumber(piece);
2352 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2353 if(j < 0) continue; /* should not happen */
2354 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2355 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2356 board[holdingsStartRow+j*direction][countsColumn]++;
2362 VariantSwitch(Board board, VariantClass newVariant)
2364 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2365 static Board oldBoard;
2367 startedFromPositionFile = FALSE;
2368 if(gameInfo.variant == newVariant) return;
2370 /* [HGM] This routine is called each time an assignment is made to
2371 * gameInfo.variant during a game, to make sure the board sizes
2372 * are set to match the new variant. If that means adding or deleting
2373 * holdings, we shift the playing board accordingly
2374 * This kludge is needed because in ICS observe mode, we get boards
2375 * of an ongoing game without knowing the variant, and learn about the
2376 * latter only later. This can be because of the move list we requested,
2377 * in which case the game history is refilled from the beginning anyway,
2378 * but also when receiving holdings of a crazyhouse game. In the latter
2379 * case we want to add those holdings to the already received position.
2383 if (appData.debugMode) {
2384 fprintf(debugFP, "Switch board from %s to %s\n",
2385 VariantName(gameInfo.variant), VariantName(newVariant));
2386 setbuf(debugFP, NULL);
2388 shuffleOpenings = 0; /* [HGM] shuffle */
2389 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2393 newWidth = 9; newHeight = 9;
2394 gameInfo.holdingsSize = 7;
2395 case VariantBughouse:
2396 case VariantCrazyhouse:
2397 newHoldingsWidth = 2; break;
2401 newHoldingsWidth = 2;
2402 gameInfo.holdingsSize = 8;
2405 case VariantCapablanca:
2406 case VariantCapaRandom:
2409 newHoldingsWidth = gameInfo.holdingsSize = 0;
2412 if(newWidth != gameInfo.boardWidth ||
2413 newHeight != gameInfo.boardHeight ||
2414 newHoldingsWidth != gameInfo.holdingsWidth ) {
2416 /* shift position to new playing area, if needed */
2417 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2418 for(i=0; i<BOARD_HEIGHT; i++)
2419 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2420 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2422 for(i=0; i<newHeight; i++) {
2423 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2424 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2426 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2427 for(i=0; i<BOARD_HEIGHT; i++)
2428 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2429 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2432 gameInfo.boardWidth = newWidth;
2433 gameInfo.boardHeight = newHeight;
2434 gameInfo.holdingsWidth = newHoldingsWidth;
2435 gameInfo.variant = newVariant;
2436 InitDrawingSizes(-2, 0);
2437 } else gameInfo.variant = newVariant;
2438 CopyBoard(oldBoard, board); // remember correctly formatted board
2439 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2440 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2443 static int loggedOn = FALSE;
2445 /*-- Game start info cache: --*/
2447 char gs_kind[MSG_SIZ];
2448 static char player1Name[128] = "";
2449 static char player2Name[128] = "";
2450 static char cont_seq[] = "\n\\ ";
2451 static int player1Rating = -1;
2452 static int player2Rating = -1;
2453 /*----------------------------*/
2455 ColorClass curColor = ColorNormal;
2456 int suppressKibitz = 0;
2459 Boolean soughtPending = FALSE;
2460 Boolean seekGraphUp;
2461 #define MAX_SEEK_ADS 200
2463 char *seekAdList[MAX_SEEK_ADS];
2464 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2465 float tcList[MAX_SEEK_ADS];
2466 char colorList[MAX_SEEK_ADS];
2467 int nrOfSeekAds = 0;
2468 int minRating = 1010, maxRating = 2800;
2469 int hMargin = 10, vMargin = 20, h, w;
2470 extern int squareSize, lineGap;
2475 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2476 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2477 if(r < minRating+100 && r >=0 ) r = minRating+100;
2478 if(r > maxRating) r = maxRating;
2479 if(tc < 1.) tc = 1.;
2480 if(tc > 95.) tc = 95.;
2481 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2482 y = ((double)r - minRating)/(maxRating - minRating)
2483 * (h-vMargin-squareSize/8-1) + vMargin;
2484 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2485 if(strstr(seekAdList[i], " u ")) color = 1;
2486 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2487 !strstr(seekAdList[i], "bullet") &&
2488 !strstr(seekAdList[i], "blitz") &&
2489 !strstr(seekAdList[i], "standard") ) color = 2;
2490 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2491 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2495 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2497 char buf[MSG_SIZ], *ext = "";
2498 VariantClass v = StringToVariant(type);
2499 if(strstr(type, "wild")) {
2500 ext = type + 4; // append wild number
2501 if(v == VariantFischeRandom) type = "chess960"; else
2502 if(v == VariantLoadable) type = "setup"; else
2503 type = VariantName(v);
2505 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2506 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2507 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2508 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2509 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2510 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2511 seekNrList[nrOfSeekAds] = nr;
2512 zList[nrOfSeekAds] = 0;
2513 seekAdList[nrOfSeekAds++] = StrSave(buf);
2514 if(plot) PlotSeekAd(nrOfSeekAds-1);
2521 int x = xList[i], y = yList[i], d=squareSize/4, k;
2522 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2523 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2524 // now replot every dot that overlapped
2525 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2526 int xx = xList[k], yy = yList[k];
2527 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2528 DrawSeekDot(xx, yy, colorList[k]);
2533 RemoveSeekAd(int nr)
2536 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2538 if(seekAdList[i]) free(seekAdList[i]);
2539 seekAdList[i] = seekAdList[--nrOfSeekAds];
2540 seekNrList[i] = seekNrList[nrOfSeekAds];
2541 ratingList[i] = ratingList[nrOfSeekAds];
2542 colorList[i] = colorList[nrOfSeekAds];
2543 tcList[i] = tcList[nrOfSeekAds];
2544 xList[i] = xList[nrOfSeekAds];
2545 yList[i] = yList[nrOfSeekAds];
2546 zList[i] = zList[nrOfSeekAds];
2547 seekAdList[nrOfSeekAds] = NULL;
2553 MatchSoughtLine(char *line)
2555 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2556 int nr, base, inc, u=0; char dummy;
2558 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2559 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2561 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2562 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2563 // match: compact and save the line
2564 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2574 if(!seekGraphUp) return FALSE;
2575 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2576 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2578 DrawSeekBackground(0, 0, w, h);
2579 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2580 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2581 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2582 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2584 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2587 snprintf(buf, MSG_SIZ, "%d", i);
2588 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2591 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2592 for(i=1; i<100; i+=(i<10?1:5)) {
2593 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2594 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2595 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2597 snprintf(buf, MSG_SIZ, "%d", i);
2598 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2601 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2605 int SeekGraphClick(ClickType click, int x, int y, int moving)
2607 static int lastDown = 0, displayed = 0, lastSecond;
2608 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2609 if(click == Release || moving) return FALSE;
2611 soughtPending = TRUE;
2612 SendToICS(ics_prefix);
2613 SendToICS("sought\n"); // should this be "sought all"?
2614 } else { // issue challenge based on clicked ad
2615 int dist = 10000; int i, closest = 0, second = 0;
2616 for(i=0; i<nrOfSeekAds; i++) {
2617 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2618 if(d < dist) { dist = d; closest = i; }
2619 second += (d - zList[i] < 120); // count in-range ads
2620 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2624 second = (second > 1);
2625 if(displayed != closest || second != lastSecond) {
2626 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2627 lastSecond = second; displayed = closest;
2629 if(click == Press) {
2630 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2633 } // on press 'hit', only show info
2634 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2635 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2636 SendToICS(ics_prefix);
2638 return TRUE; // let incoming board of started game pop down the graph
2639 } else if(click == Release) { // release 'miss' is ignored
2640 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2641 if(moving == 2) { // right up-click
2642 nrOfSeekAds = 0; // refresh graph
2643 soughtPending = TRUE;
2644 SendToICS(ics_prefix);
2645 SendToICS("sought\n"); // should this be "sought all"?
2648 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2649 // press miss or release hit 'pop down' seek graph
2650 seekGraphUp = FALSE;
2651 DrawPosition(TRUE, NULL);
2657 read_from_ics(isr, closure, data, count, error)
2664 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2665 #define STARTED_NONE 0
2666 #define STARTED_MOVES 1
2667 #define STARTED_BOARD 2
2668 #define STARTED_OBSERVE 3
2669 #define STARTED_HOLDINGS 4
2670 #define STARTED_CHATTER 5
2671 #define STARTED_COMMENT 6
2672 #define STARTED_MOVES_NOHIDE 7
2674 static int started = STARTED_NONE;
2675 static char parse[20000];
2676 static int parse_pos = 0;
2677 static char buf[BUF_SIZE + 1];
2678 static int firstTime = TRUE, intfSet = FALSE;
2679 static ColorClass prevColor = ColorNormal;
2680 static int savingComment = FALSE;
2681 static int cmatch = 0; // continuation sequence match
2688 int backup; /* [DM] For zippy color lines */
2690 char talker[MSG_SIZ]; // [HGM] chat
2693 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2695 if (appData.debugMode) {
2697 fprintf(debugFP, "<ICS: ");
2698 show_bytes(debugFP, data, count);
2699 fprintf(debugFP, "\n");
2703 if (appData.debugMode) { int f = forwardMostMove;
2704 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2705 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2706 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2709 /* If last read ended with a partial line that we couldn't parse,
2710 prepend it to the new read and try again. */
2711 if (leftover_len > 0) {
2712 for (i=0; i<leftover_len; i++)
2713 buf[i] = buf[leftover_start + i];
2716 /* copy new characters into the buffer */
2717 bp = buf + leftover_len;
2718 buf_len=leftover_len;
2719 for (i=0; i<count; i++)
2722 if (data[i] == '\r')
2725 // join lines split by ICS?
2726 if (!appData.noJoin)
2729 Joining just consists of finding matches against the
2730 continuation sequence, and discarding that sequence
2731 if found instead of copying it. So, until a match
2732 fails, there's nothing to do since it might be the
2733 complete sequence, and thus, something we don't want
2736 if (data[i] == cont_seq[cmatch])
2739 if (cmatch == strlen(cont_seq))
2741 cmatch = 0; // complete match. just reset the counter
2744 it's possible for the ICS to not include the space
2745 at the end of the last word, making our [correct]
2746 join operation fuse two separate words. the server
2747 does this when the space occurs at the width setting.
2749 if (!buf_len || buf[buf_len-1] != ' ')
2760 match failed, so we have to copy what matched before
2761 falling through and copying this character. In reality,
2762 this will only ever be just the newline character, but
2763 it doesn't hurt to be precise.
2765 strncpy(bp, cont_seq, cmatch);
2777 buf[buf_len] = NULLCHAR;
2778 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2783 while (i < buf_len) {
2784 /* Deal with part of the TELNET option negotiation
2785 protocol. We refuse to do anything beyond the
2786 defaults, except that we allow the WILL ECHO option,
2787 which ICS uses to turn off password echoing when we are
2788 directly connected to it. We reject this option
2789 if localLineEditing mode is on (always on in xboard)
2790 and we are talking to port 23, which might be a real
2791 telnet server that will try to keep WILL ECHO on permanently.
2793 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2794 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2795 unsigned char option;
2797 switch ((unsigned char) buf[++i]) {
2799 if (appData.debugMode)
2800 fprintf(debugFP, "\n<WILL ");
2801 switch (option = (unsigned char) buf[++i]) {
2803 if (appData.debugMode)
2804 fprintf(debugFP, "ECHO ");
2805 /* Reply only if this is a change, according
2806 to the protocol rules. */
2807 if (remoteEchoOption) break;
2808 if (appData.localLineEditing &&
2809 atoi(appData.icsPort) == TN_PORT) {
2810 TelnetRequest(TN_DONT, TN_ECHO);
2813 TelnetRequest(TN_DO, TN_ECHO);
2814 remoteEchoOption = TRUE;
2818 if (appData.debugMode)
2819 fprintf(debugFP, "%d ", option);
2820 /* Whatever this is, we don't want it. */
2821 TelnetRequest(TN_DONT, option);
2826 if (appData.debugMode)
2827 fprintf(debugFP, "\n<WONT ");
2828 switch (option = (unsigned char) buf[++i]) {
2830 if (appData.debugMode)
2831 fprintf(debugFP, "ECHO ");
2832 /* Reply only if this is a change, according
2833 to the protocol rules. */
2834 if (!remoteEchoOption) break;
2836 TelnetRequest(TN_DONT, TN_ECHO);
2837 remoteEchoOption = FALSE;
2840 if (appData.debugMode)
2841 fprintf(debugFP, "%d ", (unsigned char) option);
2842 /* Whatever this is, it must already be turned
2843 off, because we never agree to turn on
2844 anything non-default, so according to the
2845 protocol rules, we don't reply. */
2850 if (appData.debugMode)
2851 fprintf(debugFP, "\n<DO ");
2852 switch (option = (unsigned char) buf[++i]) {
2854 /* Whatever this is, we refuse to do it. */
2855 if (appData.debugMode)
2856 fprintf(debugFP, "%d ", option);
2857 TelnetRequest(TN_WONT, option);
2862 if (appData.debugMode)
2863 fprintf(debugFP, "\n<DONT ");
2864 switch (option = (unsigned char) buf[++i]) {
2866 if (appData.debugMode)
2867 fprintf(debugFP, "%d ", option);
2868 /* Whatever this is, we are already not doing
2869 it, because we never agree to do anything
2870 non-default, so according to the protocol
2871 rules, we don't reply. */
2876 if (appData.debugMode)
2877 fprintf(debugFP, "\n<IAC ");
2878 /* Doubled IAC; pass it through */
2882 if (appData.debugMode)
2883 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2884 /* Drop all other telnet commands on the floor */
2887 if (oldi > next_out)
2888 SendToPlayer(&buf[next_out], oldi - next_out);
2894 /* OK, this at least will *usually* work */
2895 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2899 if (loggedOn && !intfSet) {
2900 if (ics_type == ICS_ICC) {
2901 snprintf(str, MSG_SIZ,
2902 "/set-quietly interface %s\n/set-quietly style 12\n",
2904 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2905 strcat(str, "/set-2 51 1\n/set seek 1\n");
2906 } else if (ics_type == ICS_CHESSNET) {
2907 snprintf(str, MSG_SIZ, "/style 12\n");
2909 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2910 strcat(str, programVersion);
2911 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2912 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2913 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2915 strcat(str, "$iset nohighlight 1\n");
2917 strcat(str, "$iset lock 1\n$style 12\n");
2920 NotifyFrontendLogin();
2924 if (started == STARTED_COMMENT) {
2925 /* Accumulate characters in comment */
2926 parse[parse_pos++] = buf[i];
2927 if (buf[i] == '\n') {
2928 parse[parse_pos] = NULLCHAR;
2929 if(chattingPartner>=0) {
2931 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2932 OutputChatMessage(chattingPartner, mess);
2933 chattingPartner = -1;
2934 next_out = i+1; // [HGM] suppress printing in ICS window
2936 if(!suppressKibitz) // [HGM] kibitz
2937 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2938 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2939 int nrDigit = 0, nrAlph = 0, j;
2940 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2941 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2942 parse[parse_pos] = NULLCHAR;
2943 // try to be smart: if it does not look like search info, it should go to
2944 // ICS interaction window after all, not to engine-output window.
2945 for(j=0; j<parse_pos; j++) { // count letters and digits
2946 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2947 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2948 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2950 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2951 int depth=0; float score;
2952 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2953 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2954 pvInfoList[forwardMostMove-1].depth = depth;
2955 pvInfoList[forwardMostMove-1].score = 100*score;
2957 OutputKibitz(suppressKibitz, parse);
2960 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2961 SendToPlayer(tmp, strlen(tmp));
2963 next_out = i+1; // [HGM] suppress printing in ICS window
2965 started = STARTED_NONE;
2967 /* Don't match patterns against characters in comment */
2972 if (started == STARTED_CHATTER) {
2973 if (buf[i] != '\n') {
2974 /* Don't match patterns against characters in chatter */
2978 started = STARTED_NONE;
2979 if(suppressKibitz) next_out = i+1;
2982 /* Kludge to deal with rcmd protocol */
2983 if (firstTime && looking_at(buf, &i, "\001*")) {
2984 DisplayFatalError(&buf[1], 0, 1);
2990 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2993 if (appData.debugMode)
2994 fprintf(debugFP, "ics_type %d\n", ics_type);
2997 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2998 ics_type = ICS_FICS;
3000 if (appData.debugMode)
3001 fprintf(debugFP, "ics_type %d\n", ics_type);
3004 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3005 ics_type = ICS_CHESSNET;
3007 if (appData.debugMode)
3008 fprintf(debugFP, "ics_type %d\n", ics_type);
3013 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3014 looking_at(buf, &i, "Logging you in as \"*\"") ||
3015 looking_at(buf, &i, "will be \"*\""))) {
3016 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3020 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3022 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3023 DisplayIcsInteractionTitle(buf);
3024 have_set_title = TRUE;
3027 /* skip finger notes */
3028 if (started == STARTED_NONE &&
3029 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3030 (buf[i] == '1' && buf[i+1] == '0')) &&
3031 buf[i+2] == ':' && buf[i+3] == ' ') {
3032 started = STARTED_CHATTER;
3038 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3039 if(appData.seekGraph) {
3040 if(soughtPending && MatchSoughtLine(buf+i)) {
3041 i = strstr(buf+i, "rated") - buf;
3042 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3043 next_out = leftover_start = i;
3044 started = STARTED_CHATTER;
3045 suppressKibitz = TRUE;
3048 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3049 && looking_at(buf, &i, "* ads displayed")) {
3050 soughtPending = FALSE;
3055 if(appData.autoRefresh) {
3056 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3057 int s = (ics_type == ICS_ICC); // ICC format differs
3059 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3060 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3061 looking_at(buf, &i, "*% "); // eat prompt
3062 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3063 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3064 next_out = i; // suppress
3067 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3068 char *p = star_match[0];
3070 if(seekGraphUp) RemoveSeekAd(atoi(p));
3071 while(*p && *p++ != ' '); // next
3073 looking_at(buf, &i, "*% "); // eat prompt
3074 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3081 /* skip formula vars */
3082 if (started == STARTED_NONE &&
3083 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3084 started = STARTED_CHATTER;
3089 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3090 if (appData.autoKibitz && started == STARTED_NONE &&
3091 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3092 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3093 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3094 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3095 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3096 suppressKibitz = TRUE;
3097 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3099 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3100 && (gameMode == IcsPlayingWhite)) ||
3101 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3102 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3103 started = STARTED_CHATTER; // own kibitz we simply discard
3105 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3106 parse_pos = 0; parse[0] = NULLCHAR;
3107 savingComment = TRUE;
3108 suppressKibitz = gameMode != IcsObserving ? 2 :
3109 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3113 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3114 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3115 && atoi(star_match[0])) {
3116 // suppress the acknowledgements of our own autoKibitz
3118 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3119 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3120 SendToPlayer(star_match[0], strlen(star_match[0]));
3121 if(looking_at(buf, &i, "*% ")) // eat prompt
3122 suppressKibitz = FALSE;
3126 } // [HGM] kibitz: end of patch
3128 // [HGM] chat: intercept tells by users for which we have an open chat window
3130 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3131 looking_at(buf, &i, "* whispers:") ||
3132 looking_at(buf, &i, "* kibitzes:") ||
3133 looking_at(buf, &i, "* shouts:") ||
3134 looking_at(buf, &i, "* c-shouts:") ||
3135 looking_at(buf, &i, "--> * ") ||
3136 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3137 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3138 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3139 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3141 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3142 chattingPartner = -1;
3144 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3145 for(p=0; p<MAX_CHAT; p++) {
3146 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3147 talker[0] = '['; strcat(talker, "] ");
3148 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
3149 chattingPartner = p; break;
3152 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3153 for(p=0; p<MAX_CHAT; p++) {
3154 if(!strcmp("kibitzes", chatPartner[p])) {
3155 talker[0] = '['; strcat(talker, "] ");
3156 chattingPartner = p; break;
3159 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3160 for(p=0; p<MAX_CHAT; p++) {
3161 if(!strcmp("whispers", chatPartner[p])) {
3162 talker[0] = '['; strcat(talker, "] ");
3163 chattingPartner = p; break;
3166 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3167 if(buf[i-8] == '-' && buf[i-3] == 't')
3168 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3169 if(!strcmp("c-shouts", chatPartner[p])) {
3170 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3171 chattingPartner = p; break;
3174 if(chattingPartner < 0)
3175 for(p=0; p<MAX_CHAT; p++) {
3176 if(!strcmp("shouts", chatPartner[p])) {
3177 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3178 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3179 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3180 chattingPartner = p; break;
3184 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3185 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3186 talker[0] = 0; Colorize(ColorTell, FALSE);
3187 chattingPartner = p; break;
3189 if(chattingPartner<0) i = oldi; else {
3190 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3191 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3192 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3193 started = STARTED_COMMENT;
3194 parse_pos = 0; parse[0] = NULLCHAR;
3195 savingComment = 3 + chattingPartner; // counts as TRUE
3196 suppressKibitz = TRUE;
3199 } // [HGM] chat: end of patch
3202 if (appData.zippyTalk || appData.zippyPlay) {
3203 /* [DM] Backup address for color zippy lines */
3205 if (loggedOn == TRUE)
3206 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3207 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3209 } // [DM] 'else { ' deleted
3211 /* Regular tells and says */
3212 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3213 looking_at(buf, &i, "* (your partner) tells you: ") ||
3214 looking_at(buf, &i, "* says: ") ||
3215 /* Don't color "message" or "messages" output */
3216 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3217 looking_at(buf, &i, "*. * at *:*: ") ||
3218 looking_at(buf, &i, "--* (*:*): ") ||
3219 /* Message notifications (same color as tells) */
3220 looking_at(buf, &i, "* has left a message ") ||
3221 looking_at(buf, &i, "* just sent you a message:\n") ||
3222 /* Whispers and kibitzes */
3223 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3224 looking_at(buf, &i, "* kibitzes: ") ||
3226 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3228 if (tkind == 1 && strchr(star_match[0], ':')) {
3229 /* Avoid "tells you:" spoofs in channels */
3232 if (star_match[0][0] == NULLCHAR ||
3233 strchr(star_match[0], ' ') ||
3234 (tkind == 3 && strchr(star_match[1], ' '))) {
3235 /* Reject bogus matches */
3238 if (appData.colorize) {
3239 if (oldi > next_out) {
3240 SendToPlayer(&buf[next_out], oldi - next_out);
3245 Colorize(ColorTell, FALSE);
3246 curColor = ColorTell;
3249 Colorize(ColorKibitz, FALSE);
3250 curColor = ColorKibitz;
3253 p = strrchr(star_match[1], '(');
3260 Colorize(ColorChannel1, FALSE);
3261 curColor = ColorChannel1;
3263 Colorize(ColorChannel, FALSE);
3264 curColor = ColorChannel;
3268 curColor = ColorNormal;
3272 if (started == STARTED_NONE && appData.autoComment &&
3273 (gameMode == IcsObserving ||
3274 gameMode == IcsPlayingWhite ||
3275 gameMode == IcsPlayingBlack)) {
3276 parse_pos = i - oldi;
3277 memcpy(parse, &buf[oldi], parse_pos);
3278 parse[parse_pos] = NULLCHAR;
3279 started = STARTED_COMMENT;
3280 savingComment = TRUE;
3282 started = STARTED_CHATTER;
3283 savingComment = FALSE;
3290 if (looking_at(buf, &i, "* s-shouts: ") ||
3291 looking_at(buf, &i, "* c-shouts: ")) {
3292 if (appData.colorize) {
3293 if (oldi > next_out) {
3294 SendToPlayer(&buf[next_out], oldi - next_out);
3297 Colorize(ColorSShout, FALSE);
3298 curColor = ColorSShout;
3301 started = STARTED_CHATTER;
3305 if (looking_at(buf, &i, "--->")) {
3310 if (looking_at(buf, &i, "* shouts: ") ||
3311 looking_at(buf, &i, "--> ")) {
3312 if (appData.colorize) {
3313 if (oldi > next_out) {
3314 SendToPlayer(&buf[next_out], oldi - next_out);
3317 Colorize(ColorShout, FALSE);
3318 curColor = ColorShout;
3321 started = STARTED_CHATTER;
3325 if (looking_at( buf, &i, "Challenge:")) {
3326 if (appData.colorize) {
3327 if (oldi > next_out) {
3328 SendToPlayer(&buf[next_out], oldi - next_out);
3331 Colorize(ColorChallenge, FALSE);
3332 curColor = ColorChallenge;
3338 if (looking_at(buf, &i, "* offers you") ||
3339 looking_at(buf, &i, "* offers to be") ||
3340 looking_at(buf, &i, "* would like to") ||
3341 looking_at(buf, &i, "* requests to") ||
3342 looking_at(buf, &i, "Your opponent offers") ||
3343 looking_at(buf, &i, "Your opponent requests")) {
3345 if (appData.colorize) {
3346 if (oldi > next_out) {
3347 SendToPlayer(&buf[next_out], oldi - next_out);
3350 Colorize(ColorRequest, FALSE);
3351 curColor = ColorRequest;
3356 if (looking_at(buf, &i, "* (*) seeking")) {
3357 if (appData.colorize) {
3358 if (oldi > next_out) {
3359 SendToPlayer(&buf[next_out], oldi - next_out);
3362 Colorize(ColorSeek, FALSE);
3363 curColor = ColorSeek;
3368 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3370 if (looking_at(buf, &i, "\\ ")) {
3371 if (prevColor != ColorNormal) {
3372 if (oldi > next_out) {
3373 SendToPlayer(&buf[next_out], oldi - next_out);
3376 Colorize(prevColor, TRUE);
3377 curColor = prevColor;
3379 if (savingComment) {
3380 parse_pos = i - oldi;
3381 memcpy(parse, &buf[oldi], parse_pos);
3382 parse[parse_pos] = NULLCHAR;
3383 started = STARTED_COMMENT;
3384 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3385 chattingPartner = savingComment - 3; // kludge to remember the box
3387 started = STARTED_CHATTER;
3392 if (looking_at(buf, &i, "Black Strength :") ||
3393 looking_at(buf, &i, "<<< style 10 board >>>") ||
3394 looking_at(buf, &i, "<10>") ||
3395 looking_at(buf, &i, "#@#")) {
3396 /* Wrong board style */
3398 SendToICS(ics_prefix);
3399 SendToICS("set style 12\n");
3400 SendToICS(ics_prefix);
3401 SendToICS("refresh\n");
3405 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3407 have_sent_ICS_logon = 1;
3411 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3412 (looking_at(buf, &i, "\n<12> ") ||
3413 looking_at(buf, &i, "<12> "))) {
3415 if (oldi > next_out) {
3416 SendToPlayer(&buf[next_out], oldi - next_out);
3419 started = STARTED_BOARD;
3424 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3425 looking_at(buf, &i, "<b1> ")) {
3426 if (oldi > next_out) {
3427 SendToPlayer(&buf[next_out], oldi - next_out);
3430 started = STARTED_HOLDINGS;
3435 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3437 /* Header for a move list -- first line */
3439 switch (ics_getting_history) {
3443 case BeginningOfGame:
3444 /* User typed "moves" or "oldmoves" while we
3445 were idle. Pretend we asked for these
3446 moves and soak them up so user can step
3447 through them and/or save them.
3450 gameMode = IcsObserving;
3453 ics_getting_history = H_GOT_UNREQ_HEADER;
3455 case EditGame: /*?*/
3456 case EditPosition: /*?*/
3457 /* Should above feature work in these modes too? */
3458 /* For now it doesn't */
3459 ics_getting_history = H_GOT_UNWANTED_HEADER;
3462 ics_getting_history = H_GOT_UNWANTED_HEADER;
3467 /* Is this the right one? */
3468 if (gameInfo.white && gameInfo.black &&
3469 strcmp(gameInfo.white, star_match[0]) == 0 &&
3470 strcmp(gameInfo.black, star_match[2]) == 0) {
3472 ics_getting_history = H_GOT_REQ_HEADER;
3475 case H_GOT_REQ_HEADER:
3476 case H_GOT_UNREQ_HEADER:
3477 case H_GOT_UNWANTED_HEADER:
3478 case H_GETTING_MOVES:
3479 /* Should not happen */
3480 DisplayError(_("Error gathering move list: two headers"), 0);
3481 ics_getting_history = H_FALSE;
3485 /* Save player ratings into gameInfo if needed */
3486 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3487 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3488 (gameInfo.whiteRating == -1 ||
3489 gameInfo.blackRating == -1)) {
3491 gameInfo.whiteRating = string_to_rating(star_match[1]);
3492 gameInfo.blackRating = string_to_rating(star_match[3]);
3493 if (appData.debugMode)
3494 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3495 gameInfo.whiteRating, gameInfo.blackRating);
3500 if (looking_at(buf, &i,
3501 "* * match, initial time: * minute*, increment: * second")) {
3502 /* Header for a move list -- second line */
3503 /* Initial board will follow if this is a wild game */
3504 if (gameInfo.event != NULL) free(gameInfo.event);
3505 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3506 gameInfo.event = StrSave(str);
3507 /* [HGM] we switched variant. Translate boards if needed. */
3508 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3512 if (looking_at(buf, &i, "Move ")) {
3513 /* Beginning of a move list */
3514 switch (ics_getting_history) {
3516 /* Normally should not happen */
3517 /* Maybe user hit reset while we were parsing */
3520 /* Happens if we are ignoring a move list that is not
3521 * the one we just requested. Common if the user
3522 * tries to observe two games without turning off
3525 case H_GETTING_MOVES:
3526 /* Should not happen */
3527 DisplayError(_("Error gathering move list: nested"), 0);
3528 ics_getting_history = H_FALSE;
3530 case H_GOT_REQ_HEADER:
3531 ics_getting_history = H_GETTING_MOVES;
3532 started = STARTED_MOVES;
3534 if (oldi > next_out) {
3535 SendToPlayer(&buf[next_out], oldi - next_out);
3538 case H_GOT_UNREQ_HEADER:
3539 ics_getting_history = H_GETTING_MOVES;
3540 started = STARTED_MOVES_NOHIDE;
3543 case H_GOT_UNWANTED_HEADER:
3544 ics_getting_history = H_FALSE;
3550 if (looking_at(buf, &i, "% ") ||
3551 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3552 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3553 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3554 soughtPending = FALSE;
3558 if(suppressKibitz) next_out = i;
3559 savingComment = FALSE;
3563 case STARTED_MOVES_NOHIDE:
3564 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3565 parse[parse_pos + i - oldi] = NULLCHAR;
3566 ParseGameHistory(parse);
3568 if (appData.zippyPlay && first.initDone) {
3569 FeedMovesToProgram(&first, forwardMostMove);
3570 if (gameMode == IcsPlayingWhite) {
3571 if (WhiteOnMove(forwardMostMove)) {
3572 if (first.sendTime) {
3573 if (first.useColors) {
3574 SendToProgram("black\n", &first);
3576 SendTimeRemaining(&first, TRUE);
3578 if (first.useColors) {
3579 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3581 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3582 first.maybeThinking = TRUE;
3584 if (first.usePlayother) {
3585 if (first.sendTime) {
3586 SendTimeRemaining(&first, TRUE);
3588 SendToProgram("playother\n", &first);
3594 } else if (gameMode == IcsPlayingBlack) {
3595 if (!WhiteOnMove(forwardMostMove)) {
3596 if (first.sendTime) {
3597 if (first.useColors) {
3598 SendToProgram("white\n", &first);
3600 SendTimeRemaining(&first, FALSE);
3602 if (first.useColors) {
3603 SendToProgram("black\n", &first);
3605 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3606 first.maybeThinking = TRUE;
3608 if (first.usePlayother) {
3609 if (first.sendTime) {
3610 SendTimeRemaining(&first, FALSE);
3612 SendToProgram("playother\n", &first);
3621 if (gameMode == IcsObserving && ics_gamenum == -1) {
3622 /* Moves came from oldmoves or moves command
3623 while we weren't doing anything else.
3625 currentMove = forwardMostMove;
3626 ClearHighlights();/*!!could figure this out*/
3627 flipView = appData.flipView;
3628 DrawPosition(TRUE, boards[currentMove]);
3629 DisplayBothClocks();
3630 snprintf(str, MSG_SIZ, "%s vs. %s",
3631 gameInfo.white, gameInfo.black);
3635 /* Moves were history of an active game */
3636 if (gameInfo.resultDetails != NULL) {
3637 free(gameInfo.resultDetails);
3638 gameInfo.resultDetails = NULL;
3641 HistorySet(parseList, backwardMostMove,
3642 forwardMostMove, currentMove-1);
3643 DisplayMove(currentMove - 1);
3644 if (started == STARTED_MOVES) next_out = i;
3645 started = STARTED_NONE;
3646 ics_getting_history = H_FALSE;
3649 case STARTED_OBSERVE:
3650 started = STARTED_NONE;
3651 SendToICS(ics_prefix);
3652 SendToICS("refresh\n");
3658 if(bookHit) { // [HGM] book: simulate book reply
3659 static char bookMove[MSG_SIZ]; // a bit generous?
3661 programStats.nodes = programStats.depth = programStats.time =
3662 programStats.score = programStats.got_only_move = 0;
3663 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3665 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3666 strcat(bookMove, bookHit);
3667 HandleMachineMove(bookMove, &first);
3672 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3673 started == STARTED_HOLDINGS ||
3674 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3675 /* Accumulate characters in move list or board */
3676 parse[parse_pos++] = buf[i];
3679 /* Start of game messages. Mostly we detect start of game
3680 when the first board image arrives. On some versions
3681 of the ICS, though, we need to do a "refresh" after starting
3682 to observe in order to get the current board right away. */
3683 if (looking_at(buf, &i, "Adding game * to observation list")) {
3684 started = STARTED_OBSERVE;
3688 /* Handle auto-observe */
3689 if (appData.autoObserve &&
3690 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3691 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3693 /* Choose the player that was highlighted, if any. */
3694 if (star_match[0][0] == '\033' ||
3695 star_match[1][0] != '\033') {
3696 player = star_match[0];
3698 player = star_match[2];
3700 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3701 ics_prefix, StripHighlightAndTitle(player));
3704 /* Save ratings from notify string */
3705 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3706 player1Rating = string_to_rating(star_match[1]);
3707 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3708 player2Rating = string_to_rating(star_match[3]);
3710 if (appData.debugMode)
3712 "Ratings from 'Game notification:' %s %d, %s %d\n",
3713 player1Name, player1Rating,
3714 player2Name, player2Rating);
3719 /* Deal with automatic examine mode after a game,
3720 and with IcsObserving -> IcsExamining transition */
3721 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3722 looking_at(buf, &i, "has made you an examiner of game *")) {
3724 int gamenum = atoi(star_match[0]);
3725 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3726 gamenum == ics_gamenum) {
3727 /* We were already playing or observing this game;
3728 no need to refetch history */
3729 gameMode = IcsExamining;
3731 pauseExamForwardMostMove = forwardMostMove;
3732 } else if (currentMove < forwardMostMove) {
3733 ForwardInner(forwardMostMove);
3736 /* I don't think this case really can happen */
3737 SendToICS(ics_prefix);
3738 SendToICS("refresh\n");
3743 /* Error messages */
3744 // if (ics_user_moved) {
3745 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3746 if (looking_at(buf, &i, "Illegal move") ||
3747 looking_at(buf, &i, "Not a legal move") ||
3748 looking_at(buf, &i, "Your king is in check") ||
3749 looking_at(buf, &i, "It isn't your turn") ||
3750 looking_at(buf, &i, "It is not your move")) {
3752 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3753 currentMove = forwardMostMove-1;
3754 DisplayMove(currentMove - 1); /* before DMError */
3755 DrawPosition(FALSE, boards[currentMove]);
3756 SwitchClocks(forwardMostMove-1); // [HGM] race
3757 DisplayBothClocks();
3759 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3765 if (looking_at(buf, &i, "still have time") ||
3766 looking_at(buf, &i, "not out of time") ||
3767 looking_at(buf, &i, "either player is out of time") ||
3768 looking_at(buf, &i, "has timeseal; checking")) {
3769 /* We must have called his flag a little too soon */
3770 whiteFlag = blackFlag = FALSE;
3774 if (looking_at(buf, &i, "added * seconds to") ||
3775 looking_at(buf, &i, "seconds were added to")) {
3776 /* Update the clocks */
3777 SendToICS(ics_prefix);
3778 SendToICS("refresh\n");
3782 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3783 ics_clock_paused = TRUE;
3788 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3789 ics_clock_paused = FALSE;
3794 /* Grab player ratings from the Creating: message.
3795 Note we have to check for the special case when
3796 the ICS inserts things like [white] or [black]. */
3797 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3798 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3800 0 player 1 name (not necessarily white)
3802 2 empty, white, or black (IGNORED)
3803 3 player 2 name (not necessarily black)
3806 The names/ratings are sorted out when the game
3807 actually starts (below).
3809 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3810 player1Rating = string_to_rating(star_match[1]);
3811 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3812 player2Rating = string_to_rating(star_match[4]);
3814 if (appData.debugMode)
3816 "Ratings from 'Creating:' %s %d, %s %d\n",
3817 player1Name, player1Rating,
3818 player2Name, player2Rating);
3823 /* Improved generic start/end-of-game messages */
3824 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3825 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3826 /* If tkind == 0: */
3827 /* star_match[0] is the game number */
3828 /* [1] is the white player's name */
3829 /* [2] is the black player's name */
3830 /* For end-of-game: */
3831 /* [3] is the reason for the game end */
3832 /* [4] is a PGN end game-token, preceded by " " */
3833 /* For start-of-game: */
3834 /* [3] begins with "Creating" or "Continuing" */
3835 /* [4] is " *" or empty (don't care). */
3836 int gamenum = atoi(star_match[0]);
3837 char *whitename, *blackname, *why, *endtoken;
3838 ChessMove endtype = EndOfFile;
3841 whitename = star_match[1];
3842 blackname = star_match[2];
3843 why = star_match[3];
3844 endtoken = star_match[4];
3846 whitename = star_match[1];
3847 blackname = star_match[3];
3848 why = star_match[5];
3849 endtoken = star_match[6];
3852 /* Game start messages */
3853 if (strncmp(why, "Creating ", 9) == 0 ||
3854 strncmp(why, "Continuing ", 11) == 0) {
3855 gs_gamenum = gamenum;
3856 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3857 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3859 if (appData.zippyPlay) {
3860 ZippyGameStart(whitename, blackname);
3863 partnerBoardValid = FALSE; // [HGM] bughouse
3867 /* Game end messages */
3868 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3869 ics_gamenum != gamenum) {
3872 while (endtoken[0] == ' ') endtoken++;
3873 switch (endtoken[0]) {
3876 endtype = GameUnfinished;
3879 endtype = BlackWins;
3882 if (endtoken[1] == '/')
3883 endtype = GameIsDrawn;
3885 endtype = WhiteWins;
3888 GameEnds(endtype, why, GE_ICS);
3890 if (appData.zippyPlay && first.initDone) {
3891 ZippyGameEnd(endtype, why);
3892 if (first.pr == NULL) {
3893 /* Start the next process early so that we'll
3894 be ready for the next challenge */
3895 StartChessProgram(&first);
3897 /* Send "new" early, in case this command takes
3898 a long time to finish, so that we'll be ready
3899 for the next challenge. */
3900 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3904 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3908 if (looking_at(buf, &i, "Removing game * from observation") ||
3909 looking_at(buf, &i, "no longer observing game *") ||
3910 looking_at(buf, &i, "Game * (*) has no examiners")) {
3911 if (gameMode == IcsObserving &&
3912 atoi(star_match[0]) == ics_gamenum)
3914 /* icsEngineAnalyze */
3915 if (appData.icsEngineAnalyze) {
3922 ics_user_moved = FALSE;
3927 if (looking_at(buf, &i, "no longer examining game *")) {
3928 if (gameMode == IcsExamining &&
3929 atoi(star_match[0]) == ics_gamenum)
3933 ics_user_moved = FALSE;
3938 /* Advance leftover_start past any newlines we find,
3939 so only partial lines can get reparsed */
3940 if (looking_at(buf, &i, "\n")) {
3941 prevColor = curColor;
3942 if (curColor != ColorNormal) {
3943 if (oldi > next_out) {
3944 SendToPlayer(&buf[next_out], oldi - next_out);
3947 Colorize(ColorNormal, FALSE);
3948 curColor = ColorNormal;
3950 if (started == STARTED_BOARD) {
3951 started = STARTED_NONE;
3952 parse[parse_pos] = NULLCHAR;
3953 ParseBoard12(parse);
3956 /* Send premove here */
3957 if (appData.premove) {
3959 if (currentMove == 0 &&
3960 gameMode == IcsPlayingWhite &&
3961 appData.premoveWhite) {
3962 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3963 if (appData.debugMode)
3964 fprintf(debugFP, "Sending premove:\n");
3966 } else if (currentMove == 1 &&
3967 gameMode == IcsPlayingBlack &&
3968 appData.premoveBlack) {
3969 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3970 if (appData.debugMode)
3971 fprintf(debugFP, "Sending premove:\n");
3973 } else if (gotPremove) {
3975 ClearPremoveHighlights();
3976 if (appData.debugMode)
3977 fprintf(debugFP, "Sending premove:\n");
3978 UserMoveEvent(premoveFromX, premoveFromY,
3979 premoveToX, premoveToY,
3984 /* Usually suppress following prompt */
3985 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3986 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3987 if (looking_at(buf, &i, "*% ")) {
3988 savingComment = FALSE;
3993 } else if (started == STARTED_HOLDINGS) {
3995 char new_piece[MSG_SIZ];
3996 started = STARTED_NONE;
3997 parse[parse_pos] = NULLCHAR;
3998 if (appData.debugMode)
3999 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4000 parse, currentMove);
4001 if (sscanf(parse, " game %d", &gamenum) == 1) {
4002 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4003 if (gameInfo.variant == VariantNormal) {
4004 /* [HGM] We seem to switch variant during a game!
4005 * Presumably no holdings were displayed, so we have
4006 * to move the position two files to the right to
4007 * create room for them!
4009 VariantClass newVariant;
4010 switch(gameInfo.boardWidth) { // base guess on board width
4011 case 9: newVariant = VariantShogi; break;
4012 case 10: newVariant = VariantGreat; break;
4013 default: newVariant = VariantCrazyhouse; break;
4015 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4016 /* Get a move list just to see the header, which
4017 will tell us whether this is really bug or zh */
4018 if (ics_getting_history == H_FALSE) {
4019 ics_getting_history = H_REQUESTED;
4020 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4024 new_piece[0] = NULLCHAR;
4025 sscanf(parse, "game %d white [%s black [%s <- %s",
4026 &gamenum, white_holding, black_holding,
4028 white_holding[strlen(white_holding)-1] = NULLCHAR;
4029 black_holding[strlen(black_holding)-1] = NULLCHAR;
4030 /* [HGM] copy holdings to board holdings area */
4031 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4032 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4033 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4035 if (appData.zippyPlay && first.initDone) {
4036 ZippyHoldings(white_holding, black_holding,
4040 if (tinyLayout || smallLayout) {
4041 char wh[16], bh[16];
4042 PackHolding(wh, white_holding);
4043 PackHolding(bh, black_holding);
4044 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
4045 gameInfo.white, gameInfo.black);
4047 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
4048 gameInfo.white, white_holding,
4049 gameInfo.black, black_holding);
4051 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4052 DrawPosition(FALSE, boards[currentMove]);
4054 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4055 sscanf(parse, "game %d white [%s black [%s <- %s",
4056 &gamenum, white_holding, black_holding,
4058 white_holding[strlen(white_holding)-1] = NULLCHAR;
4059 black_holding[strlen(black_holding)-1] = NULLCHAR;
4060 /* [HGM] copy holdings to partner-board holdings area */
4061 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4062 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4063 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4064 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4065 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4068 /* Suppress following prompt */
4069 if (looking_at(buf, &i, "*% ")) {
4070 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4071 savingComment = FALSE;
4079 i++; /* skip unparsed character and loop back */
4082 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4083 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4084 // SendToPlayer(&buf[next_out], i - next_out);
4085 started != STARTED_HOLDINGS && leftover_start > next_out) {
4086 SendToPlayer(&buf[next_out], leftover_start - next_out);
4090 leftover_len = buf_len - leftover_start;
4091 /* if buffer ends with something we couldn't parse,
4092 reparse it after appending the next read */
4094 } else if (count == 0) {
4095 RemoveInputSource(isr);
4096 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4098 DisplayFatalError(_("Error reading from ICS"), error, 1);
4103 /* Board style 12 looks like this:
4105 <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
4107 * The "<12> " is stripped before it gets to this routine. The two
4108 * trailing 0's (flip state and clock ticking) are later addition, and
4109 * some chess servers may not have them, or may have only the first.
4110 * Additional trailing fields may be added in the future.
4113 #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"
4115 #define RELATION_OBSERVING_PLAYED 0
4116 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4117 #define RELATION_PLAYING_MYMOVE 1
4118 #define RELATION_PLAYING_NOTMYMOVE -1
4119 #define RELATION_EXAMINING 2
4120 #define RELATION_ISOLATED_BOARD -3
4121 #define RELATION_STARTING_POSITION -4 /* FICS only */
4124 ParseBoard12(string)
4127 GameMode newGameMode;
4128 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
4129 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
4130 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4131 char to_play, board_chars[200];
4132 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4133 char black[32], white[32];
4135 int prevMove = currentMove;
4138 int fromX, fromY, toX, toY;
4140 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4141 char *bookHit = NULL; // [HGM] book
4142 Boolean weird = FALSE, reqFlag = FALSE;
4144 fromX = fromY = toX = toY = -1;
4148 if (appData.debugMode)
4149 fprintf(debugFP, _("Parsing board: %s\n"), string);
4151 move_str[0] = NULLCHAR;
4152 elapsed_time[0] = NULLCHAR;
4153 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4155 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4156 if(string[i] == ' ') { ranks++; files = 0; }
4158 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4161 for(j = 0; j <i; j++) board_chars[j] = string[j];
4162 board_chars[i] = '\0';
4165 n = sscanf(string, PATTERN, &to_play, &double_push,
4166 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4167 &gamenum, white, black, &relation, &basetime, &increment,
4168 &white_stren, &black_stren, &white_time, &black_time,
4169 &moveNum, str, elapsed_time, move_str, &ics_flip,
4173 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4174 DisplayError(str, 0);
4178 /* Convert the move number to internal form */
4179 moveNum = (moveNum - 1) * 2;
4180 if (to_play == 'B') moveNum++;
4181 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4182 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4188 case RELATION_OBSERVING_PLAYED:
4189 case RELATION_OBSERVING_STATIC:
4190 if (gamenum == -1) {
4191 /* Old ICC buglet */
4192 relation = RELATION_OBSERVING_STATIC;
4194 newGameMode = IcsObserving;
4196 case RELATION_PLAYING_MYMOVE:
4197 case RELATION_PLAYING_NOTMYMOVE:
4199 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4200 IcsPlayingWhite : IcsPlayingBlack;
4202 case RELATION_EXAMINING:
4203 newGameMode = IcsExamining;
4205 case RELATION_ISOLATED_BOARD:
4207 /* Just display this board. If user was doing something else,
4208 we will forget about it until the next board comes. */
4209 newGameMode = IcsIdle;
4211 case RELATION_STARTING_POSITION:
4212 newGameMode = gameMode;
4216 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
4217 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4218 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4220 for (k = 0; k < ranks; k++) {
4221 for (j = 0; j < files; j++)
4222 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4223 if(gameInfo.holdingsWidth > 1) {
4224 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4225 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4228 CopyBoard(partnerBoard, board);
4229 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4230 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4231 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4232 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4233 if(toSqr = strchr(str, '-')) {
4234 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4235 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4236 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4237 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4238 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4239 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4240 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
4241 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
4242 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
4243 DisplayMessage(partnerStatus, "");
4244 partnerBoardValid = TRUE;
4248 /* Modify behavior for initial board display on move listing
4251 switch (ics_getting_history) {
4255 case H_GOT_REQ_HEADER:
4256 case H_GOT_UNREQ_HEADER:
4257 /* This is the initial position of the current game */
4258 gamenum = ics_gamenum;
4259 moveNum = 0; /* old ICS bug workaround */
4260 if (to_play == 'B') {
4261 startedFromSetupPosition = TRUE;
4262 blackPlaysFirst = TRUE;
4264 if (forwardMostMove == 0) forwardMostMove = 1;
4265 if (backwardMostMove == 0) backwardMostMove = 1;
4266 if (currentMove == 0) currentMove = 1;
4268 newGameMode = gameMode;
4269 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4271 case H_GOT_UNWANTED_HEADER:
4272 /* This is an initial board that we don't want */
4274 case H_GETTING_MOVES:
4275 /* Should not happen */
4276 DisplayError(_("Error gathering move list: extra board"), 0);
4277 ics_getting_history = H_FALSE;
4281 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4282 weird && (int)gameInfo.variant < (int)VariantShogi) {
4283 /* [HGM] We seem to have switched variant unexpectedly
4284 * Try to guess new variant from board size
4286 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4287 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4288 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4289 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4290 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4291 if(!weird) newVariant = VariantNormal;
4292 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4293 /* Get a move list just to see the header, which
4294 will tell us whether this is really bug or zh */
4295 if (ics_getting_history == H_FALSE) {
4296 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4297 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4302 /* Take action if this is the first board of a new game, or of a
4303 different game than is currently being displayed. */
4304 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4305 relation == RELATION_ISOLATED_BOARD) {
4307 /* Forget the old game and get the history (if any) of the new one */
4308 if (gameMode != BeginningOfGame) {
4312 if (appData.autoRaiseBoard) BoardToTop();
4314 if (gamenum == -1) {
4315 newGameMode = IcsIdle;
4316 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4317 appData.getMoveList && !reqFlag) {
4318 /* Need to get game history */
4319 ics_getting_history = H_REQUESTED;
4320 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4324 /* Initially flip the board to have black on the bottom if playing
4325 black or if the ICS flip flag is set, but let the user change
4326 it with the Flip View button. */
4327 flipView = appData.autoFlipView ?
4328 (newGameMode == IcsPlayingBlack) || ics_flip :
4331 /* Done with values from previous mode; copy in new ones */
4332 gameMode = newGameMode;
4334 ics_gamenum = gamenum;
4335 if (gamenum == gs_gamenum) {
4336 int klen = strlen(gs_kind);
4337 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4338 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4339 gameInfo.event = StrSave(str);
4341 gameInfo.event = StrSave("ICS game");
4343 gameInfo.site = StrSave(appData.icsHost);
4344 gameInfo.date = PGNDate();
4345 gameInfo.round = StrSave("-");
4346 gameInfo.white = StrSave(white);
4347 gameInfo.black = StrSave(black);
4348 timeControl = basetime * 60 * 1000;
4350 timeIncrement = increment * 1000;
4351 movesPerSession = 0;
4352 gameInfo.timeControl = TimeControlTagValue();
4353 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4354 if (appData.debugMode) {
4355 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4356 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4357 setbuf(debugFP, NULL);
4360 gameInfo.outOfBook = NULL;
4362 /* Do we have the ratings? */
4363 if (strcmp(player1Name, white) == 0 &&
4364 strcmp(player2Name, black) == 0) {
4365 if (appData.debugMode)
4366 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4367 player1Rating, player2Rating);
4368 gameInfo.whiteRating = player1Rating;
4369 gameInfo.blackRating = player2Rating;
4370 } else if (strcmp(player2Name, white) == 0 &&
4371 strcmp(player1Name, black) == 0) {
4372 if (appData.debugMode)
4373 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4374 player2Rating, player1Rating);
4375 gameInfo.whiteRating = player2Rating;
4376 gameInfo.blackRating = player1Rating;
4378 player1Name[0] = player2Name[0] = NULLCHAR;
4380 /* Silence shouts if requested */
4381 if (appData.quietPlay &&
4382 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4383 SendToICS(ics_prefix);
4384 SendToICS("set shout 0\n");
4388 /* Deal with midgame name changes */
4390 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4391 if (gameInfo.white) free(gameInfo.white);
4392 gameInfo.white = StrSave(white);
4394 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4395 if (gameInfo.black) free(gameInfo.black);
4396 gameInfo.black = StrSave(black);
4400 /* Throw away game result if anything actually changes in examine mode */
4401 if (gameMode == IcsExamining && !newGame) {
4402 gameInfo.result = GameUnfinished;
4403 if (gameInfo.resultDetails != NULL) {
4404 free(gameInfo.resultDetails);
4405 gameInfo.resultDetails = NULL;
4409 /* In pausing && IcsExamining mode, we ignore boards coming
4410 in if they are in a different variation than we are. */
4411 if (pauseExamInvalid) return;
4412 if (pausing && gameMode == IcsExamining) {
4413 if (moveNum <= pauseExamForwardMostMove) {
4414 pauseExamInvalid = TRUE;
4415 forwardMostMove = pauseExamForwardMostMove;
4420 if (appData.debugMode) {
4421 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4423 /* Parse the board */
4424 for (k = 0; k < ranks; k++) {
4425 for (j = 0; j < files; j++)
4426 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4427 if(gameInfo.holdingsWidth > 1) {
4428 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4429 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4432 CopyBoard(boards[moveNum], board);
4433 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4435 startedFromSetupPosition =
4436 !CompareBoards(board, initialPosition);
4437 if(startedFromSetupPosition)
4438 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4441 /* [HGM] Set castling rights. Take the outermost Rooks,
4442 to make it also work for FRC opening positions. Note that board12
4443 is really defective for later FRC positions, as it has no way to
4444 indicate which Rook can castle if they are on the same side of King.
4445 For the initial position we grant rights to the outermost Rooks,
4446 and remember thos rights, and we then copy them on positions
4447 later in an FRC game. This means WB might not recognize castlings with
4448 Rooks that have moved back to their original position as illegal,
4449 but in ICS mode that is not its job anyway.
4451 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4452 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4454 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4455 if(board[0][i] == WhiteRook) j = i;
4456 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4457 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4458 if(board[0][i] == WhiteRook) j = i;
4459 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4460 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4461 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4462 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4463 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4464 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4465 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4467 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4468 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4469 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4470 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4471 if(board[BOARD_HEIGHT-1][k] == bKing)
4472 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4473 if(gameInfo.variant == VariantTwoKings) {
4474 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4475 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4476 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4479 r = boards[moveNum][CASTLING][0] = initialRights[0];
4480 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4481 r = boards[moveNum][CASTLING][1] = initialRights[1];
4482 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4483 r = boards[moveNum][CASTLING][3] = initialRights[3];
4484 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4485 r = boards[moveNum][CASTLING][4] = initialRights[4];
4486 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4487 /* wildcastle kludge: always assume King has rights */
4488 r = boards[moveNum][CASTLING][2] = initialRights[2];
4489 r = boards[moveNum][CASTLING][5] = initialRights[5];
4491 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4492 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4495 if (ics_getting_history == H_GOT_REQ_HEADER ||
4496 ics_getting_history == H_GOT_UNREQ_HEADER) {
4497 /* This was an initial position from a move list, not
4498 the current position */
4502 /* Update currentMove and known move number limits */
4503 newMove = newGame || moveNum > forwardMostMove;
4506 forwardMostMove = backwardMostMove = currentMove = moveNum;
4507 if (gameMode == IcsExamining && moveNum == 0) {
4508 /* Workaround for ICS limitation: we are not told the wild
4509 type when starting to examine a game. But if we ask for
4510 the move list, the move list header will tell us */
4511 ics_getting_history = H_REQUESTED;
4512 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4515 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4516 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4518 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4519 /* [HGM] applied this also to an engine that is silently watching */
4520 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4521 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4522 gameInfo.variant == currentlyInitializedVariant) {
4523 takeback = forwardMostMove - moveNum;
4524 for (i = 0; i < takeback; i++) {
4525 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4526 SendToProgram("undo\n", &first);
4531 forwardMostMove = moveNum;
4532 if (!pausing || currentMove > forwardMostMove)
4533 currentMove = forwardMostMove;
4535 /* New part of history that is not contiguous with old part */
4536 if (pausing && gameMode == IcsExamining) {
4537 pauseExamInvalid = TRUE;
4538 forwardMostMove = pauseExamForwardMostMove;
4541 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4543 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4544 // [HGM] when we will receive the move list we now request, it will be
4545 // fed to the engine from the first move on. So if the engine is not
4546 // in the initial position now, bring it there.
4547 InitChessProgram(&first, 0);
4550 ics_getting_history = H_REQUESTED;
4551 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4554 forwardMostMove = backwardMostMove = currentMove = moveNum;
4557 /* Update the clocks */
4558 if (strchr(elapsed_time, '.')) {
4560 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4561 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4563 /* Time is in seconds */
4564 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4565 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4570 if (appData.zippyPlay && newGame &&
4571 gameMode != IcsObserving && gameMode != IcsIdle &&
4572 gameMode != IcsExamining)
4573 ZippyFirstBoard(moveNum, basetime, increment);
4576 /* Put the move on the move list, first converting
4577 to canonical algebraic form. */
4579 if (appData.debugMode) {
4580 if (appData.debugMode) { int f = forwardMostMove;
4581 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4582 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4583 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4585 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4586 fprintf(debugFP, "moveNum = %d\n", moveNum);
4587 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4588 setbuf(debugFP, NULL);
4590 if (moveNum <= backwardMostMove) {
4591 /* We don't know what the board looked like before
4593 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4594 strcat(parseList[moveNum - 1], " ");
4595 strcat(parseList[moveNum - 1], elapsed_time);
4596 moveList[moveNum - 1][0] = NULLCHAR;
4597 } else if (strcmp(move_str, "none") == 0) {
4598 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4599 /* Again, we don't know what the board looked like;
4600 this is really the start of the game. */
4601 parseList[moveNum - 1][0] = NULLCHAR;
4602 moveList[moveNum - 1][0] = NULLCHAR;
4603 backwardMostMove = moveNum;
4604 startedFromSetupPosition = TRUE;
4605 fromX = fromY = toX = toY = -1;
4607 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4608 // So we parse the long-algebraic move string in stead of the SAN move
4609 int valid; char buf[MSG_SIZ], *prom;
4611 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4612 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4613 // str looks something like "Q/a1-a2"; kill the slash
4615 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4616 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4617 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4618 strcat(buf, prom); // long move lacks promo specification!
4619 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4620 if(appData.debugMode)
4621 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4622 safeStrCpy(move_str, buf, MSG_SIZ);
4624 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4625 &fromX, &fromY, &toX, &toY, &promoChar)
4626 || ParseOneMove(buf, moveNum - 1, &moveType,
4627 &fromX, &fromY, &toX, &toY, &promoChar);
4628 // end of long SAN patch
4630 (void) CoordsToAlgebraic(boards[moveNum - 1],
4631 PosFlags(moveNum - 1),
4632 fromY, fromX, toY, toX, promoChar,
4633 parseList[moveNum-1]);
4634 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4640 if(gameInfo.variant != VariantShogi)
4641 strcat(parseList[moveNum - 1], "+");
4644 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4645 strcat(parseList[moveNum - 1], "#");
4648 strcat(parseList[moveNum - 1], " ");
4649 strcat(parseList[moveNum - 1], elapsed_time);
4650 /* currentMoveString is set as a side-effect of ParseOneMove */
4651 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4652 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4653 strcat(moveList[moveNum - 1], "\n");
4655 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4656 && gameInfo.variant != VariantGrand) // inherit info that ICS does not give from previous board
4657 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4658 ChessSquare old, new = boards[moveNum][k][j];
4659 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4660 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4661 if(old == new) continue;
4662 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4663 else if(new == WhiteWazir || new == BlackWazir) {
4664 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4665 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4666 else boards[moveNum][k][j] = old; // preserve type of Gold
4667 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4668 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4671 /* Move from ICS was illegal!? Punt. */
4672 if (appData.debugMode) {
4673 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4674 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4676 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4677 strcat(parseList[moveNum - 1], " ");
4678 strcat(parseList[moveNum - 1], elapsed_time);
4679 moveList[moveNum - 1][0] = NULLCHAR;
4680 fromX = fromY = toX = toY = -1;
4683 if (appData.debugMode) {
4684 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4685 setbuf(debugFP, NULL);
4689 /* Send move to chess program (BEFORE animating it). */
4690 if (appData.zippyPlay && !newGame && newMove &&
4691 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4693 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4694 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4695 if (moveList[moveNum - 1][0] == NULLCHAR) {
4696 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4698 DisplayError(str, 0);
4700 if (first.sendTime) {
4701 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4703 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4704 if (firstMove && !bookHit) {
4706 if (first.useColors) {
4707 SendToProgram(gameMode == IcsPlayingWhite ?
4709 "black\ngo\n", &first);
4711 SendToProgram("go\n", &first);
4713 first.maybeThinking = TRUE;
4716 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4717 if (moveList[moveNum - 1][0] == NULLCHAR) {
4718 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4719 DisplayError(str, 0);
4721 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4722 SendMoveToProgram(moveNum - 1, &first);
4729 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4730 /* If move comes from a remote source, animate it. If it
4731 isn't remote, it will have already been animated. */
4732 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4733 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4735 if (!pausing && appData.highlightLastMove) {
4736 SetHighlights(fromX, fromY, toX, toY);
4740 /* Start the clocks */
4741 whiteFlag = blackFlag = FALSE;
4742 appData.clockMode = !(basetime == 0 && increment == 0);
4744 ics_clock_paused = TRUE;
4746 } else if (ticking == 1) {
4747 ics_clock_paused = FALSE;
4749 if (gameMode == IcsIdle ||
4750 relation == RELATION_OBSERVING_STATIC ||
4751 relation == RELATION_EXAMINING ||
4753 DisplayBothClocks();
4757 /* Display opponents and material strengths */
4758 if (gameInfo.variant != VariantBughouse &&
4759 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4760 if (tinyLayout || smallLayout) {
4761 if(gameInfo.variant == VariantNormal)
4762 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4763 gameInfo.white, white_stren, gameInfo.black, black_stren,
4764 basetime, increment);
4766 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4767 gameInfo.white, white_stren, gameInfo.black, black_stren,
4768 basetime, increment, (int) gameInfo.variant);
4770 if(gameInfo.variant == VariantNormal)
4771 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4772 gameInfo.white, white_stren, gameInfo.black, black_stren,
4773 basetime, increment);
4775 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4776 gameInfo.white, white_stren, gameInfo.black, black_stren,
4777 basetime, increment, VariantName(gameInfo.variant));
4780 if (appData.debugMode) {
4781 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4786 /* Display the board */
4787 if (!pausing && !appData.noGUI) {
4789 if (appData.premove)
4791 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4792 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4793 ClearPremoveHighlights();
4795 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4796 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4797 DrawPosition(j, boards[currentMove]);
4799 DisplayMove(moveNum - 1);
4800 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4801 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4802 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4803 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4807 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4809 if(bookHit) { // [HGM] book: simulate book reply
4810 static char bookMove[MSG_SIZ]; // a bit generous?
4812 programStats.nodes = programStats.depth = programStats.time =
4813 programStats.score = programStats.got_only_move = 0;
4814 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4816 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4817 strcat(bookMove, bookHit);
4818 HandleMachineMove(bookMove, &first);
4827 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4828 ics_getting_history = H_REQUESTED;
4829 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4835 AnalysisPeriodicEvent(force)
4838 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4839 && !force) || !appData.periodicUpdates)
4842 /* Send . command to Crafty to collect stats */
4843 SendToProgram(".\n", &first);
4845 /* Don't send another until we get a response (this makes
4846 us stop sending to old Crafty's which don't understand
4847 the "." command (sending illegal cmds resets node count & time,
4848 which looks bad)) */
4849 programStats.ok_to_send = 0;
4852 void ics_update_width(new_width)
4855 ics_printf("set width %d\n", new_width);
4859 SendMoveToProgram(moveNum, cps)
4861 ChessProgramState *cps;
4865 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
4866 // null move in variant where engine does not understand it (for analysis purposes)
4867 SendBoard(cps, moveNum + 1); // send position after move in stead.
4870 if (cps->useUsermove) {
4871 SendToProgram("usermove ", cps);
4875 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4876 int len = space - parseList[moveNum];
4877 memcpy(buf, parseList[moveNum], len);
4879 buf[len] = NULLCHAR;
4881 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4883 SendToProgram(buf, cps);
4885 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4886 AlphaRank(moveList[moveNum], 4);
4887 SendToProgram(moveList[moveNum], cps);
4888 AlphaRank(moveList[moveNum], 4); // and back
4890 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4891 * the engine. It would be nice to have a better way to identify castle
4893 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4894 && cps->useOOCastle) {
4895 int fromX = moveList[moveNum][0] - AAA;
4896 int fromY = moveList[moveNum][1] - ONE;
4897 int toX = moveList[moveNum][2] - AAA;
4898 int toY = moveList[moveNum][3] - ONE;
4899 if((boards[moveNum][fromY][fromX] == WhiteKing
4900 && boards[moveNum][toY][toX] == WhiteRook)
4901 || (boards[moveNum][fromY][fromX] == BlackKing
4902 && boards[moveNum][toY][toX] == BlackRook)) {
4903 if(toX > fromX) SendToProgram("O-O\n", cps);
4904 else SendToProgram("O-O-O\n", cps);
4906 else SendToProgram(moveList[moveNum], cps);
4908 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
4909 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
4910 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
4911 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
4912 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4914 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
4915 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4916 SendToProgram(buf, cps);
4918 else SendToProgram(moveList[moveNum], cps);
4919 /* End of additions by Tord */
4922 /* [HGM] setting up the opening has brought engine in force mode! */
4923 /* Send 'go' if we are in a mode where machine should play. */
4924 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4925 (gameMode == TwoMachinesPlay ||
4927 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4929 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4930 SendToProgram("go\n", cps);
4931 if (appData.debugMode) {
4932 fprintf(debugFP, "(extra)\n");
4935 setboardSpoiledMachineBlack = 0;
4939 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4941 int fromX, fromY, toX, toY;
4944 char user_move[MSG_SIZ];
4948 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4949 (int)moveType, fromX, fromY, toX, toY);
4950 DisplayError(user_move + strlen("say "), 0);
4952 case WhiteKingSideCastle:
4953 case BlackKingSideCastle:
4954 case WhiteQueenSideCastleWild:
4955 case BlackQueenSideCastleWild:
4957 case WhiteHSideCastleFR:
4958 case BlackHSideCastleFR:
4960 snprintf(user_move, MSG_SIZ, "o-o\n");
4962 case WhiteQueenSideCastle:
4963 case BlackQueenSideCastle:
4964 case WhiteKingSideCastleWild:
4965 case BlackKingSideCastleWild:
4967 case WhiteASideCastleFR:
4968 case BlackASideCastleFR:
4970 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4972 case WhiteNonPromotion:
4973 case BlackNonPromotion:
4974 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4976 case WhitePromotion:
4977 case BlackPromotion:
4978 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4979 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4980 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4981 PieceToChar(WhiteFerz));
4982 else if(gameInfo.variant == VariantGreat)
4983 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4984 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4985 PieceToChar(WhiteMan));
4987 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4988 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4994 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4995 ToUpper(PieceToChar((ChessSquare) fromX)),
4996 AAA + toX, ONE + toY);
4998 case IllegalMove: /* could be a variant we don't quite understand */
4999 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5001 case WhiteCapturesEnPassant:
5002 case BlackCapturesEnPassant:
5003 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5004 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5007 SendToICS(user_move);
5008 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5009 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5014 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5015 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5016 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5017 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5018 DisplayError("You cannot do this while you are playing or observing", 0);
5021 if(gameMode != IcsExamining) { // is this ever not the case?
5022 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5024 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5025 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5026 } else { // on FICS we must first go to general examine mode
5027 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5029 if(gameInfo.variant != VariantNormal) {
5030 // try figure out wild number, as xboard names are not always valid on ICS
5031 for(i=1; i<=36; i++) {
5032 snprintf(buf, MSG_SIZ, "wild/%d", i);
5033 if(StringToVariant(buf) == gameInfo.variant) break;
5035 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5036 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5037 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5038 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5039 SendToICS(ics_prefix);
5041 if(startedFromSetupPosition || backwardMostMove != 0) {
5042 fen = PositionToFEN(backwardMostMove, NULL);
5043 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5044 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5046 } else { // FICS: everything has to set by separate bsetup commands
5047 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5048 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5050 if(!WhiteOnMove(backwardMostMove)) {
5051 SendToICS("bsetup tomove black\n");
5053 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5054 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5056 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5057 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5059 i = boards[backwardMostMove][EP_STATUS];
5060 if(i >= 0) { // set e.p.
5061 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5067 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5068 SendToICS("bsetup done\n"); // switch to normal examining.
5070 for(i = backwardMostMove; i<last; i++) {
5072 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5075 SendToICS(ics_prefix);
5076 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5080 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
5085 if (rf == DROP_RANK) {
5086 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5087 sprintf(move, "%c@%c%c\n",
5088 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5090 if (promoChar == 'x' || promoChar == NULLCHAR) {
5091 sprintf(move, "%c%c%c%c\n",
5092 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5094 sprintf(move, "%c%c%c%c%c\n",
5095 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5101 ProcessICSInitScript(f)
5106 while (fgets(buf, MSG_SIZ, f)) {
5107 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5114 static int lastX, lastY, selectFlag, dragging;
5119 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5120 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5121 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5122 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5123 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5124 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
5127 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5128 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5129 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5130 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5132 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5133 appData.testLegality && (promoSweep == king ||
5134 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
5135 ChangeDragPiece(promoSweep);
5138 int PromoScroll(int x, int y)
5142 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5143 if(abs(x - lastX) < 15 && abs(y - lastY) < 15) return FALSE;
5144 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5145 if(!step) return FALSE;
5146 lastX = x; lastY = y;
5147 if((promoSweep < BlackPawn) == flipView) step = -step;
5148 if(step > 0) selectFlag = 1;
5149 if(!selectFlag) Sweep(step);
5156 ChessSquare piece = boards[currentMove][toY][toX];
5159 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5160 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5161 if(!step) step = -1;
5162 } while(PieceToChar(pieceSweep) == '.');
5163 boards[currentMove][toY][toX] = pieceSweep;
5164 DrawPosition(FALSE, boards[currentMove]);
5165 boards[currentMove][toY][toX] = piece;
5167 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5169 AlphaRank(char *move, int n)
5171 // char *p = move, c; int x, y;
5173 if (appData.debugMode) {
5174 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5178 move[2]>='0' && move[2]<='9' &&
5179 move[3]>='a' && move[3]<='x' ) {
5181 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5182 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5184 if(move[0]>='0' && move[0]<='9' &&
5185 move[1]>='a' && move[1]<='x' &&
5186 move[2]>='0' && move[2]<='9' &&
5187 move[3]>='a' && move[3]<='x' ) {
5188 /* input move, Shogi -> normal */
5189 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5190 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5191 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5192 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5195 move[3]>='0' && move[3]<='9' &&
5196 move[2]>='a' && move[2]<='x' ) {
5198 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5199 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5202 move[0]>='a' && move[0]<='x' &&
5203 move[3]>='0' && move[3]<='9' &&
5204 move[2]>='a' && move[2]<='x' ) {
5205 /* output move, normal -> Shogi */
5206 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5207 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5208 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5209 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5210 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5212 if (appData.debugMode) {
5213 fprintf(debugFP, " out = '%s'\n", move);
5217 char yy_textstr[8000];
5219 /* Parser for moves from gnuchess, ICS, or user typein box */
5221 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
5224 ChessMove *moveType;
5225 int *fromX, *fromY, *toX, *toY;
5228 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5230 switch (*moveType) {
5231 case WhitePromotion:
5232 case BlackPromotion:
5233 case WhiteNonPromotion:
5234 case BlackNonPromotion:
5236 case WhiteCapturesEnPassant:
5237 case BlackCapturesEnPassant:
5238 case WhiteKingSideCastle:
5239 case WhiteQueenSideCastle:
5240 case BlackKingSideCastle:
5241 case BlackQueenSideCastle:
5242 case WhiteKingSideCastleWild:
5243 case WhiteQueenSideCastleWild:
5244 case BlackKingSideCastleWild:
5245 case BlackQueenSideCastleWild:
5246 /* Code added by Tord: */
5247 case WhiteHSideCastleFR:
5248 case WhiteASideCastleFR:
5249 case BlackHSideCastleFR:
5250 case BlackASideCastleFR:
5251 /* End of code added by Tord */
5252 case IllegalMove: /* bug or odd chess variant */
5253 *fromX = currentMoveString[0] - AAA;
5254 *fromY = currentMoveString[1] - ONE;
5255 *toX = currentMoveString[2] - AAA;
5256 *toY = currentMoveString[3] - ONE;
5257 *promoChar = currentMoveString[4];
5258 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5259 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5260 if (appData.debugMode) {
5261 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5263 *fromX = *fromY = *toX = *toY = 0;
5266 if (appData.testLegality) {
5267 return (*moveType != IllegalMove);
5269 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5270 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5275 *fromX = *moveType == WhiteDrop ?
5276 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5277 (int) CharToPiece(ToLower(currentMoveString[0]));
5279 *toX = currentMoveString[2] - AAA;
5280 *toY = currentMoveString[3] - ONE;
5281 *promoChar = NULLCHAR;
5285 case ImpossibleMove:
5295 if (appData.debugMode) {
5296 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5299 *fromX = *fromY = *toX = *toY = 0;
5300 *promoChar = NULLCHAR;
5305 Boolean pushed = FALSE;
5306 char *lastParseAttempt;
5309 ParsePV(char *pv, Boolean storeComments, Boolean atEnd)
5310 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5311 int fromX, fromY, toX, toY; char promoChar;
5316 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
5317 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5320 endPV = forwardMostMove;
5322 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5323 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5324 lastParseAttempt = pv;
5325 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5326 if(appData.debugMode){
5327 fprintf(debugFP,"parsePV: %d %c%c%c%c yy='%s'\nPV = '%s'\n", valid, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, yy_textstr, pv);
5329 if(!valid && nr == 0 &&
5330 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5331 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5332 // Hande case where played move is different from leading PV move
5333 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5334 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5335 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5336 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5337 endPV += 2; // if position different, keep this
5338 moveList[endPV-1][0] = fromX + AAA;
5339 moveList[endPV-1][1] = fromY + ONE;
5340 moveList[endPV-1][2] = toX + AAA;
5341 moveList[endPV-1][3] = toY + ONE;
5342 parseList[endPV-1][0] = NULLCHAR;
5343 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5346 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5347 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5348 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5349 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5350 valid++; // allow comments in PV
5354 if(endPV+1 > framePtr) break; // no space, truncate
5357 CopyBoard(boards[endPV], boards[endPV-1]);
5358 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5359 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5360 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5361 CoordsToAlgebraic(boards[endPV - 1],
5362 PosFlags(endPV - 1),
5363 fromY, fromX, toY, toX, promoChar,
5364 parseList[endPV - 1]);
5366 if(atEnd == 2) return; // used hidden, for PV conversion
5367 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5368 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5369 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5370 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5371 DrawPosition(TRUE, boards[currentMove]);
5375 MultiPV(ChessProgramState *cps)
5376 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5378 for(i=0; i<cps->nrOptions; i++)
5379 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5385 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5387 int startPV, multi, lineStart, origIndex = index;
5388 char *p, buf2[MSG_SIZ];
5390 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5391 lastX = x; lastY = y;
5392 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5393 lineStart = startPV = index;
5394 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5395 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5397 do{ while(buf[index] && buf[index] != '\n') index++;
5398 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5400 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(&first)) >= 0) {
5401 int n = first.option[multi].value;
5402 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5403 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5404 if(first.option[multi].value != n) SendToProgram(buf2, &first);
5405 first.option[multi].value = n;
5409 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5410 *start = startPV; *end = index-1;
5417 static char buf[10*MSG_SIZ];
5418 int i, k=0, savedEnd=endPV;
5420 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV);
5421 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5422 for(i = forwardMostMove; i<endPV; i++){
5423 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5424 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5427 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5428 if(forwardMostMove < savedEnd) PopInner(0);
5434 LoadPV(int x, int y)
5435 { // called on right mouse click to load PV
5436 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5437 lastX = x; lastY = y;
5438 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5445 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5446 if(endPV < 0) return;
5448 if(gameMode == AnalyzeMode && currentMove > forwardMostMove) {
5449 Boolean saveAnimate = appData.animate;
5451 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5452 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5453 } else storedGames--; // abandon shelved tail of original game
5456 forwardMostMove = currentMove;
5457 currentMove = oldFMM;
5458 appData.animate = FALSE;
5459 ToNrEvent(forwardMostMove);
5460 appData.animate = saveAnimate;
5462 currentMove = forwardMostMove;
5463 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5464 ClearPremoveHighlights();
5465 DrawPosition(TRUE, boards[currentMove]);
5469 MovePV(int x, int y, int h)
5470 { // step through PV based on mouse coordinates (called on mouse move)
5471 int margin = h>>3, step = 0;
5473 // we must somehow check if right button is still down (might be released off board!)
5474 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5475 if(abs(x - lastX) < 7 && abs(y - lastY) < 7) return;
5476 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5478 lastX = x; lastY = y;
5480 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5481 if(endPV < 0) return;
5482 if(y < margin) step = 1; else
5483 if(y > h - margin) step = -1;
5484 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5485 currentMove += step;
5486 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5487 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5488 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5489 DrawPosition(FALSE, boards[currentMove]);
5493 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5494 // All positions will have equal probability, but the current method will not provide a unique
5495 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5501 int piecesLeft[(int)BlackPawn];
5502 int seed, nrOfShuffles;
5504 void GetPositionNumber()
5505 { // sets global variable seed
5508 seed = appData.defaultFrcPosition;
5509 if(seed < 0) { // randomize based on time for negative FRC position numbers
5510 for(i=0; i<50; i++) seed += random();
5511 seed = random() ^ random() >> 8 ^ random() << 8;
5512 if(seed<0) seed = -seed;
5516 int put(Board board, int pieceType, int rank, int n, int shade)
5517 // put the piece on the (n-1)-th empty squares of the given shade
5521 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5522 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5523 board[rank][i] = (ChessSquare) pieceType;
5524 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5526 piecesLeft[pieceType]--;
5534 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5535 // calculate where the next piece goes, (any empty square), and put it there
5539 i = seed % squaresLeft[shade];
5540 nrOfShuffles *= squaresLeft[shade];
5541 seed /= squaresLeft[shade];
5542 put(board, pieceType, rank, i, shade);
5545 void AddTwoPieces(Board board, int pieceType, int rank)
5546 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5548 int i, n=squaresLeft[ANY], j=n-1, k;
5550 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5551 i = seed % k; // pick one
5554 while(i >= j) i -= j--;
5555 j = n - 1 - j; i += j;
5556 put(board, pieceType, rank, j, ANY);
5557 put(board, pieceType, rank, i, ANY);
5560 void SetUpShuffle(Board board, int number)
5564 GetPositionNumber(); nrOfShuffles = 1;
5566 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5567 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5568 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5570 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5572 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5573 p = (int) board[0][i];
5574 if(p < (int) BlackPawn) piecesLeft[p] ++;
5575 board[0][i] = EmptySquare;
5578 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5579 // shuffles restricted to allow normal castling put KRR first
5580 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5581 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5582 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5583 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5584 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5585 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5586 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5587 put(board, WhiteRook, 0, 0, ANY);
5588 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5591 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5592 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5593 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5594 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5595 while(piecesLeft[p] >= 2) {
5596 AddOnePiece(board, p, 0, LITE);
5597 AddOnePiece(board, p, 0, DARK);
5599 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5602 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5603 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5604 // but we leave King and Rooks for last, to possibly obey FRC restriction
5605 if(p == (int)WhiteRook) continue;
5606 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5607 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5610 // now everything is placed, except perhaps King (Unicorn) and Rooks
5612 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5613 // Last King gets castling rights
5614 while(piecesLeft[(int)WhiteUnicorn]) {
5615 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5616 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5619 while(piecesLeft[(int)WhiteKing]) {
5620 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5621 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5626 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5627 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5630 // Only Rooks can be left; simply place them all
5631 while(piecesLeft[(int)WhiteRook]) {
5632 i = put(board, WhiteRook, 0, 0, ANY);
5633 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5636 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5638 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5641 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5642 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5645 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5648 int SetCharTable( char *table, const char * map )
5649 /* [HGM] moved here from winboard.c because of its general usefulness */
5650 /* Basically a safe strcpy that uses the last character as King */
5652 int result = FALSE; int NrPieces;
5654 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5655 && NrPieces >= 12 && !(NrPieces&1)) {
5656 int i; /* [HGM] Accept even length from 12 to 34 */
5658 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5659 for( i=0; i<NrPieces/2-1; i++ ) {
5661 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5663 table[(int) WhiteKing] = map[NrPieces/2-1];
5664 table[(int) BlackKing] = map[NrPieces-1];
5672 void Prelude(Board board)
5673 { // [HGM] superchess: random selection of exo-pieces
5674 int i, j, k; ChessSquare p;
5675 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5677 GetPositionNumber(); // use FRC position number
5679 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5680 SetCharTable(pieceToChar, appData.pieceToCharTable);
5681 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5682 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5685 j = seed%4; seed /= 4;
5686 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5687 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5688 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5689 j = seed%3 + (seed%3 >= j); seed /= 3;
5690 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5691 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5692 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5693 j = seed%3; seed /= 3;
5694 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5695 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5696 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5697 j = seed%2 + (seed%2 >= j); seed /= 2;
5698 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5699 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5700 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5701 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5702 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5703 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5704 put(board, exoPieces[0], 0, 0, ANY);
5705 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5709 InitPosition(redraw)
5712 ChessSquare (* pieces)[BOARD_FILES];
5713 int i, j, pawnRow, overrule,
5714 oldx = gameInfo.boardWidth,
5715 oldy = gameInfo.boardHeight,
5716 oldh = gameInfo.holdingsWidth;
5719 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5721 /* [AS] Initialize pv info list [HGM] and game status */
5723 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5724 pvInfoList[i].depth = 0;
5725 boards[i][EP_STATUS] = EP_NONE;
5726 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5729 initialRulePlies = 0; /* 50-move counter start */
5731 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5732 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5736 /* [HGM] logic here is completely changed. In stead of full positions */
5737 /* the initialized data only consist of the two backranks. The switch */
5738 /* selects which one we will use, which is than copied to the Board */
5739 /* initialPosition, which for the rest is initialized by Pawns and */
5740 /* empty squares. This initial position is then copied to boards[0], */
5741 /* possibly after shuffling, so that it remains available. */
5743 gameInfo.holdingsWidth = 0; /* default board sizes */
5744 gameInfo.boardWidth = 8;
5745 gameInfo.boardHeight = 8;
5746 gameInfo.holdingsSize = 0;
5747 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5748 for(i=0; i<BOARD_FILES-2; i++)
5749 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5750 initialPosition[EP_STATUS] = EP_NONE;
5751 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5752 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5753 SetCharTable(pieceNickName, appData.pieceNickNames);
5754 else SetCharTable(pieceNickName, "............");
5757 switch (gameInfo.variant) {
5758 case VariantFischeRandom:
5759 shuffleOpenings = TRUE;
5762 case VariantShatranj:
5763 pieces = ShatranjArray;
5764 nrCastlingRights = 0;
5765 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5768 pieces = makrukArray;
5769 nrCastlingRights = 0;
5770 startedFromSetupPosition = TRUE;
5771 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5773 case VariantTwoKings:
5774 pieces = twoKingsArray;
5777 pieces = GrandArray;
5778 nrCastlingRights = 0;
5779 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5780 gameInfo.boardWidth = 10;
5781 gameInfo.boardHeight = 10;
5782 gameInfo.holdingsSize = 7;
5784 case VariantCapaRandom:
5785 shuffleOpenings = TRUE;
5786 case VariantCapablanca:
5787 pieces = CapablancaArray;
5788 gameInfo.boardWidth = 10;
5789 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5792 pieces = GothicArray;
5793 gameInfo.boardWidth = 10;
5794 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5797 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5798 gameInfo.holdingsSize = 7;
5801 pieces = JanusArray;
5802 gameInfo.boardWidth = 10;
5803 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5804 nrCastlingRights = 6;
5805 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5806 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5807 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5808 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5809 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5810 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5813 pieces = FalconArray;
5814 gameInfo.boardWidth = 10;
5815 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5817 case VariantXiangqi:
5818 pieces = XiangqiArray;
5819 gameInfo.boardWidth = 9;
5820 gameInfo.boardHeight = 10;
5821 nrCastlingRights = 0;
5822 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5825 pieces = ShogiArray;
5826 gameInfo.boardWidth = 9;
5827 gameInfo.boardHeight = 9;
5828 gameInfo.holdingsSize = 7;
5829 nrCastlingRights = 0;
5830 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5832 case VariantCourier:
5833 pieces = CourierArray;
5834 gameInfo.boardWidth = 12;
5835 nrCastlingRights = 0;
5836 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5838 case VariantKnightmate:
5839 pieces = KnightmateArray;
5840 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5842 case VariantSpartan:
5843 pieces = SpartanArray;
5844 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5847 pieces = fairyArray;
5848 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5851 pieces = GreatArray;
5852 gameInfo.boardWidth = 10;
5853 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5854 gameInfo.holdingsSize = 8;
5858 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5859 gameInfo.holdingsSize = 8;
5860 startedFromSetupPosition = TRUE;
5862 case VariantCrazyhouse:
5863 case VariantBughouse:
5865 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5866 gameInfo.holdingsSize = 5;
5868 case VariantWildCastle:
5870 /* !!?shuffle with kings guaranteed to be on d or e file */
5871 shuffleOpenings = 1;
5873 case VariantNoCastle:
5875 nrCastlingRights = 0;
5876 /* !!?unconstrained back-rank shuffle */
5877 shuffleOpenings = 1;
5882 if(appData.NrFiles >= 0) {
5883 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5884 gameInfo.boardWidth = appData.NrFiles;
5886 if(appData.NrRanks >= 0) {
5887 gameInfo.boardHeight = appData.NrRanks;
5889 if(appData.holdingsSize >= 0) {
5890 i = appData.holdingsSize;
5891 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5892 gameInfo.holdingsSize = i;
5894 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5895 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5896 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5898 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5899 if(pawnRow < 1) pawnRow = 1;
5900 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) pawnRow = 2;
5902 /* User pieceToChar list overrules defaults */
5903 if(appData.pieceToCharTable != NULL)
5904 SetCharTable(pieceToChar, appData.pieceToCharTable);
5906 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5908 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5909 s = (ChessSquare) 0; /* account holding counts in guard band */
5910 for( i=0; i<BOARD_HEIGHT; i++ )
5911 initialPosition[i][j] = s;
5913 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5914 initialPosition[gameInfo.variant == VariantGrand][j] = pieces[0][j-gameInfo.holdingsWidth];
5915 initialPosition[pawnRow][j] = WhitePawn;
5916 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5917 if(gameInfo.variant == VariantXiangqi) {
5919 initialPosition[pawnRow][j] =
5920 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5921 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5922 initialPosition[2][j] = WhiteCannon;
5923 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5927 if(gameInfo.variant == VariantGrand) {
5928 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
5929 initialPosition[0][j] = WhiteRook;
5930 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
5933 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand)][j] = pieces[1][j-gameInfo.holdingsWidth];
5935 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5938 initialPosition[1][j] = WhiteBishop;
5939 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5941 initialPosition[1][j] = WhiteRook;
5942 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5945 if( nrCastlingRights == -1) {
5946 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5947 /* This sets default castling rights from none to normal corners */
5948 /* Variants with other castling rights must set them themselves above */
5949 nrCastlingRights = 6;
5951 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5952 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5953 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5954 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5955 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5956 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5959 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5960 if(gameInfo.variant == VariantGreat) { // promotion commoners
5961 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5962 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5963 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5964 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5966 if( gameInfo.variant == VariantSChess ) {
5967 initialPosition[1][0] = BlackMarshall;
5968 initialPosition[2][0] = BlackAngel;
5969 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5970 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5971 initialPosition[1][1] = initialPosition[2][1] =
5972 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5974 if (appData.debugMode) {
5975 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5977 if(shuffleOpenings) {
5978 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5979 startedFromSetupPosition = TRUE;
5981 if(startedFromPositionFile) {
5982 /* [HGM] loadPos: use PositionFile for every new game */
5983 CopyBoard(initialPosition, filePosition);
5984 for(i=0; i<nrCastlingRights; i++)
5985 initialRights[i] = filePosition[CASTLING][i];
5986 startedFromSetupPosition = TRUE;
5989 CopyBoard(boards[0], initialPosition);
5991 if(oldx != gameInfo.boardWidth ||
5992 oldy != gameInfo.boardHeight ||
5993 oldv != gameInfo.variant ||
5994 oldh != gameInfo.holdingsWidth
5996 InitDrawingSizes(-2 ,0);
5998 oldv = gameInfo.variant;
6000 DrawPosition(TRUE, boards[currentMove]);
6004 SendBoard(cps, moveNum)
6005 ChessProgramState *cps;
6008 char message[MSG_SIZ];
6010 if (cps->useSetboard) {
6011 char* fen = PositionToFEN(moveNum, cps->fenOverride);
6012 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6013 SendToProgram(message, cps);
6019 /* Kludge to set black to move, avoiding the troublesome and now
6020 * deprecated "black" command.
6022 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6023 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6025 SendToProgram("edit\n", cps);
6026 SendToProgram("#\n", cps);
6027 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6028 bp = &boards[moveNum][i][BOARD_LEFT];
6029 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
6030 if ((int) *bp < (int) BlackPawn) {
6031 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
6033 if(message[0] == '+' || message[0] == '~') {
6034 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6035 PieceToChar((ChessSquare)(DEMOTED *bp)),
6038 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6039 message[1] = BOARD_RGHT - 1 - j + '1';
6040 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6042 SendToProgram(message, cps);
6047 SendToProgram("c\n", cps);
6048 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6049 bp = &boards[moveNum][i][BOARD_LEFT];
6050 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
6051 if (((int) *bp != (int) EmptySquare)
6052 && ((int) *bp >= (int) BlackPawn)) {
6053 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6055 if(message[0] == '+' || message[0] == '~') {
6056 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6057 PieceToChar((ChessSquare)(DEMOTED *bp)),
6060 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6061 message[1] = BOARD_RGHT - 1 - j + '1';
6062 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6064 SendToProgram(message, cps);
6069 SendToProgram(".\n", cps);
6071 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6075 DefaultPromoChoice(int white)
6078 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
6079 result = WhiteFerz; // no choice
6080 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6081 result= WhiteKing; // in Suicide Q is the last thing we want
6082 else if(gameInfo.variant == VariantSpartan)
6083 result = white ? WhiteQueen : WhiteAngel;
6084 else result = WhiteQueen;
6085 if(!white) result = WHITE_TO_BLACK result;
6089 static int autoQueen; // [HGM] oneclick
6092 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6094 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6095 /* [HGM] add Shogi promotions */
6096 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6101 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6102 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6104 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6105 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6108 piece = boards[currentMove][fromY][fromX];
6109 if(gameInfo.variant == VariantShogi) {
6110 promotionZoneSize = BOARD_HEIGHT/3;
6111 highestPromotingPiece = (int)WhiteFerz;
6112 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) {
6113 promotionZoneSize = 3;
6116 // Treat Lance as Pawn when it is not representing Amazon
6117 if(gameInfo.variant != VariantSuper) {
6118 if(piece == WhiteLance) piece = WhitePawn; else
6119 if(piece == BlackLance) piece = BlackPawn;
6122 // next weed out all moves that do not touch the promotion zone at all
6123 if((int)piece >= BlackPawn) {
6124 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6126 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6128 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6129 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6132 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6134 // weed out mandatory Shogi promotions
6135 if(gameInfo.variant == VariantShogi) {
6136 if(piece >= BlackPawn) {
6137 if(toY == 0 && piece == BlackPawn ||
6138 toY == 0 && piece == BlackQueen ||
6139 toY <= 1 && piece == BlackKnight) {
6144 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6145 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6146 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6153 // weed out obviously illegal Pawn moves
6154 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6155 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6156 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6157 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6158 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6159 // note we are not allowed to test for valid (non-)capture, due to premove
6162 // we either have a choice what to promote to, or (in Shogi) whether to promote
6163 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
6164 *promoChoice = PieceToChar(BlackFerz); // no choice
6167 // no sense asking what we must promote to if it is going to explode...
6168 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6169 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6172 // give caller the default choice even if we will not make it
6173 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6174 if(gameInfo.variant == VariantShogi) *promoChoice = (defaultPromoChoice == piece ? '=' : '+');
6175 if( sweepSelect && gameInfo.variant != VariantGreat
6176 && gameInfo.variant != VariantGrand
6177 && gameInfo.variant != VariantSuper) return FALSE;
6178 if(autoQueen) return FALSE; // predetermined
6180 // suppress promotion popup on illegal moves that are not premoves
6181 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6182 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6183 if(appData.testLegality && !premove) {
6184 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6185 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
6186 if(moveType != WhitePromotion && moveType != BlackPromotion)
6194 InPalace(row, column)
6196 { /* [HGM] for Xiangqi */
6197 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6198 column < (BOARD_WIDTH + 4)/2 &&
6199 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6204 PieceForSquare (x, y)
6208 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6211 return boards[currentMove][y][x];
6215 OKToStartUserMove(x, y)
6218 ChessSquare from_piece;
6221 if (matchMode) return FALSE;
6222 if (gameMode == EditPosition) return TRUE;
6224 if (x >= 0 && y >= 0)
6225 from_piece = boards[currentMove][y][x];
6227 from_piece = EmptySquare;
6229 if (from_piece == EmptySquare) return FALSE;
6231 white_piece = (int)from_piece >= (int)WhitePawn &&
6232 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6236 case TwoMachinesPlay:
6244 case MachinePlaysWhite:
6245 case IcsPlayingBlack:
6246 if (appData.zippyPlay) return FALSE;
6248 DisplayMoveError(_("You are playing Black"));
6253 case MachinePlaysBlack:
6254 case IcsPlayingWhite:
6255 if (appData.zippyPlay) return FALSE;
6257 DisplayMoveError(_("You are playing White"));
6262 case PlayFromGameFile:
6263 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6265 if (!white_piece && WhiteOnMove(currentMove)) {
6266 DisplayMoveError(_("It is White's turn"));
6269 if (white_piece && !WhiteOnMove(currentMove)) {
6270 DisplayMoveError(_("It is Black's turn"));
6273 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6274 /* Editing correspondence game history */
6275 /* Could disallow this or prompt for confirmation */
6280 case BeginningOfGame:
6281 if (appData.icsActive) return FALSE;
6282 if (!appData.noChessProgram) {
6284 DisplayMoveError(_("You are playing White"));
6291 if (!white_piece && WhiteOnMove(currentMove)) {
6292 DisplayMoveError(_("It is White's turn"));
6295 if (white_piece && !WhiteOnMove(currentMove)) {
6296 DisplayMoveError(_("It is Black's turn"));
6305 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6306 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6307 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6308 && gameMode != AnalyzeFile && gameMode != Training) {
6309 DisplayMoveError(_("Displayed position is not current"));
6316 OnlyMove(int *x, int *y, Boolean captures) {
6317 DisambiguateClosure cl;
6318 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6320 case MachinePlaysBlack:
6321 case IcsPlayingWhite:
6322 case BeginningOfGame:
6323 if(!WhiteOnMove(currentMove)) return FALSE;
6325 case MachinePlaysWhite:
6326 case IcsPlayingBlack:
6327 if(WhiteOnMove(currentMove)) return FALSE;
6334 cl.pieceIn = EmptySquare;
6339 cl.promoCharIn = NULLCHAR;
6340 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6341 if( cl.kind == NormalMove ||
6342 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6343 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6344 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6351 if(cl.kind != ImpossibleMove) return FALSE;
6352 cl.pieceIn = EmptySquare;
6357 cl.promoCharIn = NULLCHAR;
6358 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6359 if( cl.kind == NormalMove ||
6360 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6361 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6362 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6367 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6373 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6374 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6375 int lastLoadGameUseList = FALSE;
6376 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6377 ChessMove lastLoadGameStart = EndOfFile;
6380 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6381 int fromX, fromY, toX, toY;
6385 ChessSquare pdown, pup;
6387 /* Check if the user is playing in turn. This is complicated because we
6388 let the user "pick up" a piece before it is his turn. So the piece he
6389 tried to pick up may have been captured by the time he puts it down!
6390 Therefore we use the color the user is supposed to be playing in this
6391 test, not the color of the piece that is currently on the starting
6392 square---except in EditGame mode, where the user is playing both
6393 sides; fortunately there the capture race can't happen. (It can
6394 now happen in IcsExamining mode, but that's just too bad. The user
6395 will get a somewhat confusing message in that case.)
6400 case TwoMachinesPlay:
6404 /* We switched into a game mode where moves are not accepted,
6405 perhaps while the mouse button was down. */
6408 case MachinePlaysWhite:
6409 /* User is moving for Black */
6410 if (WhiteOnMove(currentMove)) {
6411 DisplayMoveError(_("It is White's turn"));
6416 case MachinePlaysBlack:
6417 /* User is moving for White */
6418 if (!WhiteOnMove(currentMove)) {
6419 DisplayMoveError(_("It is Black's turn"));
6424 case PlayFromGameFile:
6425 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6428 case BeginningOfGame:
6431 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6432 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6433 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6434 /* User is moving for Black */
6435 if (WhiteOnMove(currentMove)) {
6436 DisplayMoveError(_("It is White's turn"));
6440 /* User is moving for White */
6441 if (!WhiteOnMove(currentMove)) {
6442 DisplayMoveError(_("It is Black's turn"));
6448 case IcsPlayingBlack:
6449 /* User is moving for Black */
6450 if (WhiteOnMove(currentMove)) {
6451 if (!appData.premove) {
6452 DisplayMoveError(_("It is White's turn"));
6453 } else if (toX >= 0 && toY >= 0) {
6456 premoveFromX = fromX;
6457 premoveFromY = fromY;
6458 premovePromoChar = promoChar;
6460 if (appData.debugMode)
6461 fprintf(debugFP, "Got premove: fromX %d,"
6462 "fromY %d, toX %d, toY %d\n",
6463 fromX, fromY, toX, toY);
6469 case IcsPlayingWhite:
6470 /* User is moving for White */
6471 if (!WhiteOnMove(currentMove)) {
6472 if (!appData.premove) {
6473 DisplayMoveError(_("It is Black's turn"));
6474 } else if (toX >= 0 && toY >= 0) {
6477 premoveFromX = fromX;
6478 premoveFromY = fromY;
6479 premovePromoChar = promoChar;
6481 if (appData.debugMode)
6482 fprintf(debugFP, "Got premove: fromX %d,"
6483 "fromY %d, toX %d, toY %d\n",
6484 fromX, fromY, toX, toY);
6494 /* EditPosition, empty square, or different color piece;
6495 click-click move is possible */
6496 if (toX == -2 || toY == -2) {
6497 boards[0][fromY][fromX] = EmptySquare;
6498 DrawPosition(FALSE, boards[currentMove]);
6500 } else if (toX >= 0 && toY >= 0) {
6501 boards[0][toY][toX] = boards[0][fromY][fromX];
6502 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6503 if(boards[0][fromY][0] != EmptySquare) {
6504 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6505 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6508 if(fromX == BOARD_RGHT+1) {
6509 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6510 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6511 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6514 boards[0][fromY][fromX] = EmptySquare;
6515 DrawPosition(FALSE, boards[currentMove]);
6521 if(toX < 0 || toY < 0) return;
6522 pdown = boards[currentMove][fromY][fromX];
6523 pup = boards[currentMove][toY][toX];
6525 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6526 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6527 if( pup != EmptySquare ) return;
6528 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6529 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6530 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6531 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6532 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6533 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6534 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6538 /* [HGM] always test for legality, to get promotion info */
6539 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6540 fromY, fromX, toY, toX, promoChar);
6542 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame)) moveType = NormalMove;
6544 /* [HGM] but possibly ignore an IllegalMove result */
6545 if (appData.testLegality) {
6546 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6547 DisplayMoveError(_("Illegal move"));
6552 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6555 /* Common tail of UserMoveEvent and DropMenuEvent */
6557 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6559 int fromX, fromY, toX, toY;
6560 /*char*/int promoChar;
6564 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
6565 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
6566 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6567 if(WhiteOnMove(currentMove)) {
6568 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6570 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6574 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6575 move type in caller when we know the move is a legal promotion */
6576 if(moveType == NormalMove && promoChar)
6577 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6579 /* [HGM] <popupFix> The following if has been moved here from
6580 UserMoveEvent(). Because it seemed to belong here (why not allow
6581 piece drops in training games?), and because it can only be
6582 performed after it is known to what we promote. */
6583 if (gameMode == Training) {
6584 /* compare the move played on the board to the next move in the
6585 * game. If they match, display the move and the opponent's response.
6586 * If they don't match, display an error message.
6590 CopyBoard(testBoard, boards[currentMove]);
6591 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6593 if (CompareBoards(testBoard, boards[currentMove+1])) {
6594 ForwardInner(currentMove+1);
6596 /* Autoplay the opponent's response.
6597 * if appData.animate was TRUE when Training mode was entered,
6598 * the response will be animated.
6600 saveAnimate = appData.animate;
6601 appData.animate = animateTraining;
6602 ForwardInner(currentMove+1);
6603 appData.animate = saveAnimate;
6605 /* check for the end of the game */
6606 if (currentMove >= forwardMostMove) {
6607 gameMode = PlayFromGameFile;
6609 SetTrainingModeOff();
6610 DisplayInformation(_("End of game"));
6613 DisplayError(_("Incorrect move"), 0);
6618 /* Ok, now we know that the move is good, so we can kill
6619 the previous line in Analysis Mode */
6620 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
6621 && currentMove < forwardMostMove) {
6622 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6623 else forwardMostMove = currentMove;
6626 /* If we need the chess program but it's dead, restart it */
6627 ResurrectChessProgram();
6629 /* A user move restarts a paused game*/
6633 thinkOutput[0] = NULLCHAR;
6635 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6637 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6638 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6642 if (gameMode == BeginningOfGame) {
6643 if (appData.noChessProgram) {
6644 gameMode = EditGame;
6648 gameMode = MachinePlaysBlack;
6651 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6653 if (first.sendName) {
6654 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6655 SendToProgram(buf, &first);
6662 /* Relay move to ICS or chess engine */
6663 if (appData.icsActive) {
6664 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6665 gameMode == IcsExamining) {
6666 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6667 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6669 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6671 // also send plain move, in case ICS does not understand atomic claims
6672 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6676 if (first.sendTime && (gameMode == BeginningOfGame ||
6677 gameMode == MachinePlaysWhite ||
6678 gameMode == MachinePlaysBlack)) {
6679 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6681 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6682 // [HGM] book: if program might be playing, let it use book
6683 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6684 first.maybeThinking = TRUE;
6685 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
6686 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
6687 SendBoard(&first, currentMove+1);
6688 } else SendMoveToProgram(forwardMostMove-1, &first);
6689 if (currentMove == cmailOldMove + 1) {
6690 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6694 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6698 if(appData.testLegality)
6699 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6705 if (WhiteOnMove(currentMove)) {
6706 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6708 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6712 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6717 case MachinePlaysBlack:
6718 case MachinePlaysWhite:
6719 /* disable certain menu options while machine is thinking */
6720 SetMachineThinkingEnables();
6727 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6728 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6730 if(bookHit) { // [HGM] book: simulate book reply
6731 static char bookMove[MSG_SIZ]; // a bit generous?
6733 programStats.nodes = programStats.depth = programStats.time =
6734 programStats.score = programStats.got_only_move = 0;
6735 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6737 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6738 strcat(bookMove, bookHit);
6739 HandleMachineMove(bookMove, &first);
6745 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6752 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6753 Markers *m = (Markers *) closure;
6754 if(rf == fromY && ff == fromX)
6755 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6756 || kind == WhiteCapturesEnPassant
6757 || kind == BlackCapturesEnPassant);
6758 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6762 MarkTargetSquares(int clear)
6765 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
6766 !appData.testLegality || gameMode == EditPosition) return;
6768 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6771 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
6772 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6773 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6775 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6778 DrawPosition(TRUE, NULL);
6782 Explode(Board board, int fromX, int fromY, int toX, int toY)
6784 if(gameInfo.variant == VariantAtomic &&
6785 (board[toY][toX] != EmptySquare || // capture?
6786 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6787 board[fromY][fromX] == BlackPawn )
6789 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6795 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6797 int CanPromote(ChessSquare piece, int y)
6799 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6800 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6801 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6802 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6803 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6804 gameInfo.variant == VariantMakruk) return FALSE;
6805 return (piece == BlackPawn && y == 1 ||
6806 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6807 piece == BlackLance && y == 1 ||
6808 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6811 void LeftClick(ClickType clickType, int xPix, int yPix)
6814 Boolean saveAnimate;
6815 static int second = 0, promotionChoice = 0, clearFlag = 0;
6816 char promoChoice = NULLCHAR;
6819 if(appData.seekGraph && appData.icsActive && loggedOn &&
6820 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6821 SeekGraphClick(clickType, xPix, yPix, 0);
6825 if (clickType == Press) ErrorPopDown();
6827 x = EventToSquare(xPix, BOARD_WIDTH);
6828 y = EventToSquare(yPix, BOARD_HEIGHT);
6829 if (!flipView && y >= 0) {
6830 y = BOARD_HEIGHT - 1 - y;
6832 if (flipView && x >= 0) {
6833 x = BOARD_WIDTH - 1 - x;
6836 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6837 defaultPromoChoice = promoSweep;
6838 promoSweep = EmptySquare; // terminate sweep
6839 promoDefaultAltered = TRUE;
6840 if(!selectFlag && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6843 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6844 if(clickType == Release) return; // ignore upclick of click-click destination
6845 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6846 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6847 if(gameInfo.holdingsWidth &&
6848 (WhiteOnMove(currentMove)
6849 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
6850 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
6851 // click in right holdings, for determining promotion piece
6852 ChessSquare p = boards[currentMove][y][x];
6853 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6854 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
6855 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
6856 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
6861 DrawPosition(FALSE, boards[currentMove]);
6865 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6866 if(clickType == Press
6867 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6868 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6869 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6872 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6873 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6875 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6876 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6877 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6878 defaultPromoChoice = DefaultPromoChoice(side);
6881 autoQueen = appData.alwaysPromoteToQueen;
6885 gatingPiece = EmptySquare;
6886 if (clickType != Press) {
6887 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6888 DragPieceEnd(xPix, yPix); dragging = 0;
6889 DrawPosition(FALSE, NULL);
6893 fromX = x; fromY = y; toX = toY = -1;
6894 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6895 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6896 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6898 if (OKToStartUserMove(fromX, fromY)) {
6900 MarkTargetSquares(0);
6901 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
6902 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6903 promoSweep = defaultPromoChoice;
6904 selectFlag = 0; lastX = xPix; lastY = yPix;
6905 Sweep(0); // Pawn that is going to promote: preview promotion piece
6906 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6908 if (appData.highlightDragging) {
6909 SetHighlights(fromX, fromY, -1, -1);
6911 } else fromX = fromY = -1;
6917 if (clickType == Press && gameMode != EditPosition) {
6922 // ignore off-board to clicks
6923 if(y < 0 || x < 0) return;
6925 /* Check if clicking again on the same color piece */
6926 fromP = boards[currentMove][fromY][fromX];
6927 toP = boards[currentMove][y][x];
6928 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6929 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6930 WhitePawn <= toP && toP <= WhiteKing &&
6931 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6932 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6933 (BlackPawn <= fromP && fromP <= BlackKing &&
6934 BlackPawn <= toP && toP <= BlackKing &&
6935 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6936 !(fromP == BlackKing && toP == BlackRook && frc))) {
6937 /* Clicked again on same color piece -- changed his mind */
6938 second = (x == fromX && y == fromY);
6939 promoDefaultAltered = FALSE;
6940 MarkTargetSquares(1);
6941 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6942 if (appData.highlightDragging) {
6943 SetHighlights(x, y, -1, -1);
6947 if (OKToStartUserMove(x, y)) {
6948 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6949 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6950 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6951 gatingPiece = boards[currentMove][fromY][fromX];
6952 else gatingPiece = EmptySquare;
6954 fromY = y; dragging = 1;
6955 MarkTargetSquares(0);
6956 DragPieceBegin(xPix, yPix, FALSE);
6957 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6958 promoSweep = defaultPromoChoice;
6959 selectFlag = 0; lastX = xPix; lastY = yPix;
6960 Sweep(0); // Pawn that is going to promote: preview promotion piece
6964 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6967 // ignore clicks on holdings
6968 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6971 if (clickType == Release && x == fromX && y == fromY) {
6972 DragPieceEnd(xPix, yPix); dragging = 0;
6974 // a deferred attempt to click-click move an empty square on top of a piece
6975 boards[currentMove][y][x] = EmptySquare;
6977 DrawPosition(FALSE, boards[currentMove]);
6978 fromX = fromY = -1; clearFlag = 0;
6981 if (appData.animateDragging) {
6982 /* Undo animation damage if any */
6983 DrawPosition(FALSE, NULL);
6986 /* Second up/down in same square; just abort move */
6989 gatingPiece = EmptySquare;
6992 ClearPremoveHighlights();
6994 /* First upclick in same square; start click-click mode */
6995 SetHighlights(x, y, -1, -1);
7002 /* we now have a different from- and (possibly off-board) to-square */
7003 /* Completed move */
7006 saveAnimate = appData.animate;
7007 MarkTargetSquares(1);
7008 if (clickType == Press) {
7009 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7010 // must be Edit Position mode with empty-square selected
7011 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7012 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7015 if(appData.sweepSelect && HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7016 ChessSquare piece = boards[currentMove][fromY][fromX];
7017 DragPieceBegin(xPix, yPix, TRUE); dragging = 1;
7018 promoSweep = defaultPromoChoice;
7019 if(PieceToChar(PROMOTED piece) == '+') promoSweep = PROMOTED piece;
7020 selectFlag = 0; lastX = xPix; lastY = yPix;
7021 Sweep(0); // Pawn that is going to promote: preview promotion piece
7022 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7023 DrawPosition(FALSE, boards[currentMove]);
7026 /* Finish clickclick move */
7027 if (appData.animate || appData.highlightLastMove) {
7028 SetHighlights(fromX, fromY, toX, toY);
7033 /* Finish drag move */
7034 if (appData.highlightLastMove) {
7035 SetHighlights(fromX, fromY, toX, toY);
7039 DragPieceEnd(xPix, yPix); dragging = 0;
7040 /* Don't animate move and drag both */
7041 appData.animate = FALSE;
7044 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7045 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7046 ChessSquare piece = boards[currentMove][fromY][fromX];
7047 if(gameMode == EditPosition && piece != EmptySquare &&
7048 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7051 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7052 n = PieceToNumber(piece - (int)BlackPawn);
7053 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7054 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7055 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7057 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7058 n = PieceToNumber(piece);
7059 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7060 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7061 boards[currentMove][n][BOARD_WIDTH-2]++;
7063 boards[currentMove][fromY][fromX] = EmptySquare;
7067 DrawPosition(TRUE, boards[currentMove]);
7071 // off-board moves should not be highlighted
7072 if(x < 0 || y < 0) ClearHighlights();
7074 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
7076 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7077 SetHighlights(fromX, fromY, toX, toY);
7078 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7079 // [HGM] super: promotion to captured piece selected from holdings
7080 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7081 promotionChoice = TRUE;
7082 // kludge follows to temporarily execute move on display, without promoting yet
7083 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7084 boards[currentMove][toY][toX] = p;
7085 DrawPosition(FALSE, boards[currentMove]);
7086 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7087 boards[currentMove][toY][toX] = q;
7088 DisplayMessage("Click in holdings to choose piece", "");
7093 int oldMove = currentMove;
7094 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7095 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7096 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7097 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7098 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7099 DrawPosition(TRUE, boards[currentMove]);
7102 appData.animate = saveAnimate;
7103 if (appData.animate || appData.animateDragging) {
7104 /* Undo animation damage if needed */
7105 DrawPosition(FALSE, NULL);
7109 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
7110 { // front-end-free part taken out of PieceMenuPopup
7111 int whichMenu; int xSqr, ySqr;
7113 if(seekGraphUp) { // [HGM] seekgraph
7114 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7115 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7119 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7120 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7121 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7122 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7123 if(action == Press) {
7124 originalFlip = flipView;
7125 flipView = !flipView; // temporarily flip board to see game from partners perspective
7126 DrawPosition(TRUE, partnerBoard);
7127 DisplayMessage(partnerStatus, "");
7129 } else if(action == Release) {
7130 flipView = originalFlip;
7131 DrawPosition(TRUE, boards[currentMove]);
7137 xSqr = EventToSquare(x, BOARD_WIDTH);
7138 ySqr = EventToSquare(y, BOARD_HEIGHT);
7139 if (action == Release) {
7140 if(pieceSweep != EmptySquare) {
7141 EditPositionMenuEvent(pieceSweep, toX, toY);
7142 pieceSweep = EmptySquare;
7143 } else UnLoadPV(); // [HGM] pv
7145 if (action != Press) return -2; // return code to be ignored
7148 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7150 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7151 if (xSqr < 0 || ySqr < 0) return -1;
7152 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7153 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7154 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7155 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7159 if(!appData.icsEngineAnalyze) return -1;
7160 case IcsPlayingWhite:
7161 case IcsPlayingBlack:
7162 if(!appData.zippyPlay) goto noZip;
7165 case MachinePlaysWhite:
7166 case MachinePlaysBlack:
7167 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7168 if (!appData.dropMenu) {
7170 return 2; // flag front-end to grab mouse events
7172 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7173 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7176 if (xSqr < 0 || ySqr < 0) return -1;
7177 if (!appData.dropMenu || appData.testLegality &&
7178 gameInfo.variant != VariantBughouse &&
7179 gameInfo.variant != VariantCrazyhouse) return -1;
7180 whichMenu = 1; // drop menu
7186 if (((*fromX = xSqr) < 0) ||
7187 ((*fromY = ySqr) < 0)) {
7188 *fromX = *fromY = -1;
7192 *fromX = BOARD_WIDTH - 1 - *fromX;
7194 *fromY = BOARD_HEIGHT - 1 - *fromY;
7199 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
7201 // char * hint = lastHint;
7202 FrontEndProgramStats stats;
7204 stats.which = cps == &first ? 0 : 1;
7205 stats.depth = cpstats->depth;
7206 stats.nodes = cpstats->nodes;
7207 stats.score = cpstats->score;
7208 stats.time = cpstats->time;
7209 stats.pv = cpstats->movelist;
7210 stats.hint = lastHint;
7211 stats.an_move_index = 0;
7212 stats.an_move_count = 0;
7214 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7215 stats.hint = cpstats->move_name;
7216 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7217 stats.an_move_count = cpstats->nr_moves;
7220 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
7222 SetProgramStats( &stats );
7226 ClearEngineOutputPane(int which)
7228 static FrontEndProgramStats dummyStats;
7229 dummyStats.which = which;
7230 dummyStats.pv = "#";
7231 SetProgramStats( &dummyStats );
7234 #define MAXPLAYERS 500
7237 TourneyStandings(int display)
7239 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7240 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7241 char result, *p, *names[MAXPLAYERS];
7243 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7244 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7245 names[0] = p = strdup(appData.participants);
7246 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7248 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7250 while(result = appData.results[nr]) {
7251 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7252 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7253 wScore = bScore = 0;
7255 case '+': wScore = 2; break;
7256 case '-': bScore = 2; break;
7257 case '=': wScore = bScore = 1; break;
7259 case '*': return strdup("busy"); // tourney not finished
7267 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7268 for(w=0; w<nPlayers; w++) {
7270 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7271 ranking[w] = b; points[w] = bScore; score[b] = -2;
7273 p = malloc(nPlayers*34+1);
7274 for(w=0; w<nPlayers && w<display; w++)
7275 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7281 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7282 { // count all piece types
7284 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7285 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7286 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7289 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7290 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7291 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7292 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7293 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7294 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7299 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
7301 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7302 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7304 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7305 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7306 if(myPawns == 2 && nMine == 3) // KPP
7307 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7308 if(myPawns == 1 && nMine == 2) // KP
7309 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7310 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7311 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7312 if(myPawns) return FALSE;
7313 if(pCnt[WhiteRook+side])
7314 return pCnt[BlackRook-side] ||
7315 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7316 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7317 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7318 if(pCnt[WhiteCannon+side]) {
7319 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7320 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7322 if(pCnt[WhiteKnight+side])
7323 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7328 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7330 VariantClass v = gameInfo.variant;
7332 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7333 if(v == VariantShatranj) return TRUE; // always winnable through baring
7334 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7335 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7337 if(v == VariantXiangqi) {
7338 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7340 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7341 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7342 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7343 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7344 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7345 if(stale) // we have at least one last-rank P plus perhaps C
7346 return majors // KPKX
7347 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7349 return pCnt[WhiteFerz+side] // KCAK
7350 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7351 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7352 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7354 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7355 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7357 if(nMine == 1) return FALSE; // bare King
7358 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
7359 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7360 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7361 // by now we have King + 1 piece (or multiple Bishops on the same color)
7362 if(pCnt[WhiteKnight+side])
7363 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7364 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7365 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7367 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7368 if(pCnt[WhiteAlfil+side])
7369 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7370 if(pCnt[WhiteWazir+side])
7371 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7378 CompareWithRights(Board b1, Board b2)
7381 if(!CompareBoards(b1, b2)) return FALSE;
7382 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
7383 /* compare castling rights */
7384 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
7385 rights++; /* King lost rights, while rook still had them */
7386 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
7387 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
7388 rights++; /* but at least one rook lost them */
7390 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
7392 if( b1[CASTLING][5] != NoRights ) {
7393 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
7400 Adjudicate(ChessProgramState *cps)
7401 { // [HGM] some adjudications useful with buggy engines
7402 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7403 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7404 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7405 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7406 int k, count = 0; static int bare = 1;
7407 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7408 Boolean canAdjudicate = !appData.icsActive;
7410 // most tests only when we understand the game, i.e. legality-checking on
7411 if( appData.testLegality )
7412 { /* [HGM] Some more adjudications for obstinate engines */
7413 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7414 static int moveCount = 6;
7416 char *reason = NULL;
7418 /* Count what is on board. */
7419 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7421 /* Some material-based adjudications that have to be made before stalemate test */
7422 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7423 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7424 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7425 if(canAdjudicate && appData.checkMates) {
7427 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7428 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7429 "Xboard adjudication: King destroyed", GE_XBOARD );
7434 /* Bare King in Shatranj (loses) or Losers (wins) */
7435 if( nrW == 1 || nrB == 1) {
7436 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7437 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7438 if(canAdjudicate && appData.checkMates) {
7440 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7441 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7442 "Xboard adjudication: Bare king", GE_XBOARD );
7446 if( gameInfo.variant == VariantShatranj && --bare < 0)
7448 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7449 if(canAdjudicate && appData.checkMates) {
7450 /* but only adjudicate if adjudication enabled */
7452 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7453 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7454 "Xboard adjudication: Bare king", GE_XBOARD );
7461 // don't wait for engine to announce game end if we can judge ourselves
7462 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7464 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7465 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7466 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7467 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7470 reason = "Xboard adjudication: 3rd check";
7471 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7481 reason = "Xboard adjudication: Stalemate";
7482 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7483 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7484 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7485 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7486 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7487 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7488 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7489 EP_CHECKMATE : EP_WINS);
7490 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7491 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7495 reason = "Xboard adjudication: Checkmate";
7496 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7500 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7502 result = GameIsDrawn; break;
7504 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7506 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7510 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7512 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7513 GameEnds( result, reason, GE_XBOARD );
7517 /* Next absolutely insufficient mating material. */
7518 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7519 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7520 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7522 /* always flag draws, for judging claims */
7523 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7525 if(canAdjudicate && appData.materialDraws) {
7526 /* but only adjudicate them if adjudication enabled */
7527 if(engineOpponent) {
7528 SendToProgram("force\n", engineOpponent); // suppress reply
7529 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7531 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7536 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7537 if(gameInfo.variant == VariantXiangqi ?
7538 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7540 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7541 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7542 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7543 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7545 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7546 { /* if the first 3 moves do not show a tactical win, declare draw */
7547 if(engineOpponent) {
7548 SendToProgram("force\n", engineOpponent); // suppress reply
7549 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7551 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7554 } else moveCount = 6;
7556 if (appData.debugMode) { int i;
7557 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
7558 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
7559 appData.drawRepeats);
7560 for( i=forwardMostMove; i>=backwardMostMove; i-- )
7561 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
7565 // Repetition draws and 50-move rule can be applied independently of legality testing
7567 /* Check for rep-draws */
7569 for(k = forwardMostMove-2;
7570 k>=backwardMostMove && k>=forwardMostMove-100 &&
7571 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7572 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7575 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7576 /* compare castling rights */
7577 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7578 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7579 rights++; /* King lost rights, while rook still had them */
7580 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7581 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7582 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7583 rights++; /* but at least one rook lost them */
7585 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7586 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7588 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7589 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7590 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7593 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7594 && appData.drawRepeats > 1) {
7595 /* adjudicate after user-specified nr of repeats */
7596 int result = GameIsDrawn;
7597 char *details = "XBoard adjudication: repetition draw";
7598 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7599 // [HGM] xiangqi: check for forbidden perpetuals
7600 int m, ourPerpetual = 1, hisPerpetual = 1;
7601 for(m=forwardMostMove; m>k; m-=2) {
7602 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7603 ourPerpetual = 0; // the current mover did not always check
7604 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7605 hisPerpetual = 0; // the opponent did not always check
7607 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7608 ourPerpetual, hisPerpetual);
7609 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7610 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7611 details = "Xboard adjudication: perpetual checking";
7613 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7614 break; // (or we would have caught him before). Abort repetition-checking loop.
7616 // Now check for perpetual chases
7617 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7618 hisPerpetual = PerpetualChase(k, forwardMostMove);
7619 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7620 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7621 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7622 details = "Xboard adjudication: perpetual chasing";
7624 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7625 break; // Abort repetition-checking loop.
7627 // if neither of us is checking or chasing all the time, or both are, it is draw
7629 if(engineOpponent) {
7630 SendToProgram("force\n", engineOpponent); // suppress reply
7631 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7633 GameEnds( result, details, GE_XBOARD );
7636 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7637 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7641 /* Now we test for 50-move draws. Determine ply count */
7642 count = forwardMostMove;
7643 /* look for last irreversble move */
7644 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7646 /* if we hit starting position, add initial plies */
7647 if( count == backwardMostMove )
7648 count -= initialRulePlies;
7649 count = forwardMostMove - count;
7650 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7651 // adjust reversible move counter for checks in Xiangqi
7652 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7653 if(i < backwardMostMove) i = backwardMostMove;
7654 while(i <= forwardMostMove) {
7655 lastCheck = inCheck; // check evasion does not count
7656 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7657 if(inCheck || lastCheck) count--; // check does not count
7662 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7663 /* this is used to judge if draw claims are legal */
7664 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7665 if(engineOpponent) {
7666 SendToProgram("force\n", engineOpponent); // suppress reply
7667 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7669 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7673 /* if draw offer is pending, treat it as a draw claim
7674 * when draw condition present, to allow engines a way to
7675 * claim draws before making their move to avoid a race
7676 * condition occurring after their move
7678 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7680 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7681 p = "Draw claim: 50-move rule";
7682 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7683 p = "Draw claim: 3-fold repetition";
7684 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7685 p = "Draw claim: insufficient mating material";
7686 if( p != NULL && canAdjudicate) {
7687 if(engineOpponent) {
7688 SendToProgram("force\n", engineOpponent); // suppress reply
7689 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7691 GameEnds( GameIsDrawn, p, GE_XBOARD );
7696 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7697 if(engineOpponent) {
7698 SendToProgram("force\n", engineOpponent); // suppress reply
7699 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7701 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7707 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7708 { // [HGM] book: this routine intercepts moves to simulate book replies
7709 char *bookHit = NULL;
7711 //first determine if the incoming move brings opponent into his book
7712 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7713 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7714 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7715 if(bookHit != NULL && !cps->bookSuspend) {
7716 // make sure opponent is not going to reply after receiving move to book position
7717 SendToProgram("force\n", cps);
7718 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7720 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7721 // now arrange restart after book miss
7723 // after a book hit we never send 'go', and the code after the call to this routine
7724 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7725 char buf[MSG_SIZ], *move = bookHit;
7727 int fromX, fromY, toX, toY;
7731 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
7732 &fromX, &fromY, &toX, &toY, &promoChar)) {
7733 (void) CoordsToAlgebraic(boards[forwardMostMove],
7734 PosFlags(forwardMostMove),
7735 fromY, fromX, toY, toX, promoChar, move);
7737 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
7741 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
7742 SendToProgram(buf, cps);
7743 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7744 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7745 SendToProgram("go\n", cps);
7746 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7747 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7748 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7749 SendToProgram("go\n", cps);
7750 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7752 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7756 ChessProgramState *savedState;
7757 void DeferredBookMove(void)
7759 if(savedState->lastPing != savedState->lastPong)
7760 ScheduleDelayedEvent(DeferredBookMove, 10);
7762 HandleMachineMove(savedMessage, savedState);
7765 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
7768 HandleMachineMove(message, cps)
7770 ChessProgramState *cps;
7772 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7773 char realname[MSG_SIZ];
7774 int fromX, fromY, toX, toY;
7781 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
7782 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
7783 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
7784 DisplayError(_("Invalid pairing from pairing engine"), 0);
7787 pairingReceived = 1;
7789 return; // Skim the pairing messages here.
7794 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7796 * Kludge to ignore BEL characters
7798 while (*message == '\007') message++;
7801 * [HGM] engine debug message: ignore lines starting with '#' character
7803 if(cps->debug && *message == '#') return;
7806 * Look for book output
7808 if (cps == &first && bookRequested) {
7809 if (message[0] == '\t' || message[0] == ' ') {
7810 /* Part of the book output is here; append it */
7811 strcat(bookOutput, message);
7812 strcat(bookOutput, " \n");
7814 } else if (bookOutput[0] != NULLCHAR) {
7815 /* All of book output has arrived; display it */
7816 char *p = bookOutput;
7817 while (*p != NULLCHAR) {
7818 if (*p == '\t') *p = ' ';
7821 DisplayInformation(bookOutput);
7822 bookRequested = FALSE;
7823 /* Fall through to parse the current output */
7828 * Look for machine move.
7830 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7831 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7833 /* This method is only useful on engines that support ping */
7834 if (cps->lastPing != cps->lastPong) {
7835 if (gameMode == BeginningOfGame) {
7836 /* Extra move from before last new; ignore */
7837 if (appData.debugMode) {
7838 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7841 if (appData.debugMode) {
7842 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7843 cps->which, gameMode);
7846 SendToProgram("undo\n", cps);
7852 case BeginningOfGame:
7853 /* Extra move from before last reset; ignore */
7854 if (appData.debugMode) {
7855 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7862 /* Extra move after we tried to stop. The mode test is
7863 not a reliable way of detecting this problem, but it's
7864 the best we can do on engines that don't support ping.
7866 if (appData.debugMode) {
7867 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7868 cps->which, gameMode);
7870 SendToProgram("undo\n", cps);
7873 case MachinePlaysWhite:
7874 case IcsPlayingWhite:
7875 machineWhite = TRUE;
7878 case MachinePlaysBlack:
7879 case IcsPlayingBlack:
7880 machineWhite = FALSE;
7883 case TwoMachinesPlay:
7884 machineWhite = (cps->twoMachinesColor[0] == 'w');
7887 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7888 if (appData.debugMode) {
7890 "Ignoring move out of turn by %s, gameMode %d"
7891 ", forwardMost %d\n",
7892 cps->which, gameMode, forwardMostMove);
7897 if (appData.debugMode) { int f = forwardMostMove;
7898 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7899 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7900 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7902 if(cps->alphaRank) AlphaRank(machineMove, 4);
7903 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7904 &fromX, &fromY, &toX, &toY, &promoChar)) {
7905 /* Machine move could not be parsed; ignore it. */
7906 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7907 machineMove, _(cps->which));
7908 DisplayError(buf1, 0);
7909 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7910 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7911 if (gameMode == TwoMachinesPlay) {
7912 GameEnds(machineWhite ? BlackWins : WhiteWins,
7918 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7919 /* So we have to redo legality test with true e.p. status here, */
7920 /* to make sure an illegal e.p. capture does not slip through, */
7921 /* to cause a forfeit on a justified illegal-move complaint */
7922 /* of the opponent. */
7923 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7925 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7926 fromY, fromX, toY, toX, promoChar);
7927 if (appData.debugMode) {
7929 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7930 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7931 fprintf(debugFP, "castling rights\n");
7933 if(moveType == IllegalMove) {
7934 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7935 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7936 GameEnds(machineWhite ? BlackWins : WhiteWins,
7939 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7940 /* [HGM] Kludge to handle engines that send FRC-style castling
7941 when they shouldn't (like TSCP-Gothic) */
7943 case WhiteASideCastleFR:
7944 case BlackASideCastleFR:
7946 currentMoveString[2]++;
7948 case WhiteHSideCastleFR:
7949 case BlackHSideCastleFR:
7951 currentMoveString[2]--;
7953 default: ; // nothing to do, but suppresses warning of pedantic compilers
7956 hintRequested = FALSE;
7957 lastHint[0] = NULLCHAR;
7958 bookRequested = FALSE;
7959 /* Program may be pondering now */
7960 cps->maybeThinking = TRUE;
7961 if (cps->sendTime == 2) cps->sendTime = 1;
7962 if (cps->offeredDraw) cps->offeredDraw--;
7964 /* [AS] Save move info*/
7965 pvInfoList[ forwardMostMove ].score = programStats.score;
7966 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7967 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7969 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7971 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7972 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7975 while( count < adjudicateLossPlies ) {
7976 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7979 score = -score; /* Flip score for winning side */
7982 if( score > adjudicateLossThreshold ) {
7989 if( count >= adjudicateLossPlies ) {
7990 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7992 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7993 "Xboard adjudication",
8000 if(Adjudicate(cps)) {
8001 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8002 return; // [HGM] adjudicate: for all automatic game ends
8006 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8008 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8009 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8011 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8013 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8015 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8016 char buf[3*MSG_SIZ];
8018 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8019 programStats.score / 100.,
8021 programStats.time / 100.,
8022 (unsigned int)programStats.nodes,
8023 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8024 programStats.movelist);
8026 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
8031 /* [AS] Clear stats for next move */
8032 ClearProgramStats();
8033 thinkOutput[0] = NULLCHAR;
8034 hiddenThinkOutputState = 0;
8037 if (gameMode == TwoMachinesPlay) {
8038 /* [HGM] relaying draw offers moved to after reception of move */
8039 /* and interpreting offer as claim if it brings draw condition */
8040 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8041 SendToProgram("draw\n", cps->other);
8043 if (cps->other->sendTime) {
8044 SendTimeRemaining(cps->other,
8045 cps->other->twoMachinesColor[0] == 'w');
8047 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8048 if (firstMove && !bookHit) {
8050 if (cps->other->useColors) {
8051 SendToProgram(cps->other->twoMachinesColor, cps->other);
8053 SendToProgram("go\n", cps->other);
8055 cps->other->maybeThinking = TRUE;
8058 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8060 if (!pausing && appData.ringBellAfterMoves) {
8065 * Reenable menu items that were disabled while
8066 * machine was thinking
8068 if (gameMode != TwoMachinesPlay)
8069 SetUserThinkingEnables();
8071 // [HGM] book: after book hit opponent has received move and is now in force mode
8072 // force the book reply into it, and then fake that it outputted this move by jumping
8073 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8075 static char bookMove[MSG_SIZ]; // a bit generous?
8077 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8078 strcat(bookMove, bookHit);
8081 programStats.nodes = programStats.depth = programStats.time =
8082 programStats.score = programStats.got_only_move = 0;
8083 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8085 if(cps->lastPing != cps->lastPong) {
8086 savedMessage = message; // args for deferred call
8088 ScheduleDelayedEvent(DeferredBookMove, 10);
8097 /* Set special modes for chess engines. Later something general
8098 * could be added here; for now there is just one kludge feature,
8099 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8100 * when "xboard" is given as an interactive command.
8102 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8103 cps->useSigint = FALSE;
8104 cps->useSigterm = FALSE;
8106 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8107 ParseFeatures(message+8, cps);
8108 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8111 if (!appData.testLegality && !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
8112 int dummy, s=6; char buf[MSG_SIZ];
8113 if(appData.icsActive || forwardMostMove != 0 || cps != &first || startedFromSetupPosition) return;
8114 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
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;
8272 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
8273 DisplayError(buf2, 0);
8276 if (StrStr(message, "(no matching move)st")) {
8277 /* Special kludge for GNU Chess 4 only */
8278 cps->stKludge = TRUE;
8279 SendTimeControl(cps, movesPerSession, timeControl,
8280 timeIncrement, appData.searchDepth,
8284 if (StrStr(message, "(no matching move)sd")) {
8285 /* Special kludge for GNU Chess 4 only */
8286 cps->sdKludge = TRUE;
8287 SendTimeControl(cps, movesPerSession, timeControl,
8288 timeIncrement, appData.searchDepth,
8292 if (!StrStr(message, "llegal")) {
8295 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8296 gameMode == IcsIdle) return;
8297 if (forwardMostMove <= backwardMostMove) return;
8298 if (pausing) PauseEvent();
8299 if(appData.forceIllegal) {
8300 // [HGM] illegal: machine refused move; force position after move into it
8301 SendToProgram("force\n", cps);
8302 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
8303 // we have a real problem now, as SendBoard will use the a2a3 kludge
8304 // when black is to move, while there might be nothing on a2 or black
8305 // might already have the move. So send the board as if white has the move.
8306 // But first we must change the stm of the engine, as it refused the last move
8307 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
8308 if(WhiteOnMove(forwardMostMove)) {
8309 SendToProgram("a7a6\n", cps); // for the engine black still had the move
8310 SendBoard(cps, forwardMostMove); // kludgeless board
8312 SendToProgram("a2a3\n", cps); // for the engine white still had the move
8313 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8314 SendBoard(cps, forwardMostMove+1); // kludgeless board
8316 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
8317 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
8318 gameMode == TwoMachinesPlay)
8319 SendToProgram("go\n", cps);
8322 if (gameMode == PlayFromGameFile) {
8323 /* Stop reading this game file */
8324 gameMode = EditGame;
8327 /* [HGM] illegal-move claim should forfeit game when Xboard */
8328 /* only passes fully legal moves */
8329 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
8330 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
8331 "False illegal-move claim", GE_XBOARD );
8332 return; // do not take back move we tested as valid
8334 currentMove = forwardMostMove-1;
8335 DisplayMove(currentMove-1); /* before DisplayMoveError */
8336 SwitchClocks(forwardMostMove-1); // [HGM] race
8337 DisplayBothClocks();
8338 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
8339 parseList[currentMove], _(cps->which));
8340 DisplayMoveError(buf1);
8341 DrawPosition(FALSE, boards[currentMove]);
8344 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
8345 /* Program has a broken "time" command that
8346 outputs a string not ending in newline.
8352 * If chess program startup fails, exit with an error message.
8353 * Attempts to recover here are futile.
8355 if ((StrStr(message, "unknown host") != NULL)
8356 || (StrStr(message, "No remote directory") != NULL)
8357 || (StrStr(message, "not found") != NULL)
8358 || (StrStr(message, "No such file") != NULL)
8359 || (StrStr(message, "can't alloc") != NULL)
8360 || (StrStr(message, "Permission denied") != NULL)) {
8362 cps->maybeThinking = FALSE;
8363 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
8364 _(cps->which), cps->program, cps->host, message);
8365 RemoveInputSource(cps->isr);
8366 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
8367 if(cps == &first) appData.noChessProgram = TRUE;
8368 DisplayError(buf1, 0);
8374 * Look for hint output
8376 if (sscanf(message, "Hint: %s", buf1) == 1) {
8377 if (cps == &first && hintRequested) {
8378 hintRequested = FALSE;
8379 if (ParseOneMove(buf1, forwardMostMove, &moveType,
8380 &fromX, &fromY, &toX, &toY, &promoChar)) {
8381 (void) CoordsToAlgebraic(boards[forwardMostMove],
8382 PosFlags(forwardMostMove),
8383 fromY, fromX, toY, toX, promoChar, buf1);
8384 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
8385 DisplayInformation(buf2);
8387 /* Hint move could not be parsed!? */
8388 snprintf(buf2, sizeof(buf2),
8389 _("Illegal hint move \"%s\"\nfrom %s chess program"),
8390 buf1, _(cps->which));
8391 DisplayError(buf2, 0);
8394 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
8400 * Ignore other messages if game is not in progress
8402 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8403 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
8406 * look for win, lose, draw, or draw offer
8408 if (strncmp(message, "1-0", 3) == 0) {
8409 char *p, *q, *r = "";
8410 p = strchr(message, '{');
8418 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8420 } else if (strncmp(message, "0-1", 3) == 0) {
8421 char *p, *q, *r = "";
8422 p = strchr(message, '{');
8430 /* Kludge for Arasan 4.1 bug */
8431 if (strcmp(r, "Black resigns") == 0) {
8432 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8435 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8437 } else if (strncmp(message, "1/2", 3) == 0) {
8438 char *p, *q, *r = "";
8439 p = strchr(message, '{');
8448 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8451 } else if (strncmp(message, "White resign", 12) == 0) {
8452 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8454 } else if (strncmp(message, "Black resign", 12) == 0) {
8455 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8457 } else if (strncmp(message, "White matches", 13) == 0 ||
8458 strncmp(message, "Black matches", 13) == 0 ) {
8459 /* [HGM] ignore GNUShogi noises */
8461 } else if (strncmp(message, "White", 5) == 0 &&
8462 message[5] != '(' &&
8463 StrStr(message, "Black") == NULL) {
8464 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8466 } else if (strncmp(message, "Black", 5) == 0 &&
8467 message[5] != '(') {
8468 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8470 } else if (strcmp(message, "resign") == 0 ||
8471 strcmp(message, "computer resigns") == 0) {
8473 case MachinePlaysBlack:
8474 case IcsPlayingBlack:
8475 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8477 case MachinePlaysWhite:
8478 case IcsPlayingWhite:
8479 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8481 case TwoMachinesPlay:
8482 if (cps->twoMachinesColor[0] == 'w')
8483 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8485 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8492 } else if (strncmp(message, "opponent mates", 14) == 0) {
8494 case MachinePlaysBlack:
8495 case IcsPlayingBlack:
8496 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8498 case MachinePlaysWhite:
8499 case IcsPlayingWhite:
8500 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8502 case TwoMachinesPlay:
8503 if (cps->twoMachinesColor[0] == 'w')
8504 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8506 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8513 } else if (strncmp(message, "computer mates", 14) == 0) {
8515 case MachinePlaysBlack:
8516 case IcsPlayingBlack:
8517 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8519 case MachinePlaysWhite:
8520 case IcsPlayingWhite:
8521 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8523 case TwoMachinesPlay:
8524 if (cps->twoMachinesColor[0] == 'w')
8525 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8527 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8534 } else if (strncmp(message, "checkmate", 9) == 0) {
8535 if (WhiteOnMove(forwardMostMove)) {
8536 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8538 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8541 } else if (strstr(message, "Draw") != NULL ||
8542 strstr(message, "game is a draw") != NULL) {
8543 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8545 } else if (strstr(message, "offer") != NULL &&
8546 strstr(message, "draw") != NULL) {
8548 if (appData.zippyPlay && first.initDone) {
8549 /* Relay offer to ICS */
8550 SendToICS(ics_prefix);
8551 SendToICS("draw\n");
8554 cps->offeredDraw = 2; /* valid until this engine moves twice */
8555 if (gameMode == TwoMachinesPlay) {
8556 if (cps->other->offeredDraw) {
8557 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8558 /* [HGM] in two-machine mode we delay relaying draw offer */
8559 /* until after we also have move, to see if it is really claim */
8561 } else if (gameMode == MachinePlaysWhite ||
8562 gameMode == MachinePlaysBlack) {
8563 if (userOfferedDraw) {
8564 DisplayInformation(_("Machine accepts your draw offer"));
8565 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8567 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8574 * Look for thinking output
8576 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8577 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8579 int plylev, mvleft, mvtot, curscore, time;
8580 char mvname[MOVE_LEN];
8584 int prefixHint = FALSE;
8585 mvname[0] = NULLCHAR;
8588 case MachinePlaysBlack:
8589 case IcsPlayingBlack:
8590 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8592 case MachinePlaysWhite:
8593 case IcsPlayingWhite:
8594 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8599 case IcsObserving: /* [DM] icsEngineAnalyze */
8600 if (!appData.icsEngineAnalyze) ignore = TRUE;
8602 case TwoMachinesPlay:
8603 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8613 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8615 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8616 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8618 if (plyext != ' ' && plyext != '\t') {
8622 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8623 if( cps->scoreIsAbsolute &&
8624 ( gameMode == MachinePlaysBlack ||
8625 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8626 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8627 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8628 !WhiteOnMove(currentMove)
8631 curscore = -curscore;
8634 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
8636 tempStats.depth = plylev;
8637 tempStats.nodes = nodes;
8638 tempStats.time = time;
8639 tempStats.score = curscore;
8640 tempStats.got_only_move = 0;
8642 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8645 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8646 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8647 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8648 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8649 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8650 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8651 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8652 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8655 /* Buffer overflow protection */
8656 if (pv[0] != NULLCHAR) {
8657 if (strlen(pv) >= sizeof(tempStats.movelist)
8658 && appData.debugMode) {
8660 "PV is too long; using the first %u bytes.\n",
8661 (unsigned) sizeof(tempStats.movelist) - 1);
8664 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8666 sprintf(tempStats.movelist, " no PV\n");
8669 if (tempStats.seen_stat) {
8670 tempStats.ok_to_send = 1;
8673 if (strchr(tempStats.movelist, '(') != NULL) {
8674 tempStats.line_is_book = 1;
8675 tempStats.nr_moves = 0;
8676 tempStats.moves_left = 0;
8678 tempStats.line_is_book = 0;
8681 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8682 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8684 SendProgramStatsToFrontend( cps, &tempStats );
8687 [AS] Protect the thinkOutput buffer from overflow... this
8688 is only useful if buf1 hasn't overflowed first!
8690 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8692 (gameMode == TwoMachinesPlay ?
8693 ToUpper(cps->twoMachinesColor[0]) : ' '),
8694 ((double) curscore) / 100.0,
8695 prefixHint ? lastHint : "",
8696 prefixHint ? " " : "" );
8698 if( buf1[0] != NULLCHAR ) {
8699 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8701 if( strlen(pv) > max_len ) {
8702 if( appData.debugMode) {
8703 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8705 pv[max_len+1] = '\0';
8708 strcat( thinkOutput, pv);
8711 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8712 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8713 DisplayMove(currentMove - 1);
8717 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8718 /* crafty (9.25+) says "(only move) <move>"
8719 * if there is only 1 legal move
8721 sscanf(p, "(only move) %s", buf1);
8722 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8723 sprintf(programStats.movelist, "%s (only move)", buf1);
8724 programStats.depth = 1;
8725 programStats.nr_moves = 1;
8726 programStats.moves_left = 1;
8727 programStats.nodes = 1;
8728 programStats.time = 1;
8729 programStats.got_only_move = 1;
8731 /* Not really, but we also use this member to
8732 mean "line isn't going to change" (Crafty
8733 isn't searching, so stats won't change) */
8734 programStats.line_is_book = 1;
8736 SendProgramStatsToFrontend( cps, &programStats );
8738 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8739 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8740 DisplayMove(currentMove - 1);
8743 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8744 &time, &nodes, &plylev, &mvleft,
8745 &mvtot, mvname) >= 5) {
8746 /* The stat01: line is from Crafty (9.29+) in response
8747 to the "." command */
8748 programStats.seen_stat = 1;
8749 cps->maybeThinking = TRUE;
8751 if (programStats.got_only_move || !appData.periodicUpdates)
8754 programStats.depth = plylev;
8755 programStats.time = time;
8756 programStats.nodes = nodes;
8757 programStats.moves_left = mvleft;
8758 programStats.nr_moves = mvtot;
8759 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8760 programStats.ok_to_send = 1;
8761 programStats.movelist[0] = '\0';
8763 SendProgramStatsToFrontend( cps, &programStats );
8767 } else if (strncmp(message,"++",2) == 0) {
8768 /* Crafty 9.29+ outputs this */
8769 programStats.got_fail = 2;
8772 } else if (strncmp(message,"--",2) == 0) {
8773 /* Crafty 9.29+ outputs this */
8774 programStats.got_fail = 1;
8777 } else if (thinkOutput[0] != NULLCHAR &&
8778 strncmp(message, " ", 4) == 0) {
8779 unsigned message_len;
8782 while (*p && *p == ' ') p++;
8784 message_len = strlen( p );
8786 /* [AS] Avoid buffer overflow */
8787 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8788 strcat(thinkOutput, " ");
8789 strcat(thinkOutput, p);
8792 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8793 strcat(programStats.movelist, " ");
8794 strcat(programStats.movelist, p);
8797 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8798 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8799 DisplayMove(currentMove - 1);
8807 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8808 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8810 ChessProgramStats cpstats;
8812 if (plyext != ' ' && plyext != '\t') {
8816 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8817 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8818 curscore = -curscore;
8821 cpstats.depth = plylev;
8822 cpstats.nodes = nodes;
8823 cpstats.time = time;
8824 cpstats.score = curscore;
8825 cpstats.got_only_move = 0;
8826 cpstats.movelist[0] = '\0';
8828 if (buf1[0] != NULLCHAR) {
8829 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8832 cpstats.ok_to_send = 0;
8833 cpstats.line_is_book = 0;
8834 cpstats.nr_moves = 0;
8835 cpstats.moves_left = 0;
8837 SendProgramStatsToFrontend( cps, &cpstats );
8844 /* Parse a game score from the character string "game", and
8845 record it as the history of the current game. The game
8846 score is NOT assumed to start from the standard position.
8847 The display is not updated in any way.
8850 ParseGameHistory(game)
8854 int fromX, fromY, toX, toY, boardIndex;
8859 if (appData.debugMode)
8860 fprintf(debugFP, "Parsing game history: %s\n", game);
8862 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8863 gameInfo.site = StrSave(appData.icsHost);
8864 gameInfo.date = PGNDate();
8865 gameInfo.round = StrSave("-");
8867 /* Parse out names of players */
8868 while (*game == ' ') game++;
8870 while (*game != ' ') *p++ = *game++;
8872 gameInfo.white = StrSave(buf);
8873 while (*game == ' ') game++;
8875 while (*game != ' ' && *game != '\n') *p++ = *game++;
8877 gameInfo.black = StrSave(buf);
8880 boardIndex = blackPlaysFirst ? 1 : 0;
8883 yyboardindex = boardIndex;
8884 moveType = (ChessMove) Myylex();
8886 case IllegalMove: /* maybe suicide chess, etc. */
8887 if (appData.debugMode) {
8888 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8889 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8890 setbuf(debugFP, NULL);
8892 case WhitePromotion:
8893 case BlackPromotion:
8894 case WhiteNonPromotion:
8895 case BlackNonPromotion:
8897 case WhiteCapturesEnPassant:
8898 case BlackCapturesEnPassant:
8899 case WhiteKingSideCastle:
8900 case WhiteQueenSideCastle:
8901 case BlackKingSideCastle:
8902 case BlackQueenSideCastle:
8903 case WhiteKingSideCastleWild:
8904 case WhiteQueenSideCastleWild:
8905 case BlackKingSideCastleWild:
8906 case BlackQueenSideCastleWild:
8908 case WhiteHSideCastleFR:
8909 case WhiteASideCastleFR:
8910 case BlackHSideCastleFR:
8911 case BlackASideCastleFR:
8913 fromX = currentMoveString[0] - AAA;
8914 fromY = currentMoveString[1] - ONE;
8915 toX = currentMoveString[2] - AAA;
8916 toY = currentMoveString[3] - ONE;
8917 promoChar = currentMoveString[4];
8921 fromX = moveType == WhiteDrop ?
8922 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8923 (int) CharToPiece(ToLower(currentMoveString[0]));
8925 toX = currentMoveString[2] - AAA;
8926 toY = currentMoveString[3] - ONE;
8927 promoChar = NULLCHAR;
8931 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8932 if (appData.debugMode) {
8933 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8934 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8935 setbuf(debugFP, NULL);
8937 DisplayError(buf, 0);
8939 case ImpossibleMove:
8941 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8942 if (appData.debugMode) {
8943 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8944 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8945 setbuf(debugFP, NULL);
8947 DisplayError(buf, 0);
8950 if (boardIndex < backwardMostMove) {
8951 /* Oops, gap. How did that happen? */
8952 DisplayError(_("Gap in move list"), 0);
8955 backwardMostMove = blackPlaysFirst ? 1 : 0;
8956 if (boardIndex > forwardMostMove) {
8957 forwardMostMove = boardIndex;
8961 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8962 strcat(parseList[boardIndex-1], " ");
8963 strcat(parseList[boardIndex-1], yy_text);
8975 case GameUnfinished:
8976 if (gameMode == IcsExamining) {
8977 if (boardIndex < backwardMostMove) {
8978 /* Oops, gap. How did that happen? */
8981 backwardMostMove = blackPlaysFirst ? 1 : 0;
8984 gameInfo.result = moveType;
8985 p = strchr(yy_text, '{');
8986 if (p == NULL) p = strchr(yy_text, '(');
8989 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8991 q = strchr(p, *p == '{' ? '}' : ')');
8992 if (q != NULL) *q = NULLCHAR;
8995 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
8996 gameInfo.resultDetails = StrSave(p);
8999 if (boardIndex >= forwardMostMove &&
9000 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9001 backwardMostMove = blackPlaysFirst ? 1 : 0;
9004 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9005 fromY, fromX, toY, toX, promoChar,
9006 parseList[boardIndex]);
9007 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9008 /* currentMoveString is set as a side-effect of yylex */
9009 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9010 strcat(moveList[boardIndex], "\n");
9012 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9013 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9019 if(gameInfo.variant != VariantShogi)
9020 strcat(parseList[boardIndex - 1], "+");
9024 strcat(parseList[boardIndex - 1], "#");
9031 /* Apply a move to the given board */
9033 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
9034 int fromX, fromY, toX, toY;
9038 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9039 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
9041 /* [HGM] compute & store e.p. status and castling rights for new position */
9042 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9044 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9045 oldEP = (signed char)board[EP_STATUS];
9046 board[EP_STATUS] = EP_NONE;
9048 if (fromY == DROP_RANK) {
9050 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9051 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9054 piece = board[toY][toX] = (ChessSquare) fromX;
9058 if( board[toY][toX] != EmptySquare )
9059 board[EP_STATUS] = EP_CAPTURE;
9061 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9062 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9063 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9065 if( board[fromY][fromX] == WhitePawn ) {
9066 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9067 board[EP_STATUS] = EP_PAWN_MOVE;
9069 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9070 gameInfo.variant != VariantBerolina || toX < fromX)
9071 board[EP_STATUS] = toX | berolina;
9072 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9073 gameInfo.variant != VariantBerolina || toX > fromX)
9074 board[EP_STATUS] = toX;
9077 if( board[fromY][fromX] == BlackPawn ) {
9078 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9079 board[EP_STATUS] = EP_PAWN_MOVE;
9080 if( toY-fromY== -2) {
9081 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9082 gameInfo.variant != VariantBerolina || toX < fromX)
9083 board[EP_STATUS] = toX | berolina;
9084 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9085 gameInfo.variant != VariantBerolina || toX > fromX)
9086 board[EP_STATUS] = toX;
9090 for(i=0; i<nrCastlingRights; i++) {
9091 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9092 board[CASTLING][i] == toX && castlingRank[i] == toY
9093 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9096 if (fromX == toX && fromY == toY) return;
9098 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9099 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9100 if(gameInfo.variant == VariantKnightmate)
9101 king += (int) WhiteUnicorn - (int) WhiteKing;
9103 /* Code added by Tord: */
9104 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9105 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9106 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9107 board[fromY][fromX] = EmptySquare;
9108 board[toY][toX] = EmptySquare;
9109 if((toX > fromX) != (piece == WhiteRook)) {
9110 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9112 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9114 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9115 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9116 board[fromY][fromX] = EmptySquare;
9117 board[toY][toX] = EmptySquare;
9118 if((toX > fromX) != (piece == BlackRook)) {
9119 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9121 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9123 /* End of code added by Tord */
9125 } else if (board[fromY][fromX] == king
9126 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9127 && toY == fromY && toX > fromX+1) {
9128 board[fromY][fromX] = EmptySquare;
9129 board[toY][toX] = king;
9130 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9131 board[fromY][BOARD_RGHT-1] = EmptySquare;
9132 } else if (board[fromY][fromX] == king
9133 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9134 && toY == fromY && toX < fromX-1) {
9135 board[fromY][fromX] = EmptySquare;
9136 board[toY][toX] = king;
9137 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9138 board[fromY][BOARD_LEFT] = EmptySquare;
9139 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
9140 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9141 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
9143 /* white pawn promotion */
9144 board[toY][toX] = CharToPiece(ToUpper(promoChar));
9145 if(gameInfo.variant==VariantBughouse ||
9146 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9147 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9148 board[fromY][fromX] = EmptySquare;
9149 } else if ((fromY >= BOARD_HEIGHT>>1)
9151 && gameInfo.variant != VariantXiangqi
9152 && gameInfo.variant != VariantBerolina
9153 && (board[fromY][fromX] == WhitePawn)
9154 && (board[toY][toX] == EmptySquare)) {
9155 board[fromY][fromX] = EmptySquare;
9156 board[toY][toX] = WhitePawn;
9157 captured = board[toY - 1][toX];
9158 board[toY - 1][toX] = EmptySquare;
9159 } else if ((fromY == BOARD_HEIGHT-4)
9161 && gameInfo.variant == VariantBerolina
9162 && (board[fromY][fromX] == WhitePawn)
9163 && (board[toY][toX] == EmptySquare)) {
9164 board[fromY][fromX] = EmptySquare;
9165 board[toY][toX] = WhitePawn;
9166 if(oldEP & EP_BEROLIN_A) {
9167 captured = board[fromY][fromX-1];
9168 board[fromY][fromX-1] = EmptySquare;
9169 }else{ captured = board[fromY][fromX+1];
9170 board[fromY][fromX+1] = EmptySquare;
9172 } else if (board[fromY][fromX] == king
9173 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9174 && toY == fromY && toX > fromX+1) {
9175 board[fromY][fromX] = EmptySquare;
9176 board[toY][toX] = king;
9177 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9178 board[fromY][BOARD_RGHT-1] = EmptySquare;
9179 } else if (board[fromY][fromX] == king
9180 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9181 && toY == fromY && toX < fromX-1) {
9182 board[fromY][fromX] = EmptySquare;
9183 board[toY][toX] = king;
9184 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9185 board[fromY][BOARD_LEFT] = EmptySquare;
9186 } else if (fromY == 7 && fromX == 3
9187 && board[fromY][fromX] == BlackKing
9188 && toY == 7 && toX == 5) {
9189 board[fromY][fromX] = EmptySquare;
9190 board[toY][toX] = BlackKing;
9191 board[fromY][7] = EmptySquare;
9192 board[toY][4] = BlackRook;
9193 } else if (fromY == 7 && fromX == 3
9194 && board[fromY][fromX] == BlackKing
9195 && toY == 7 && toX == 1) {
9196 board[fromY][fromX] = EmptySquare;
9197 board[toY][toX] = BlackKing;
9198 board[fromY][0] = EmptySquare;
9199 board[toY][2] = BlackRook;
9200 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
9201 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9202 && toY < promoRank && promoChar
9204 /* black pawn promotion */
9205 board[toY][toX] = CharToPiece(ToLower(promoChar));
9206 if(gameInfo.variant==VariantBughouse ||
9207 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9208 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9209 board[fromY][fromX] = EmptySquare;
9210 } else if ((fromY < BOARD_HEIGHT>>1)
9212 && gameInfo.variant != VariantXiangqi
9213 && gameInfo.variant != VariantBerolina
9214 && (board[fromY][fromX] == BlackPawn)
9215 && (board[toY][toX] == EmptySquare)) {
9216 board[fromY][fromX] = EmptySquare;
9217 board[toY][toX] = BlackPawn;
9218 captured = board[toY + 1][toX];
9219 board[toY + 1][toX] = EmptySquare;
9220 } else if ((fromY == 3)
9222 && gameInfo.variant == VariantBerolina
9223 && (board[fromY][fromX] == BlackPawn)
9224 && (board[toY][toX] == EmptySquare)) {
9225 board[fromY][fromX] = EmptySquare;
9226 board[toY][toX] = BlackPawn;
9227 if(oldEP & EP_BEROLIN_A) {
9228 captured = board[fromY][fromX-1];
9229 board[fromY][fromX-1] = EmptySquare;
9230 }else{ captured = board[fromY][fromX+1];
9231 board[fromY][fromX+1] = EmptySquare;
9234 board[toY][toX] = board[fromY][fromX];
9235 board[fromY][fromX] = EmptySquare;
9239 if (gameInfo.holdingsWidth != 0) {
9241 /* !!A lot more code needs to be written to support holdings */
9242 /* [HGM] OK, so I have written it. Holdings are stored in the */
9243 /* penultimate board files, so they are automaticlly stored */
9244 /* in the game history. */
9245 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
9246 && promoChar && piece != WhitePawn && piece != BlackPawn) {
9247 /* Delete from holdings, by decreasing count */
9248 /* and erasing image if necessary */
9249 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
9250 if(p < (int) BlackPawn) { /* white drop */
9251 p -= (int)WhitePawn;
9252 p = PieceToNumber((ChessSquare)p);
9253 if(p >= gameInfo.holdingsSize) p = 0;
9254 if(--board[p][BOARD_WIDTH-2] <= 0)
9255 board[p][BOARD_WIDTH-1] = EmptySquare;
9256 if((int)board[p][BOARD_WIDTH-2] < 0)
9257 board[p][BOARD_WIDTH-2] = 0;
9258 } else { /* black drop */
9259 p -= (int)BlackPawn;
9260 p = PieceToNumber((ChessSquare)p);
9261 if(p >= gameInfo.holdingsSize) p = 0;
9262 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
9263 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
9264 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
9265 board[BOARD_HEIGHT-1-p][1] = 0;
9268 if (captured != EmptySquare && gameInfo.holdingsSize > 0
9269 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
9270 /* [HGM] holdings: Add to holdings, if holdings exist */
9271 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
9272 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
9273 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
9276 if (p >= (int) BlackPawn) {
9277 p -= (int)BlackPawn;
9278 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9279 /* in Shogi restore piece to its original first */
9280 captured = (ChessSquare) (DEMOTED captured);
9283 p = PieceToNumber((ChessSquare)p);
9284 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
9285 board[p][BOARD_WIDTH-2]++;
9286 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
9288 p -= (int)WhitePawn;
9289 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9290 captured = (ChessSquare) (DEMOTED captured);
9293 p = PieceToNumber((ChessSquare)p);
9294 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
9295 board[BOARD_HEIGHT-1-p][1]++;
9296 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
9299 } else if (gameInfo.variant == VariantAtomic) {
9300 if (captured != EmptySquare) {
9302 for (y = toY-1; y <= toY+1; y++) {
9303 for (x = toX-1; x <= toX+1; x++) {
9304 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
9305 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
9306 board[y][x] = EmptySquare;
9310 board[toY][toX] = EmptySquare;
9313 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
9314 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
9316 if(promoChar == '+') {
9317 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
9318 board[toY][toX] = (ChessSquare) (PROMOTED piece);
9319 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
9320 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
9322 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
9323 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
9324 // [HGM] superchess: take promotion piece out of holdings
9325 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
9326 if((int)piece < (int)BlackPawn) { // determine stm from piece color
9327 if(!--board[k][BOARD_WIDTH-2])
9328 board[k][BOARD_WIDTH-1] = EmptySquare;
9330 if(!--board[BOARD_HEIGHT-1-k][1])
9331 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
9337 /* Updates forwardMostMove */
9339 MakeMove(fromX, fromY, toX, toY, promoChar)
9340 int fromX, fromY, toX, toY;
9343 // forwardMostMove++; // [HGM] bare: moved downstream
9345 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
9346 int timeLeft; static int lastLoadFlag=0; int king, piece;
9347 piece = boards[forwardMostMove][fromY][fromX];
9348 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
9349 if(gameInfo.variant == VariantKnightmate)
9350 king += (int) WhiteUnicorn - (int) WhiteKing;
9351 if(forwardMostMove == 0) {
9353 fprintf(serverMoves, "%s;", second.tidy);
9354 fprintf(serverMoves, "%s;", first.tidy);
9355 if(!blackPlaysFirst)
9356 fprintf(serverMoves, "%s;", second.tidy);
9357 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
9358 lastLoadFlag = loadFlag;
9360 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
9361 // print castling suffix
9362 if( toY == fromY && piece == king ) {
9364 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
9366 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
9369 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
9370 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
9371 boards[forwardMostMove][toY][toX] == EmptySquare
9372 && fromX != toX && fromY != toY)
9373 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
9375 if(promoChar != NULLCHAR)
9376 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
9378 fprintf(serverMoves, "/%d/%d",
9379 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
9380 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
9381 else timeLeft = blackTimeRemaining/1000;
9382 fprintf(serverMoves, "/%d", timeLeft);
9384 fflush(serverMoves);
9387 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
9388 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
9392 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
9393 if (commentList[forwardMostMove+1] != NULL) {
9394 free(commentList[forwardMostMove+1]);
9395 commentList[forwardMostMove+1] = NULL;
9397 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9398 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
9399 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
9400 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
9401 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9402 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9403 gameInfo.result = GameUnfinished;
9404 if (gameInfo.resultDetails != NULL) {
9405 free(gameInfo.resultDetails);
9406 gameInfo.resultDetails = NULL;
9408 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9409 moveList[forwardMostMove - 1]);
9410 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
9411 PosFlags(forwardMostMove - 1),
9412 fromY, fromX, toY, toX, promoChar,
9413 parseList[forwardMostMove - 1]);
9414 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9420 if(gameInfo.variant != VariantShogi)
9421 strcat(parseList[forwardMostMove - 1], "+");
9425 strcat(parseList[forwardMostMove - 1], "#");
9428 if (appData.debugMode) {
9429 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
9434 /* Updates currentMove if not pausing */
9436 ShowMove(fromX, fromY, toX, toY)
9438 int instant = (gameMode == PlayFromGameFile) ?
9439 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9440 if(appData.noGUI) return;
9441 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9443 if (forwardMostMove == currentMove + 1) {
9444 AnimateMove(boards[forwardMostMove - 1],
9445 fromX, fromY, toX, toY);
9447 if (appData.highlightLastMove) {
9448 SetHighlights(fromX, fromY, toX, toY);
9451 currentMove = forwardMostMove;
9454 if (instant) return;
9456 DisplayMove(currentMove - 1);
9457 DrawPosition(FALSE, boards[currentMove]);
9458 DisplayBothClocks();
9459 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9460 DisplayBook(currentMove);
9463 void SendEgtPath(ChessProgramState *cps)
9464 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9465 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9467 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9470 char c, *q = name+1, *r, *s;
9472 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9473 while(*p && *p != ',') *q++ = *p++;
9475 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9476 strcmp(name, ",nalimov:") == 0 ) {
9477 // take nalimov path from the menu-changeable option first, if it is defined
9478 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9479 SendToProgram(buf,cps); // send egtbpath command for nalimov
9481 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9482 (s = StrStr(appData.egtFormats, name)) != NULL) {
9483 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9484 s = r = StrStr(s, ":") + 1; // beginning of path info
9485 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9486 c = *r; *r = 0; // temporarily null-terminate path info
9487 *--q = 0; // strip of trailig ':' from name
9488 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9490 SendToProgram(buf,cps); // send egtbpath command for this format
9492 if(*p == ',') p++; // read away comma to position for next format name
9497 InitChessProgram(cps, setup)
9498 ChessProgramState *cps;
9499 int setup; /* [HGM] needed to setup FRC opening position */
9501 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9502 if (appData.noChessProgram) return;
9503 hintRequested = FALSE;
9504 bookRequested = FALSE;
9506 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9507 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9508 if(cps->memSize) { /* [HGM] memory */
9509 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9510 SendToProgram(buf, cps);
9512 SendEgtPath(cps); /* [HGM] EGT */
9513 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9514 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9515 SendToProgram(buf, cps);
9518 SendToProgram(cps->initString, cps);
9519 if (gameInfo.variant != VariantNormal &&
9520 gameInfo.variant != VariantLoadable
9521 /* [HGM] also send variant if board size non-standard */
9522 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9524 char *v = VariantName(gameInfo.variant);
9525 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9526 /* [HGM] in protocol 1 we have to assume all variants valid */
9527 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9528 DisplayFatalError(buf, 0, 1);
9532 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9533 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9534 if( gameInfo.variant == VariantXiangqi )
9535 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9536 if( gameInfo.variant == VariantShogi )
9537 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9538 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9539 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9540 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9541 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9542 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9543 if( gameInfo.variant == VariantCourier )
9544 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9545 if( gameInfo.variant == VariantSuper )
9546 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9547 if( gameInfo.variant == VariantGreat )
9548 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9549 if( gameInfo.variant == VariantSChess )
9550 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9551 if( gameInfo.variant == VariantGrand )
9552 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 7;
9555 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9556 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9557 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9558 if(StrStr(cps->variants, b) == NULL) {
9559 // specific sized variant not known, check if general sizing allowed
9560 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9561 if(StrStr(cps->variants, "boardsize") == NULL) {
9562 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9563 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9564 DisplayFatalError(buf, 0, 1);
9567 /* [HGM] here we really should compare with the maximum supported board size */
9570 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9571 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9572 SendToProgram(buf, cps);
9574 currentlyInitializedVariant = gameInfo.variant;
9576 /* [HGM] send opening position in FRC to first engine */
9578 SendToProgram("force\n", cps);
9580 /* engine is now in force mode! Set flag to wake it up after first move. */
9581 setboardSpoiledMachineBlack = 1;
9585 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9586 SendToProgram(buf, cps);
9588 cps->maybeThinking = FALSE;
9589 cps->offeredDraw = 0;
9590 if (!appData.icsActive) {
9591 SendTimeControl(cps, movesPerSession, timeControl,
9592 timeIncrement, appData.searchDepth,
9595 if (appData.showThinking
9596 // [HGM] thinking: four options require thinking output to be sent
9597 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9599 SendToProgram("post\n", cps);
9601 SendToProgram("hard\n", cps);
9602 if (!appData.ponderNextMove) {
9603 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9604 it without being sure what state we are in first. "hard"
9605 is not a toggle, so that one is OK.
9607 SendToProgram("easy\n", cps);
9610 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9611 SendToProgram(buf, cps);
9613 cps->initDone = TRUE;
9614 ClearEngineOutputPane(cps == &second);
9619 StartChessProgram(cps)
9620 ChessProgramState *cps;
9625 if (appData.noChessProgram) return;
9626 cps->initDone = FALSE;
9628 if (strcmp(cps->host, "localhost") == 0) {
9629 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9630 } else if (*appData.remoteShell == NULLCHAR) {
9631 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9633 if (*appData.remoteUser == NULLCHAR) {
9634 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9637 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9638 cps->host, appData.remoteUser, cps->program);
9640 err = StartChildProcess(buf, "", &cps->pr);
9644 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9645 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
9646 if(cps != &first) return;
9647 appData.noChessProgram = TRUE;
9650 // DisplayFatalError(buf, err, 1);
9651 // cps->pr = NoProc;
9656 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9657 if (cps->protocolVersion > 1) {
9658 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9659 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9660 cps->comboCnt = 0; // and values of combo boxes
9661 SendToProgram(buf, cps);
9663 SendToProgram("xboard\n", cps);
9668 TwoMachinesEventIfReady P((void))
9670 static int curMess = 0;
9671 if (first.lastPing != first.lastPong) {
9672 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
9673 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9676 if (second.lastPing != second.lastPong) {
9677 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
9678 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9681 DisplayMessage("", ""); curMess = 0;
9687 MakeName(char *template)
9691 static char buf[MSG_SIZ];
9695 clock = time((time_t *)NULL);
9696 tm = localtime(&clock);
9698 while(*p++ = *template++) if(p[-1] == '%') {
9699 switch(*template++) {
9700 case 0: *p = 0; return buf;
9701 case 'Y': i = tm->tm_year+1900; break;
9702 case 'y': i = tm->tm_year-100; break;
9703 case 'M': i = tm->tm_mon+1; break;
9704 case 'd': i = tm->tm_mday; break;
9705 case 'h': i = tm->tm_hour; break;
9706 case 'm': i = tm->tm_min; break;
9707 case 's': i = tm->tm_sec; break;
9710 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
9716 CountPlayers(char *p)
9719 while(p = strchr(p, '\n')) p++, n++; // count participants
9724 WriteTourneyFile(char *results, FILE *f)
9725 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
9726 if(f == NULL) f = fopen(appData.tourneyFile, "w");
9727 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
9728 // create a file with tournament description
9729 fprintf(f, "-participants {%s}\n", appData.participants);
9730 fprintf(f, "-seedBase %d\n", appData.seedBase);
9731 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
9732 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
9733 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
9734 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
9735 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
9736 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
9737 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
9738 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
9739 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
9740 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
9741 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
9743 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
9745 fprintf(f, "-mps %d\n", appData.movesPerSession);
9746 fprintf(f, "-tc %s\n", appData.timeControl);
9747 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
9749 fprintf(f, "-results \"%s\"\n", results);
9754 #define MAXENGINES 1000
9755 char *command[MAXENGINES], *mnemonic[MAXENGINES];
9757 void Substitute(char *participants, int expunge)
9759 int i, changed, changes=0, nPlayers=0;
9760 char *p, *q, *r, buf[MSG_SIZ];
9761 if(participants == NULL) return;
9762 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
9763 r = p = participants; q = appData.participants;
9764 while(*p && *p == *q) {
9765 if(*p == '\n') r = p+1, nPlayers++;
9768 if(*p) { // difference
9769 while(*p && *p++ != '\n');
9770 while(*q && *q++ != '\n');
9772 changes = 1 + (strcmp(p, q) != 0);
9774 if(changes == 1) { // a single engine mnemonic was changed
9775 q = r; while(*q) nPlayers += (*q++ == '\n');
9776 p = buf; while(*r && (*p = *r++) != '\n') p++;
9778 NamesToList(firstChessProgramNames, command, mnemonic);
9779 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
9780 if(mnemonic[i]) { // The substitute is valid
9782 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
9783 flock(fileno(f), LOCK_EX);
9784 ParseArgsFromFile(f);
9785 fseek(f, 0, SEEK_SET);
9786 FREE(appData.participants); appData.participants = participants;
9787 if(expunge) { // erase results of replaced engine
9788 int len = strlen(appData.results), w, b, dummy;
9789 for(i=0; i<len; i++) {
9790 Pairing(i, nPlayers, &w, &b, &dummy);
9791 if((w == changed || b == changed) && appData.results[i] == '*') {
9792 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
9797 for(i=0; i<len; i++) {
9798 Pairing(i, nPlayers, &w, &b, &dummy);
9799 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
9802 WriteTourneyFile(appData.results, f);
9803 fclose(f); // release lock
9806 } else DisplayError(_("No engine with the name you gave is installed"), 0);
9808 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
9809 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
9815 CreateTourney(char *name)
9818 if(matchMode && strcmp(name, appData.tourneyFile)) {
9819 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
9821 if(name[0] == NULLCHAR) {
9822 if(appData.participants[0])
9823 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
9826 f = fopen(name, "r");
9827 if(f) { // file exists
9828 ASSIGN(appData.tourneyFile, name);
9829 ParseArgsFromFile(f); // parse it
9831 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
9832 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
9833 DisplayError(_("Not enough participants"), 0);
9836 ASSIGN(appData.tourneyFile, name);
9837 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
9838 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
9841 appData.noChessProgram = FALSE;
9842 appData.clockMode = TRUE;
9847 void NamesToList(char *names, char **engineList, char **engineMnemonic)
9849 char buf[MSG_SIZ], *p, *q;
9853 while(*p && *p != '\n') *q++ = *p++;
9855 if(engineList[i]) free(engineList[i]);
9856 engineList[i] = strdup(buf);
9858 TidyProgramName(engineList[i], "localhost", buf);
9859 if(engineMnemonic[i]) free(engineMnemonic[i]);
9860 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
9862 sscanf(q + 8, "%s", buf + strlen(buf));
9865 engineMnemonic[i] = strdup(buf);
9867 if(i > MAXENGINES - 2) break;
9869 engineList[i] = engineMnemonic[i] = NULL;
9872 // following implemented as macro to avoid type limitations
9873 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
9875 void SwapEngines(int n)
9876 { // swap settings for first engine and other engine (so far only some selected options)
9881 SWAP(chessProgram, p)
9883 SWAP(hasOwnBookUCI, h)
9884 SWAP(protocolVersion, h)
9886 SWAP(scoreIsAbsolute, h)
9894 SetPlayer(int player)
9895 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
9897 char buf[MSG_SIZ], *engineName, *p = appData.participants;
9898 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
9899 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
9900 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
9902 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
9903 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL;
9904 ParseArgsFromString(buf);
9910 Pairing(int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
9911 { // determine players from game number
9912 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
9914 if(appData.tourneyType == 0) {
9915 roundsPerCycle = (nPlayers - 1) | 1;
9916 pairingsPerRound = nPlayers / 2;
9917 } else if(appData.tourneyType > 0) {
9918 roundsPerCycle = nPlayers - appData.tourneyType;
9919 pairingsPerRound = appData.tourneyType;
9921 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
9922 gamesPerCycle = gamesPerRound * roundsPerCycle;
9923 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
9924 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
9925 curRound = nr / gamesPerRound; nr %= gamesPerRound;
9926 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
9927 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
9928 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
9930 if(appData.cycleSync) *syncInterval = gamesPerCycle;
9931 if(appData.roundSync) *syncInterval = gamesPerRound;
9933 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
9935 if(appData.tourneyType == 0) {
9936 if(curPairing == (nPlayers-1)/2 ) {
9937 *whitePlayer = curRound;
9938 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
9940 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
9941 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
9942 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
9943 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
9945 } else if(appData.tourneyType > 0) {
9946 *whitePlayer = curPairing;
9947 *blackPlayer = curRound + appData.tourneyType;
9950 // take care of white/black alternation per round.
9951 // For cycles and games this is already taken care of by default, derived from matchGame!
9952 return curRound & 1;
9956 NextTourneyGame(int nr, int *swapColors)
9957 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
9959 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers;
9961 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
9962 tf = fopen(appData.tourneyFile, "r");
9963 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
9964 ParseArgsFromFile(tf); fclose(tf);
9965 InitTimeControls(); // TC might be altered from tourney file
9967 nPlayers = CountPlayers(appData.participants); // count participants
9968 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
9969 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
9972 p = q = appData.results;
9973 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
9974 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
9975 DisplayMessage(_("Waiting for other game(s)"),"");
9976 waitingForGame = TRUE;
9977 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
9980 waitingForGame = FALSE;
9983 if(appData.tourneyType < 0) {
9984 if(nr>=0 && !pairingReceived) {
9986 if(pairing.pr == NoProc) {
9987 if(!appData.pairingEngine[0]) {
9988 DisplayFatalError(_("No pairing engine specified"), 0, 1);
9991 StartChessProgram(&pairing); // starts the pairing engine
9993 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
9994 SendToProgram(buf, &pairing);
9995 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
9996 SendToProgram(buf, &pairing);
9997 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
9999 pairingReceived = 0; // ... so we continue here
10001 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
10002 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
10003 matchGame = 1; roundNr = nr / syncInterval + 1;
10006 if(first.pr != NoProc) return 1; // engines already loaded
10008 // redefine engines, engine dir, etc.
10009 NamesToList(firstChessProgramNames, command, mnemonic); // get mnemonics of installed engines
10010 SetPlayer(whitePlayer); // find white player amongst it, and parse its engine line
10012 SetPlayer(blackPlayer); // find black player amongst it, and parse its engine line
10013 SwapEngines(1); // and make that valid for second engine by swapping
10014 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
10015 InitEngine(&second, 1);
10016 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
10017 UpdateLogos(FALSE); // leave display to ModeHiglight()
10023 { // performs game initialization that does not invoke engines, and then tries to start the game
10024 int firstWhite, swapColors = 0;
10025 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
10026 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
10027 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
10028 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
10029 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
10030 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
10031 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
10032 Reset(FALSE, first.pr != NoProc);
10033 appData.noChessProgram = FALSE;
10034 if(!LoadGameOrPosition(matchGame)) return; // setup game; abort when bad game/pos file
10035 TwoMachinesEvent();
10038 void UserAdjudicationEvent( int result )
10040 ChessMove gameResult = GameIsDrawn;
10043 gameResult = WhiteWins;
10045 else if( result < 0 ) {
10046 gameResult = BlackWins;
10049 if( gameMode == TwoMachinesPlay ) {
10050 GameEnds( gameResult, "User adjudication", GE_XBOARD );
10055 // [HGM] save: calculate checksum of game to make games easily identifiable
10056 int StringCheckSum(char *s)
10059 if(s==NULL) return 0;
10060 while(*s) i = i*259 + *s++;
10067 for(i=backwardMostMove; i<forwardMostMove; i++) {
10068 sum += pvInfoList[i].depth;
10069 sum += StringCheckSum(parseList[i]);
10070 sum += StringCheckSum(commentList[i]);
10073 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
10074 return sum + StringCheckSum(commentList[i]);
10075 } // end of save patch
10078 GameEnds(result, resultDetails, whosays)
10080 char *resultDetails;
10083 GameMode nextGameMode;
10085 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
10087 if(endingGame) return; /* [HGM] crash: forbid recursion */
10089 if(twoBoards) { // [HGM] dual: switch back to one board
10090 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
10091 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
10093 if (appData.debugMode) {
10094 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
10095 result, resultDetails ? resultDetails : "(null)", whosays);
10098 fromX = fromY = -1; // [HGM] abort any move the user is entering.
10100 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
10101 /* If we are playing on ICS, the server decides when the
10102 game is over, but the engine can offer to draw, claim
10106 if (appData.zippyPlay && first.initDone) {
10107 if (result == GameIsDrawn) {
10108 /* In case draw still needs to be claimed */
10109 SendToICS(ics_prefix);
10110 SendToICS("draw\n");
10111 } else if (StrCaseStr(resultDetails, "resign")) {
10112 SendToICS(ics_prefix);
10113 SendToICS("resign\n");
10117 endingGame = 0; /* [HGM] crash */
10121 /* If we're loading the game from a file, stop */
10122 if (whosays == GE_FILE) {
10123 (void) StopLoadGameTimer();
10127 /* Cancel draw offers */
10128 first.offeredDraw = second.offeredDraw = 0;
10130 /* If this is an ICS game, only ICS can really say it's done;
10131 if not, anyone can. */
10132 isIcsGame = (gameMode == IcsPlayingWhite ||
10133 gameMode == IcsPlayingBlack ||
10134 gameMode == IcsObserving ||
10135 gameMode == IcsExamining);
10137 if (!isIcsGame || whosays == GE_ICS) {
10138 /* OK -- not an ICS game, or ICS said it was done */
10140 if (!isIcsGame && !appData.noChessProgram)
10141 SetUserThinkingEnables();
10143 /* [HGM] if a machine claims the game end we verify this claim */
10144 if(gameMode == TwoMachinesPlay && appData.testClaims) {
10145 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
10147 ChessMove trueResult = (ChessMove) -1;
10149 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
10150 first.twoMachinesColor[0] :
10151 second.twoMachinesColor[0] ;
10153 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
10154 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
10155 /* [HGM] verify: engine mate claims accepted if they were flagged */
10156 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
10158 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
10159 /* [HGM] verify: engine mate claims accepted if they were flagged */
10160 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
10162 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
10163 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
10166 // now verify win claims, but not in drop games, as we don't understand those yet
10167 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10168 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
10169 (result == WhiteWins && claimer == 'w' ||
10170 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
10171 if (appData.debugMode) {
10172 fprintf(debugFP, "result=%d sp=%d move=%d\n",
10173 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
10175 if(result != trueResult) {
10176 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
10177 result = claimer == 'w' ? BlackWins : WhiteWins;
10178 resultDetails = buf;
10181 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
10182 && (forwardMostMove <= backwardMostMove ||
10183 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
10184 (claimer=='b')==(forwardMostMove&1))
10186 /* [HGM] verify: draws that were not flagged are false claims */
10187 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
10188 result = claimer == 'w' ? BlackWins : WhiteWins;
10189 resultDetails = buf;
10191 /* (Claiming a loss is accepted no questions asked!) */
10193 /* [HGM] bare: don't allow bare King to win */
10194 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10195 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10196 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
10197 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
10198 && result != GameIsDrawn)
10199 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
10200 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
10201 int p = (signed char)boards[forwardMostMove][i][j] - color;
10202 if(p >= 0 && p <= (int)WhiteKing) k++;
10204 if (appData.debugMode) {
10205 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
10206 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
10209 result = GameIsDrawn;
10210 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
10211 resultDetails = buf;
10217 if(serverMoves != NULL && !loadFlag) { char c = '=';
10218 if(result==WhiteWins) c = '+';
10219 if(result==BlackWins) c = '-';
10220 if(resultDetails != NULL)
10221 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
10223 if (resultDetails != NULL) {
10224 gameInfo.result = result;
10225 gameInfo.resultDetails = StrSave(resultDetails);
10227 /* display last move only if game was not loaded from file */
10228 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
10229 DisplayMove(currentMove - 1);
10231 if (forwardMostMove != 0) {
10232 if (gameMode != PlayFromGameFile && gameMode != EditGame
10233 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
10235 if (*appData.saveGameFile != NULLCHAR) {
10236 SaveGameToFile(appData.saveGameFile, TRUE);
10237 } else if (appData.autoSaveGames) {
10240 if (*appData.savePositionFile != NULLCHAR) {
10241 SavePositionToFile(appData.savePositionFile);
10246 /* Tell program how game ended in case it is learning */
10247 /* [HGM] Moved this to after saving the PGN, just in case */
10248 /* engine died and we got here through time loss. In that */
10249 /* case we will get a fatal error writing the pipe, which */
10250 /* would otherwise lose us the PGN. */
10251 /* [HGM] crash: not needed anymore, but doesn't hurt; */
10252 /* output during GameEnds should never be fatal anymore */
10253 if (gameMode == MachinePlaysWhite ||
10254 gameMode == MachinePlaysBlack ||
10255 gameMode == TwoMachinesPlay ||
10256 gameMode == IcsPlayingWhite ||
10257 gameMode == IcsPlayingBlack ||
10258 gameMode == BeginningOfGame) {
10260 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
10262 if (first.pr != NoProc) {
10263 SendToProgram(buf, &first);
10265 if (second.pr != NoProc &&
10266 gameMode == TwoMachinesPlay) {
10267 SendToProgram(buf, &second);
10272 if (appData.icsActive) {
10273 if (appData.quietPlay &&
10274 (gameMode == IcsPlayingWhite ||
10275 gameMode == IcsPlayingBlack)) {
10276 SendToICS(ics_prefix);
10277 SendToICS("set shout 1\n");
10279 nextGameMode = IcsIdle;
10280 ics_user_moved = FALSE;
10281 /* clean up premove. It's ugly when the game has ended and the
10282 * premove highlights are still on the board.
10285 gotPremove = FALSE;
10286 ClearPremoveHighlights();
10287 DrawPosition(FALSE, boards[currentMove]);
10289 if (whosays == GE_ICS) {
10292 if (gameMode == IcsPlayingWhite)
10294 else if(gameMode == IcsPlayingBlack)
10295 PlayIcsLossSound();
10298 if (gameMode == IcsPlayingBlack)
10300 else if(gameMode == IcsPlayingWhite)
10301 PlayIcsLossSound();
10304 PlayIcsDrawSound();
10307 PlayIcsUnfinishedSound();
10310 } else if (gameMode == EditGame ||
10311 gameMode == PlayFromGameFile ||
10312 gameMode == AnalyzeMode ||
10313 gameMode == AnalyzeFile) {
10314 nextGameMode = gameMode;
10316 nextGameMode = EndOfGame;
10321 nextGameMode = gameMode;
10324 if (appData.noChessProgram) {
10325 gameMode = nextGameMode;
10327 endingGame = 0; /* [HGM] crash */
10332 /* Put first chess program into idle state */
10333 if (first.pr != NoProc &&
10334 (gameMode == MachinePlaysWhite ||
10335 gameMode == MachinePlaysBlack ||
10336 gameMode == TwoMachinesPlay ||
10337 gameMode == IcsPlayingWhite ||
10338 gameMode == IcsPlayingBlack ||
10339 gameMode == BeginningOfGame)) {
10340 SendToProgram("force\n", &first);
10341 if (first.usePing) {
10343 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
10344 SendToProgram(buf, &first);
10347 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10348 /* Kill off first chess program */
10349 if (first.isr != NULL)
10350 RemoveInputSource(first.isr);
10353 if (first.pr != NoProc) {
10355 DoSleep( appData.delayBeforeQuit );
10356 SendToProgram("quit\n", &first);
10357 DoSleep( appData.delayAfterQuit );
10358 DestroyChildProcess(first.pr, first.useSigterm);
10362 if (second.reuse) {
10363 /* Put second chess program into idle state */
10364 if (second.pr != NoProc &&
10365 gameMode == TwoMachinesPlay) {
10366 SendToProgram("force\n", &second);
10367 if (second.usePing) {
10369 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
10370 SendToProgram(buf, &second);
10373 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10374 /* Kill off second chess program */
10375 if (second.isr != NULL)
10376 RemoveInputSource(second.isr);
10379 if (second.pr != NoProc) {
10380 DoSleep( appData.delayBeforeQuit );
10381 SendToProgram("quit\n", &second);
10382 DoSleep( appData.delayAfterQuit );
10383 DestroyChildProcess(second.pr, second.useSigterm);
10385 second.pr = NoProc;
10388 if (matchMode && (gameMode == TwoMachinesPlay || waitingForGame && exiting)) {
10389 char resChar = '=';
10393 if (first.twoMachinesColor[0] == 'w') {
10396 second.matchWins++;
10401 if (first.twoMachinesColor[0] == 'b') {
10404 second.matchWins++;
10407 case GameUnfinished:
10413 if(waitingForGame) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
10414 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
10415 ReserveGame(nextGame, resChar); // sets nextGame
10416 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
10417 else ranking = strdup("busy"); //suppress popup when aborted but not finished
10418 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
10420 if (nextGame <= appData.matchGames && !abortMatch) {
10421 gameMode = nextGameMode;
10422 matchGame = nextGame; // this will be overruled in tourney mode!
10423 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
10424 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
10425 endingGame = 0; /* [HGM] crash */
10428 gameMode = nextGameMode;
10429 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
10430 first.tidy, second.tidy,
10431 first.matchWins, second.matchWins,
10432 appData.matchGames - (first.matchWins + second.matchWins));
10433 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
10434 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
10435 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
10436 first.twoMachinesColor = "black\n";
10437 second.twoMachinesColor = "white\n";
10439 first.twoMachinesColor = "white\n";
10440 second.twoMachinesColor = "black\n";
10444 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
10445 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
10447 gameMode = nextGameMode;
10449 endingGame = 0; /* [HGM] crash */
10450 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
10451 if(matchMode == TRUE) { // match through command line: exit with or without popup
10453 ToNrEvent(forwardMostMove);
10454 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
10456 } else DisplayFatalError(buf, 0, 0);
10457 } else { // match through menu; just stop, with or without popup
10458 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10461 if(strcmp(ranking, "busy")) DisplayNote(ranking);
10462 } else DisplayNote(buf);
10464 if(ranking) free(ranking);
10468 /* Assumes program was just initialized (initString sent).
10469 Leaves program in force mode. */
10471 FeedMovesToProgram(cps, upto)
10472 ChessProgramState *cps;
10477 if (appData.debugMode)
10478 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
10479 startedFromSetupPosition ? "position and " : "",
10480 backwardMostMove, upto, cps->which);
10481 if(currentlyInitializedVariant != gameInfo.variant) {
10483 // [HGM] variantswitch: make engine aware of new variant
10484 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
10485 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
10486 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
10487 SendToProgram(buf, cps);
10488 currentlyInitializedVariant = gameInfo.variant;
10490 SendToProgram("force\n", cps);
10491 if (startedFromSetupPosition) {
10492 SendBoard(cps, backwardMostMove);
10493 if (appData.debugMode) {
10494 fprintf(debugFP, "feedMoves\n");
10497 for (i = backwardMostMove; i < upto; i++) {
10498 SendMoveToProgram(i, cps);
10504 ResurrectChessProgram()
10506 /* The chess program may have exited.
10507 If so, restart it and feed it all the moves made so far. */
10508 static int doInit = 0;
10510 if (appData.noChessProgram) return 1;
10512 if(matchMode && appData.tourneyFile[0]) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
10513 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit
10514 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
10515 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
10517 if (first.pr != NoProc) return 1;
10518 StartChessProgram(&first);
10520 InitChessProgram(&first, FALSE);
10521 FeedMovesToProgram(&first, currentMove);
10523 if (!first.sendTime) {
10524 /* can't tell gnuchess what its clock should read,
10525 so we bow to its notion. */
10527 timeRemaining[0][currentMove] = whiteTimeRemaining;
10528 timeRemaining[1][currentMove] = blackTimeRemaining;
10531 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
10532 appData.icsEngineAnalyze) && first.analysisSupport) {
10533 SendToProgram("analyze\n", &first);
10534 first.analyzing = TRUE;
10540 * Button procedures
10543 Reset(redraw, init)
10548 if (appData.debugMode) {
10549 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
10550 redraw, init, gameMode);
10552 CleanupTail(); // [HGM] vari: delete any stored variations
10553 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
10554 pausing = pauseExamInvalid = FALSE;
10555 startedFromSetupPosition = blackPlaysFirst = FALSE;
10557 whiteFlag = blackFlag = FALSE;
10558 userOfferedDraw = FALSE;
10559 hintRequested = bookRequested = FALSE;
10560 first.maybeThinking = FALSE;
10561 second.maybeThinking = FALSE;
10562 first.bookSuspend = FALSE; // [HGM] book
10563 second.bookSuspend = FALSE;
10564 thinkOutput[0] = NULLCHAR;
10565 lastHint[0] = NULLCHAR;
10566 ClearGameInfo(&gameInfo);
10567 gameInfo.variant = StringToVariant(appData.variant);
10568 ics_user_moved = ics_clock_paused = FALSE;
10569 ics_getting_history = H_FALSE;
10571 white_holding[0] = black_holding[0] = NULLCHAR;
10572 ClearProgramStats();
10573 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
10577 flipView = appData.flipView;
10578 ClearPremoveHighlights();
10579 gotPremove = FALSE;
10580 alarmSounded = FALSE;
10582 GameEnds(EndOfFile, NULL, GE_PLAYER);
10583 if(appData.serverMovesName != NULL) {
10584 /* [HGM] prepare to make moves file for broadcasting */
10585 clock_t t = clock();
10586 if(serverMoves != NULL) fclose(serverMoves);
10587 serverMoves = fopen(appData.serverMovesName, "r");
10588 if(serverMoves != NULL) {
10589 fclose(serverMoves);
10590 /* delay 15 sec before overwriting, so all clients can see end */
10591 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
10593 serverMoves = fopen(appData.serverMovesName, "w");
10597 gameMode = BeginningOfGame;
10599 if(appData.icsActive) gameInfo.variant = VariantNormal;
10600 currentMove = forwardMostMove = backwardMostMove = 0;
10601 InitPosition(redraw);
10602 for (i = 0; i < MAX_MOVES; i++) {
10603 if (commentList[i] != NULL) {
10604 free(commentList[i]);
10605 commentList[i] = NULL;
10609 timeRemaining[0][0] = whiteTimeRemaining;
10610 timeRemaining[1][0] = blackTimeRemaining;
10612 if (first.pr == NULL) {
10613 StartChessProgram(&first);
10616 InitChessProgram(&first, startedFromSetupPosition);
10619 DisplayMessage("", "");
10620 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10621 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
10628 if (!AutoPlayOneMove())
10630 if (matchMode || appData.timeDelay == 0)
10632 if (appData.timeDelay < 0)
10634 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
10643 int fromX, fromY, toX, toY;
10645 if (appData.debugMode) {
10646 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
10649 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
10652 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
10653 pvInfoList[currentMove].depth = programStats.depth;
10654 pvInfoList[currentMove].score = programStats.score;
10655 pvInfoList[currentMove].time = 0;
10656 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
10659 if (currentMove >= forwardMostMove) {
10660 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
10661 // gameMode = EndOfGame;
10662 // ModeHighlight();
10664 /* [AS] Clear current move marker at the end of a game */
10665 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
10670 toX = moveList[currentMove][2] - AAA;
10671 toY = moveList[currentMove][3] - ONE;
10673 if (moveList[currentMove][1] == '@') {
10674 if (appData.highlightLastMove) {
10675 SetHighlights(-1, -1, toX, toY);
10678 fromX = moveList[currentMove][0] - AAA;
10679 fromY = moveList[currentMove][1] - ONE;
10681 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
10683 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
10685 if (appData.highlightLastMove) {
10686 SetHighlights(fromX, fromY, toX, toY);
10689 DisplayMove(currentMove);
10690 SendMoveToProgram(currentMove++, &first);
10691 DisplayBothClocks();
10692 DrawPosition(FALSE, boards[currentMove]);
10693 // [HGM] PV info: always display, routine tests if empty
10694 DisplayComment(currentMove - 1, commentList[currentMove]);
10700 LoadGameOneMove(readAhead)
10701 ChessMove readAhead;
10703 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
10704 char promoChar = NULLCHAR;
10705 ChessMove moveType;
10706 char move[MSG_SIZ];
10709 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
10710 gameMode != AnalyzeMode && gameMode != Training) {
10715 yyboardindex = forwardMostMove;
10716 if (readAhead != EndOfFile) {
10717 moveType = readAhead;
10719 if (gameFileFP == NULL)
10721 moveType = (ChessMove) Myylex();
10725 switch (moveType) {
10727 if (appData.debugMode)
10728 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10731 /* append the comment but don't display it */
10732 AppendComment(currentMove, p, FALSE);
10735 case WhiteCapturesEnPassant:
10736 case BlackCapturesEnPassant:
10737 case WhitePromotion:
10738 case BlackPromotion:
10739 case WhiteNonPromotion:
10740 case BlackNonPromotion:
10742 case WhiteKingSideCastle:
10743 case WhiteQueenSideCastle:
10744 case BlackKingSideCastle:
10745 case BlackQueenSideCastle:
10746 case WhiteKingSideCastleWild:
10747 case WhiteQueenSideCastleWild:
10748 case BlackKingSideCastleWild:
10749 case BlackQueenSideCastleWild:
10751 case WhiteHSideCastleFR:
10752 case WhiteASideCastleFR:
10753 case BlackHSideCastleFR:
10754 case BlackASideCastleFR:
10756 if (appData.debugMode)
10757 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
10758 fromX = currentMoveString[0] - AAA;
10759 fromY = currentMoveString[1] - ONE;
10760 toX = currentMoveString[2] - AAA;
10761 toY = currentMoveString[3] - ONE;
10762 promoChar = currentMoveString[4];
10767 if (appData.debugMode)
10768 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
10769 fromX = moveType == WhiteDrop ?
10770 (int) CharToPiece(ToUpper(currentMoveString[0])) :
10771 (int) CharToPiece(ToLower(currentMoveString[0]));
10773 toX = currentMoveString[2] - AAA;
10774 toY = currentMoveString[3] - ONE;
10780 case GameUnfinished:
10781 if (appData.debugMode)
10782 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
10783 p = strchr(yy_text, '{');
10784 if (p == NULL) p = strchr(yy_text, '(');
10787 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
10789 q = strchr(p, *p == '{' ? '}' : ')');
10790 if (q != NULL) *q = NULLCHAR;
10793 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10794 GameEnds(moveType, p, GE_FILE);
10796 if (cmailMsgLoaded) {
10798 flipView = WhiteOnMove(currentMove);
10799 if (moveType == GameUnfinished) flipView = !flipView;
10800 if (appData.debugMode)
10801 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
10806 if (appData.debugMode)
10807 fprintf(debugFP, "Parser hit end of file\n");
10808 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10814 if (WhiteOnMove(currentMove)) {
10815 GameEnds(BlackWins, "Black mates", GE_FILE);
10817 GameEnds(WhiteWins, "White mates", GE_FILE);
10821 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10827 case MoveNumberOne:
10828 if (lastLoadGameStart == GNUChessGame) {
10829 /* GNUChessGames have numbers, but they aren't move numbers */
10830 if (appData.debugMode)
10831 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10832 yy_text, (int) moveType);
10833 return LoadGameOneMove(EndOfFile); /* tail recursion */
10835 /* else fall thru */
10840 /* Reached start of next game in file */
10841 if (appData.debugMode)
10842 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
10843 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10849 if (WhiteOnMove(currentMove)) {
10850 GameEnds(BlackWins, "Black mates", GE_FILE);
10852 GameEnds(WhiteWins, "White mates", GE_FILE);
10856 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10862 case PositionDiagram: /* should not happen; ignore */
10863 case ElapsedTime: /* ignore */
10864 case NAG: /* ignore */
10865 if (appData.debugMode)
10866 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10867 yy_text, (int) moveType);
10868 return LoadGameOneMove(EndOfFile); /* tail recursion */
10871 if (appData.testLegality) {
10872 if (appData.debugMode)
10873 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10874 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10875 (forwardMostMove / 2) + 1,
10876 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10877 DisplayError(move, 0);
10880 if (appData.debugMode)
10881 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10882 yy_text, currentMoveString);
10883 fromX = currentMoveString[0] - AAA;
10884 fromY = currentMoveString[1] - ONE;
10885 toX = currentMoveString[2] - AAA;
10886 toY = currentMoveString[3] - ONE;
10887 promoChar = currentMoveString[4];
10891 case AmbiguousMove:
10892 if (appData.debugMode)
10893 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10894 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10895 (forwardMostMove / 2) + 1,
10896 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10897 DisplayError(move, 0);
10902 case ImpossibleMove:
10903 if (appData.debugMode)
10904 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10905 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10906 (forwardMostMove / 2) + 1,
10907 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10908 DisplayError(move, 0);
10914 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10915 DrawPosition(FALSE, boards[currentMove]);
10916 DisplayBothClocks();
10917 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10918 DisplayComment(currentMove - 1, commentList[currentMove]);
10920 (void) StopLoadGameTimer();
10922 cmailOldMove = forwardMostMove;
10925 /* currentMoveString is set as a side-effect of yylex */
10927 thinkOutput[0] = NULLCHAR;
10928 MakeMove(fromX, fromY, toX, toY, promoChar);
10929 currentMove = forwardMostMove;
10934 /* Load the nth game from the given file */
10936 LoadGameFromFile(filename, n, title, useList)
10940 /*Boolean*/ int useList;
10945 if (strcmp(filename, "-") == 0) {
10949 f = fopen(filename, "rb");
10951 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10952 DisplayError(buf, errno);
10956 if (fseek(f, 0, 0) == -1) {
10957 /* f is not seekable; probably a pipe */
10960 if (useList && n == 0) {
10961 int error = GameListBuild(f);
10963 DisplayError(_("Cannot build game list"), error);
10964 } else if (!ListEmpty(&gameList) &&
10965 ((ListGame *) gameList.tailPred)->number > 1) {
10966 GameListPopUp(f, title);
10973 return LoadGame(f, n, title, FALSE);
10978 MakeRegisteredMove()
10980 int fromX, fromY, toX, toY;
10982 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10983 switch (cmailMoveType[lastLoadGameNumber - 1]) {
10986 if (appData.debugMode)
10987 fprintf(debugFP, "Restoring %s for game %d\n",
10988 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
10990 thinkOutput[0] = NULLCHAR;
10991 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
10992 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
10993 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
10994 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
10995 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
10996 promoChar = cmailMove[lastLoadGameNumber - 1][4];
10997 MakeMove(fromX, fromY, toX, toY, promoChar);
10998 ShowMove(fromX, fromY, toX, toY);
11000 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11007 if (WhiteOnMove(currentMove)) {
11008 GameEnds(BlackWins, "Black mates", GE_PLAYER);
11010 GameEnds(WhiteWins, "White mates", GE_PLAYER);
11015 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
11022 if (WhiteOnMove(currentMove)) {
11023 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11025 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11030 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11041 /* Wrapper around LoadGame for use when a Cmail message is loaded */
11043 CmailLoadGame(f, gameNumber, title, useList)
11051 if (gameNumber > nCmailGames) {
11052 DisplayError(_("No more games in this message"), 0);
11055 if (f == lastLoadGameFP) {
11056 int offset = gameNumber - lastLoadGameNumber;
11058 cmailMsg[0] = NULLCHAR;
11059 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11060 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11061 nCmailMovesRegistered--;
11063 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11064 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
11065 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
11068 if (! RegisterMove()) return FALSE;
11072 retVal = LoadGame(f, gameNumber, title, useList);
11074 /* Make move registered during previous look at this game, if any */
11075 MakeRegisteredMove();
11077 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
11078 commentList[currentMove]
11079 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
11080 DisplayComment(currentMove - 1, commentList[currentMove]);
11086 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
11091 int gameNumber = lastLoadGameNumber + offset;
11092 if (lastLoadGameFP == NULL) {
11093 DisplayError(_("No game has been loaded yet"), 0);
11096 if (gameNumber <= 0) {
11097 DisplayError(_("Can't back up any further"), 0);
11100 if (cmailMsgLoaded) {
11101 return CmailLoadGame(lastLoadGameFP, gameNumber,
11102 lastLoadGameTitle, lastLoadGameUseList);
11104 return LoadGame(lastLoadGameFP, gameNumber,
11105 lastLoadGameTitle, lastLoadGameUseList);
11109 int keys[EmptySquare+1];
11112 PositionMatches(Board b1, Board b2)
11115 switch(appData.searchMode) {
11116 case 1: return CompareWithRights(b1, b2);
11118 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11119 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
11123 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11124 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
11125 sum += keys[b1[r][f]] - keys[b2[r][f]];
11129 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11130 sum += keys[b1[r][f]] - keys[b2[r][f]];
11137 GameInfo dummyInfo;
11139 int GameContainsPosition(FILE *f, ListGame *lg)
11141 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
11142 int fromX, fromY, toX, toY;
11144 static int initDone=FALSE;
11147 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
11150 dummyInfo.variant = VariantNormal;
11151 FREE(dummyInfo.fen); dummyInfo.fen = NULL;
11152 dummyInfo.whiteRating = 0;
11153 dummyInfo.blackRating = 0;
11154 FREE(dummyInfo.date); dummyInfo.date = NULL;
11155 fseek(f, lg->offset, 0);
11157 CopyBoard(boards[scratch], initialPosition); // default start position
11159 yyboardindex = scratch + (plyNr&1);
11165 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
11167 ParsePGNTag(yy_text, &dummyInfo); // this has a bad memory leak...
11168 if(dummyInfo.fen) ParseFEN(boards[scratch], &btm, dummyInfo.fen), free(dummyInfo.fen), dummyInfo.fen = NULL;
11170 // do it ourselves avoiding malloc
11171 { char *p = yy_text+1, *q;
11172 while(!isdigit(*p) && !isalpha(*p)) p++;
11173 q = p; while(*p != ' ' && *p != '\t' && *p != '\n') p++;
11175 if(!StrCaseCmp(q, "Date") && (p = strchr(p+1, '"'))) { if(atoi(p+1) < appData.dateThreshold) return -1; } else
11176 if(!StrCaseCmp(q, "Variant") && (p = strchr(p+1, '"'))) dummyInfo.variant = StringToVariant(p+1); else
11177 if(!StrCaseCmp(q, "WhiteElo") && (p = strchr(p+1, '"'))) dummyInfo.whiteRating = atoi(p+1); else
11178 if(!StrCaseCmp(q, "BlackElo") && (p = strchr(p+1, '"'))) dummyInfo.blackRating = atoi(p+1); else
11179 if(!StrCaseCmp(q, "WhiteUSCF") && (p = strchr(p+1, '"'))) dummyInfo.whiteRating = atoi(p+1); else
11180 if(!StrCaseCmp(q, "BlackUSCF") && (p = strchr(p+1, '"'))) dummyInfo.blackRating = atoi(p+1); else
11181 if(!StrCaseCmp(q, "FEN") && (p = strchr(p+1, '"'))) ParseFEN(boards[scratch], &btm, p+1);
11189 if(plyNr) return -1; // after we have seen moves, this is for new game
11192 case AmbiguousMove: // we cannot reconstruct the game beyond these two
11193 case ImpossibleMove:
11194 case WhiteWins: // game ends here with these four
11197 case GameUnfinished:
11201 if(appData.testLegality) return -1;
11202 case WhiteCapturesEnPassant:
11203 case BlackCapturesEnPassant:
11204 case WhitePromotion:
11205 case BlackPromotion:
11206 case WhiteNonPromotion:
11207 case BlackNonPromotion:
11209 case WhiteKingSideCastle:
11210 case WhiteQueenSideCastle:
11211 case BlackKingSideCastle:
11212 case BlackQueenSideCastle:
11213 case WhiteKingSideCastleWild:
11214 case WhiteQueenSideCastleWild:
11215 case BlackKingSideCastleWild:
11216 case BlackQueenSideCastleWild:
11217 case WhiteHSideCastleFR:
11218 case WhiteASideCastleFR:
11219 case BlackHSideCastleFR:
11220 case BlackASideCastleFR:
11221 fromX = currentMoveString[0] - AAA;
11222 fromY = currentMoveString[1] - ONE;
11223 toX = currentMoveString[2] - AAA;
11224 toY = currentMoveString[3] - ONE;
11225 promoChar = currentMoveString[4];
11229 fromX = next == WhiteDrop ?
11230 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11231 (int) CharToPiece(ToLower(currentMoveString[0]));
11233 toX = currentMoveString[2] - AAA;
11234 toY = currentMoveString[3] - ONE;
11237 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
11238 if(plyNr == 0) { // but first figure out variant and initial position
11239 if(dummyInfo.variant != gameInfo.variant) return -1; // wrong variant
11240 if(appData.eloThreshold1 && (dummyInfo.whiteRating < appData.eloThreshold1 && dummyInfo.blackRating < appData.eloThreshold1)) return -1;
11241 if(appData.eloThreshold2 && (dummyInfo.whiteRating < appData.eloThreshold2 || dummyInfo.blackRating < appData.eloThreshold2)) return -1;
11242 if(appData.dateThreshold && (!dummyInfo.date || atoi(dummyInfo.date) < appData.dateThreshold)) return -1;
11243 if(btm) CopyBoard(boards[scratch+1], boards[scratch]), plyNr++;
11244 if(PositionMatches(boards[scratch + plyNr], boards[currentMove])) return plyNr;
11246 CopyBoard(boards[scratch + (plyNr+1&1)], boards[scratch + (plyNr&1)]);
11248 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch + (plyNr&1)]);
11249 if(PositionMatches(boards[scratch + (plyNr&1)], boards[currentMove])) return plyNr;
11253 /* Load the nth game from open file f */
11255 LoadGame(f, gameNumber, title, useList)
11263 int gn = gameNumber;
11264 ListGame *lg = NULL;
11265 int numPGNTags = 0;
11267 GameMode oldGameMode;
11268 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
11270 if (appData.debugMode)
11271 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
11273 if (gameMode == Training )
11274 SetTrainingModeOff();
11276 oldGameMode = gameMode;
11277 if (gameMode != BeginningOfGame) {
11278 Reset(FALSE, TRUE);
11282 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
11283 fclose(lastLoadGameFP);
11287 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
11290 fseek(f, lg->offset, 0);
11291 GameListHighlight(gameNumber);
11292 pos = lg->position;
11296 DisplayError(_("Game number out of range"), 0);
11301 if (fseek(f, 0, 0) == -1) {
11302 if (f == lastLoadGameFP ?
11303 gameNumber == lastLoadGameNumber + 1 :
11307 DisplayError(_("Can't seek on game file"), 0);
11312 lastLoadGameFP = f;
11313 lastLoadGameNumber = gameNumber;
11314 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
11315 lastLoadGameUseList = useList;
11319 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
11320 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
11321 lg->gameInfo.black);
11323 } else if (*title != NULLCHAR) {
11324 if (gameNumber > 1) {
11325 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
11328 DisplayTitle(title);
11332 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
11333 gameMode = PlayFromGameFile;
11337 currentMove = forwardMostMove = backwardMostMove = 0;
11338 CopyBoard(boards[0], initialPosition);
11342 * Skip the first gn-1 games in the file.
11343 * Also skip over anything that precedes an identifiable
11344 * start of game marker, to avoid being confused by
11345 * garbage at the start of the file. Currently
11346 * recognized start of game markers are the move number "1",
11347 * the pattern "gnuchess .* game", the pattern
11348 * "^[#;%] [^ ]* game file", and a PGN tag block.
11349 * A game that starts with one of the latter two patterns
11350 * will also have a move number 1, possibly
11351 * following a position diagram.
11352 * 5-4-02: Let's try being more lenient and allowing a game to
11353 * start with an unnumbered move. Does that break anything?
11355 cm = lastLoadGameStart = EndOfFile;
11357 yyboardindex = forwardMostMove;
11358 cm = (ChessMove) Myylex();
11361 if (cmailMsgLoaded) {
11362 nCmailGames = CMAIL_MAX_GAMES - gn;
11365 DisplayError(_("Game not found in file"), 0);
11372 lastLoadGameStart = cm;
11375 case MoveNumberOne:
11376 switch (lastLoadGameStart) {
11381 case MoveNumberOne:
11383 gn--; /* count this game */
11384 lastLoadGameStart = cm;
11393 switch (lastLoadGameStart) {
11396 case MoveNumberOne:
11398 gn--; /* count this game */
11399 lastLoadGameStart = cm;
11402 lastLoadGameStart = cm; /* game counted already */
11410 yyboardindex = forwardMostMove;
11411 cm = (ChessMove) Myylex();
11412 } while (cm == PGNTag || cm == Comment);
11419 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
11420 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
11421 != CMAIL_OLD_RESULT) {
11423 cmailResult[ CMAIL_MAX_GAMES
11424 - gn - 1] = CMAIL_OLD_RESULT;
11430 /* Only a NormalMove can be at the start of a game
11431 * without a position diagram. */
11432 if (lastLoadGameStart == EndOfFile ) {
11434 lastLoadGameStart = MoveNumberOne;
11443 if (appData.debugMode)
11444 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
11446 if (cm == XBoardGame) {
11447 /* Skip any header junk before position diagram and/or move 1 */
11449 yyboardindex = forwardMostMove;
11450 cm = (ChessMove) Myylex();
11452 if (cm == EndOfFile ||
11453 cm == GNUChessGame || cm == XBoardGame) {
11454 /* Empty game; pretend end-of-file and handle later */
11459 if (cm == MoveNumberOne || cm == PositionDiagram ||
11460 cm == PGNTag || cm == Comment)
11463 } else if (cm == GNUChessGame) {
11464 if (gameInfo.event != NULL) {
11465 free(gameInfo.event);
11467 gameInfo.event = StrSave(yy_text);
11470 startedFromSetupPosition = FALSE;
11471 while (cm == PGNTag) {
11472 if (appData.debugMode)
11473 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
11474 err = ParsePGNTag(yy_text, &gameInfo);
11475 if (!err) numPGNTags++;
11477 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
11478 if(gameInfo.variant != oldVariant) {
11479 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
11480 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
11481 InitPosition(TRUE);
11482 oldVariant = gameInfo.variant;
11483 if (appData.debugMode)
11484 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
11488 if (gameInfo.fen != NULL) {
11489 Board initial_position;
11490 startedFromSetupPosition = TRUE;
11491 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
11493 DisplayError(_("Bad FEN position in file"), 0);
11496 CopyBoard(boards[0], initial_position);
11497 if (blackPlaysFirst) {
11498 currentMove = forwardMostMove = backwardMostMove = 1;
11499 CopyBoard(boards[1], initial_position);
11500 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
11501 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
11502 timeRemaining[0][1] = whiteTimeRemaining;
11503 timeRemaining[1][1] = blackTimeRemaining;
11504 if (commentList[0] != NULL) {
11505 commentList[1] = commentList[0];
11506 commentList[0] = NULL;
11509 currentMove = forwardMostMove = backwardMostMove = 0;
11511 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
11513 initialRulePlies = FENrulePlies;
11514 for( i=0; i< nrCastlingRights; i++ )
11515 initialRights[i] = initial_position[CASTLING][i];
11517 yyboardindex = forwardMostMove;
11518 free(gameInfo.fen);
11519 gameInfo.fen = NULL;
11522 yyboardindex = forwardMostMove;
11523 cm = (ChessMove) Myylex();
11525 /* Handle comments interspersed among the tags */
11526 while (cm == Comment) {
11528 if (appData.debugMode)
11529 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11531 AppendComment(currentMove, p, FALSE);
11532 yyboardindex = forwardMostMove;
11533 cm = (ChessMove) Myylex();
11537 /* don't rely on existence of Event tag since if game was
11538 * pasted from clipboard the Event tag may not exist
11540 if (numPGNTags > 0){
11542 if (gameInfo.variant == VariantNormal) {
11543 VariantClass v = StringToVariant(gameInfo.event);
11544 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
11545 if(v < VariantShogi) gameInfo.variant = v;
11548 if( appData.autoDisplayTags ) {
11549 tags = PGNTags(&gameInfo);
11550 TagsPopUp(tags, CmailMsg());
11555 /* Make something up, but don't display it now */
11560 if (cm == PositionDiagram) {
11563 Board initial_position;
11565 if (appData.debugMode)
11566 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
11568 if (!startedFromSetupPosition) {
11570 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
11571 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
11582 initial_position[i][j++] = CharToPiece(*p);
11585 while (*p == ' ' || *p == '\t' ||
11586 *p == '\n' || *p == '\r') p++;
11588 if (strncmp(p, "black", strlen("black"))==0)
11589 blackPlaysFirst = TRUE;
11591 blackPlaysFirst = FALSE;
11592 startedFromSetupPosition = TRUE;
11594 CopyBoard(boards[0], initial_position);
11595 if (blackPlaysFirst) {
11596 currentMove = forwardMostMove = backwardMostMove = 1;
11597 CopyBoard(boards[1], initial_position);
11598 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
11599 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
11600 timeRemaining[0][1] = whiteTimeRemaining;
11601 timeRemaining[1][1] = blackTimeRemaining;
11602 if (commentList[0] != NULL) {
11603 commentList[1] = commentList[0];
11604 commentList[0] = NULL;
11607 currentMove = forwardMostMove = backwardMostMove = 0;
11610 yyboardindex = forwardMostMove;
11611 cm = (ChessMove) Myylex();
11614 if (first.pr == NoProc) {
11615 StartChessProgram(&first);
11617 InitChessProgram(&first, FALSE);
11618 SendToProgram("force\n", &first);
11619 if (startedFromSetupPosition) {
11620 SendBoard(&first, forwardMostMove);
11621 if (appData.debugMode) {
11622 fprintf(debugFP, "Load Game\n");
11624 DisplayBothClocks();
11627 /* [HGM] server: flag to write setup moves in broadcast file as one */
11628 loadFlag = appData.suppressLoadMoves;
11630 while (cm == Comment) {
11632 if (appData.debugMode)
11633 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11635 AppendComment(currentMove, p, FALSE);
11636 yyboardindex = forwardMostMove;
11637 cm = (ChessMove) Myylex();
11640 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
11641 cm == WhiteWins || cm == BlackWins ||
11642 cm == GameIsDrawn || cm == GameUnfinished) {
11643 DisplayMessage("", _("No moves in game"));
11644 if (cmailMsgLoaded) {
11645 if (appData.debugMode)
11646 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
11650 DrawPosition(FALSE, boards[currentMove]);
11651 DisplayBothClocks();
11652 gameMode = EditGame;
11659 // [HGM] PV info: routine tests if comment empty
11660 if (!matchMode && (pausing || appData.timeDelay != 0)) {
11661 DisplayComment(currentMove - 1, commentList[currentMove]);
11663 if (!matchMode && appData.timeDelay != 0)
11664 DrawPosition(FALSE, boards[currentMove]);
11666 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
11667 programStats.ok_to_send = 1;
11670 /* if the first token after the PGN tags is a move
11671 * and not move number 1, retrieve it from the parser
11673 if (cm != MoveNumberOne)
11674 LoadGameOneMove(cm);
11676 /* load the remaining moves from the file */
11677 while (LoadGameOneMove(EndOfFile)) {
11678 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
11679 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
11682 /* rewind to the start of the game */
11683 currentMove = backwardMostMove;
11685 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11687 if (oldGameMode == AnalyzeFile ||
11688 oldGameMode == AnalyzeMode) {
11689 AnalyzeFileEvent();
11692 if (!matchMode && pos >= 0) {
11693 ToNrEvent(pos); // [HGM] no autoplay if selected on position
11695 if (matchMode || appData.timeDelay == 0) {
11697 } else if (appData.timeDelay > 0) {
11698 AutoPlayGameLoop();
11701 if (appData.debugMode)
11702 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
11704 loadFlag = 0; /* [HGM] true game starts */
11708 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
11710 ReloadPosition(offset)
11713 int positionNumber = lastLoadPositionNumber + offset;
11714 if (lastLoadPositionFP == NULL) {
11715 DisplayError(_("No position has been loaded yet"), 0);
11718 if (positionNumber <= 0) {
11719 DisplayError(_("Can't back up any further"), 0);
11722 return LoadPosition(lastLoadPositionFP, positionNumber,
11723 lastLoadPositionTitle);
11726 /* Load the nth position from the given file */
11728 LoadPositionFromFile(filename, n, title)
11736 if (strcmp(filename, "-") == 0) {
11737 return LoadPosition(stdin, n, "stdin");
11739 f = fopen(filename, "rb");
11741 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11742 DisplayError(buf, errno);
11745 return LoadPosition(f, n, title);
11750 /* Load the nth position from the given open file, and close it */
11752 LoadPosition(f, positionNumber, title)
11754 int positionNumber;
11757 char *p, line[MSG_SIZ];
11758 Board initial_position;
11759 int i, j, fenMode, pn;
11761 if (gameMode == Training )
11762 SetTrainingModeOff();
11764 if (gameMode != BeginningOfGame) {
11765 Reset(FALSE, TRUE);
11767 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
11768 fclose(lastLoadPositionFP);
11770 if (positionNumber == 0) positionNumber = 1;
11771 lastLoadPositionFP = f;
11772 lastLoadPositionNumber = positionNumber;
11773 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
11774 if (first.pr == NoProc) {
11775 StartChessProgram(&first);
11776 InitChessProgram(&first, FALSE);
11778 pn = positionNumber;
11779 if (positionNumber < 0) {
11780 /* Negative position number means to seek to that byte offset */
11781 if (fseek(f, -positionNumber, 0) == -1) {
11782 DisplayError(_("Can't seek on position file"), 0);
11787 if (fseek(f, 0, 0) == -1) {
11788 if (f == lastLoadPositionFP ?
11789 positionNumber == lastLoadPositionNumber + 1 :
11790 positionNumber == 1) {
11793 DisplayError(_("Can't seek on position file"), 0);
11798 /* See if this file is FEN or old-style xboard */
11799 if (fgets(line, MSG_SIZ, f) == NULL) {
11800 DisplayError(_("Position not found in file"), 0);
11803 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
11804 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
11807 if (fenMode || line[0] == '#') pn--;
11809 /* skip positions before number pn */
11810 if (fgets(line, MSG_SIZ, f) == NULL) {
11812 DisplayError(_("Position not found in file"), 0);
11815 if (fenMode || line[0] == '#') pn--;
11820 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
11821 DisplayError(_("Bad FEN position in file"), 0);
11825 (void) fgets(line, MSG_SIZ, f);
11826 (void) fgets(line, MSG_SIZ, f);
11828 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
11829 (void) fgets(line, MSG_SIZ, f);
11830 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
11833 initial_position[i][j++] = CharToPiece(*p);
11837 blackPlaysFirst = FALSE;
11839 (void) fgets(line, MSG_SIZ, f);
11840 if (strncmp(line, "black", strlen("black"))==0)
11841 blackPlaysFirst = TRUE;
11844 startedFromSetupPosition = TRUE;
11846 SendToProgram("force\n", &first);
11847 CopyBoard(boards[0], initial_position);
11848 if (blackPlaysFirst) {
11849 currentMove = forwardMostMove = backwardMostMove = 1;
11850 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
11851 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
11852 CopyBoard(boards[1], initial_position);
11853 DisplayMessage("", _("Black to play"));
11855 currentMove = forwardMostMove = backwardMostMove = 0;
11856 DisplayMessage("", _("White to play"));
11858 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
11859 SendBoard(&first, forwardMostMove);
11860 if (appData.debugMode) {
11862 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
11863 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
11864 fprintf(debugFP, "Load Position\n");
11867 if (positionNumber > 1) {
11868 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
11869 DisplayTitle(line);
11871 DisplayTitle(title);
11873 gameMode = EditGame;
11876 timeRemaining[0][1] = whiteTimeRemaining;
11877 timeRemaining[1][1] = blackTimeRemaining;
11878 DrawPosition(FALSE, boards[currentMove]);
11885 CopyPlayerNameIntoFileName(dest, src)
11888 while (*src != NULLCHAR && *src != ',') {
11893 *(*dest)++ = *src++;
11898 char *DefaultFileName(ext)
11901 static char def[MSG_SIZ];
11904 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
11906 CopyPlayerNameIntoFileName(&p, gameInfo.white);
11908 CopyPlayerNameIntoFileName(&p, gameInfo.black);
11910 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
11917 /* Save the current game to the given file */
11919 SaveGameToFile(filename, append)
11927 if (strcmp(filename, "-") == 0) {
11928 return SaveGame(stdout, 0, NULL);
11930 f = fopen(filename, append ? "a" : "w");
11932 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11933 DisplayError(buf, errno);
11936 safeStrCpy(buf, lastMsg, MSG_SIZ);
11937 DisplayMessage(_("Waiting for access to save file"), "");
11938 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
11939 DisplayMessage(_("Saving game"), "");
11940 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError("Bad Seek", errno); // better safe than sorry...
11941 result = SaveGame(f, 0, NULL);
11942 DisplayMessage(buf, "");
11952 static char buf[MSG_SIZ];
11955 p = strchr(str, ' ');
11956 if (p == NULL) return str;
11957 strncpy(buf, str, p - str);
11958 buf[p - str] = NULLCHAR;
11962 #define PGN_MAX_LINE 75
11964 #define PGN_SIDE_WHITE 0
11965 #define PGN_SIDE_BLACK 1
11968 static int FindFirstMoveOutOfBook( int side )
11972 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
11973 int index = backwardMostMove;
11974 int has_book_hit = 0;
11976 if( (index % 2) != side ) {
11980 while( index < forwardMostMove ) {
11981 /* Check to see if engine is in book */
11982 int depth = pvInfoList[index].depth;
11983 int score = pvInfoList[index].score;
11989 else if( score == 0 && depth == 63 ) {
11990 in_book = 1; /* Zappa */
11992 else if( score == 2 && depth == 99 ) {
11993 in_book = 1; /* Abrok */
11996 has_book_hit += in_book;
12012 void GetOutOfBookInfo( char * buf )
12016 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12018 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
12019 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
12023 if( oob[0] >= 0 || oob[1] >= 0 ) {
12024 for( i=0; i<2; i++ ) {
12028 if( i > 0 && oob[0] >= 0 ) {
12029 strcat( buf, " " );
12032 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
12033 sprintf( buf+strlen(buf), "%s%.2f",
12034 pvInfoList[idx].score >= 0 ? "+" : "",
12035 pvInfoList[idx].score / 100.0 );
12041 /* Save game in PGN style and close the file */
12046 int i, offset, linelen, newblock;
12050 int movelen, numlen, blank;
12051 char move_buffer[100]; /* [AS] Buffer for move+PV info */
12053 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12055 tm = time((time_t *) NULL);
12057 PrintPGNTags(f, &gameInfo);
12059 if (backwardMostMove > 0 || startedFromSetupPosition) {
12060 char *fen = PositionToFEN(backwardMostMove, NULL);
12061 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
12062 fprintf(f, "\n{--------------\n");
12063 PrintPosition(f, backwardMostMove);
12064 fprintf(f, "--------------}\n");
12068 /* [AS] Out of book annotation */
12069 if( appData.saveOutOfBookInfo ) {
12072 GetOutOfBookInfo( buf );
12074 if( buf[0] != '\0' ) {
12075 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
12082 i = backwardMostMove;
12086 while (i < forwardMostMove) {
12087 /* Print comments preceding this move */
12088 if (commentList[i] != NULL) {
12089 if (linelen > 0) fprintf(f, "\n");
12090 fprintf(f, "%s", commentList[i]);
12095 /* Format move number */
12097 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
12100 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
12102 numtext[0] = NULLCHAR;
12104 numlen = strlen(numtext);
12107 /* Print move number */
12108 blank = linelen > 0 && numlen > 0;
12109 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
12118 fprintf(f, "%s", numtext);
12122 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
12123 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
12126 blank = linelen > 0 && movelen > 0;
12127 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12136 fprintf(f, "%s", move_buffer);
12137 linelen += movelen;
12139 /* [AS] Add PV info if present */
12140 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
12141 /* [HGM] add time */
12142 char buf[MSG_SIZ]; int seconds;
12144 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
12150 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
12153 seconds = (seconds + 4)/10; // round to full seconds
12155 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
12157 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
12160 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
12161 pvInfoList[i].score >= 0 ? "+" : "",
12162 pvInfoList[i].score / 100.0,
12163 pvInfoList[i].depth,
12166 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
12168 /* Print score/depth */
12169 blank = linelen > 0 && movelen > 0;
12170 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12179 fprintf(f, "%s", move_buffer);
12180 linelen += movelen;
12186 /* Start a new line */
12187 if (linelen > 0) fprintf(f, "\n");
12189 /* Print comments after last move */
12190 if (commentList[i] != NULL) {
12191 fprintf(f, "%s\n", commentList[i]);
12195 if (gameInfo.resultDetails != NULL &&
12196 gameInfo.resultDetails[0] != NULLCHAR) {
12197 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
12198 PGNResult(gameInfo.result));
12200 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12204 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12208 /* Save game in old style and close the file */
12210 SaveGameOldStyle(f)
12216 tm = time((time_t *) NULL);
12218 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
12221 if (backwardMostMove > 0 || startedFromSetupPosition) {
12222 fprintf(f, "\n[--------------\n");
12223 PrintPosition(f, backwardMostMove);
12224 fprintf(f, "--------------]\n");
12229 i = backwardMostMove;
12230 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12232 while (i < forwardMostMove) {
12233 if (commentList[i] != NULL) {
12234 fprintf(f, "[%s]\n", commentList[i]);
12237 if ((i % 2) == 1) {
12238 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
12241 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
12243 if (commentList[i] != NULL) {
12247 if (i >= forwardMostMove) {
12251 fprintf(f, "%s\n", parseList[i]);
12256 if (commentList[i] != NULL) {
12257 fprintf(f, "[%s]\n", commentList[i]);
12260 /* This isn't really the old style, but it's close enough */
12261 if (gameInfo.resultDetails != NULL &&
12262 gameInfo.resultDetails[0] != NULLCHAR) {
12263 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
12264 gameInfo.resultDetails);
12266 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12273 /* Save the current game to open file f and close the file */
12275 SaveGame(f, dummy, dummy2)
12280 if (gameMode == EditPosition) EditPositionDone(TRUE);
12281 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12282 if (appData.oldSaveStyle)
12283 return SaveGameOldStyle(f);
12285 return SaveGamePGN(f);
12288 /* Save the current position to the given file */
12290 SavePositionToFile(filename)
12296 if (strcmp(filename, "-") == 0) {
12297 return SavePosition(stdout, 0, NULL);
12299 f = fopen(filename, "a");
12301 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12302 DisplayError(buf, errno);
12305 safeStrCpy(buf, lastMsg, MSG_SIZ);
12306 DisplayMessage(_("Waiting for access to save file"), "");
12307 flock(fileno(f), LOCK_EX); // [HGM] lock
12308 DisplayMessage(_("Saving position"), "");
12309 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
12310 SavePosition(f, 0, NULL);
12311 DisplayMessage(buf, "");
12317 /* Save the current position to the given open file and close the file */
12319 SavePosition(f, dummy, dummy2)
12327 if (gameMode == EditPosition) EditPositionDone(TRUE);
12328 if (appData.oldSaveStyle) {
12329 tm = time((time_t *) NULL);
12331 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
12333 fprintf(f, "[--------------\n");
12334 PrintPosition(f, currentMove);
12335 fprintf(f, "--------------]\n");
12337 fen = PositionToFEN(currentMove, NULL);
12338 fprintf(f, "%s\n", fen);
12346 ReloadCmailMsgEvent(unregister)
12350 static char *inFilename = NULL;
12351 static char *outFilename;
12353 struct stat inbuf, outbuf;
12356 /* Any registered moves are unregistered if unregister is set, */
12357 /* i.e. invoked by the signal handler */
12359 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12360 cmailMoveRegistered[i] = FALSE;
12361 if (cmailCommentList[i] != NULL) {
12362 free(cmailCommentList[i]);
12363 cmailCommentList[i] = NULL;
12366 nCmailMovesRegistered = 0;
12369 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12370 cmailResult[i] = CMAIL_NOT_RESULT;
12374 if (inFilename == NULL) {
12375 /* Because the filenames are static they only get malloced once */
12376 /* and they never get freed */
12377 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
12378 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
12380 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
12381 sprintf(outFilename, "%s.out", appData.cmailGameName);
12384 status = stat(outFilename, &outbuf);
12386 cmailMailedMove = FALSE;
12388 status = stat(inFilename, &inbuf);
12389 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
12392 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
12393 counts the games, notes how each one terminated, etc.
12395 It would be nice to remove this kludge and instead gather all
12396 the information while building the game list. (And to keep it
12397 in the game list nodes instead of having a bunch of fixed-size
12398 parallel arrays.) Note this will require getting each game's
12399 termination from the PGN tags, as the game list builder does
12400 not process the game moves. --mann
12402 cmailMsgLoaded = TRUE;
12403 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
12405 /* Load first game in the file or popup game menu */
12406 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
12408 #endif /* !WIN32 */
12416 char string[MSG_SIZ];
12418 if ( cmailMailedMove
12419 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
12420 return TRUE; /* Allow free viewing */
12423 /* Unregister move to ensure that we don't leave RegisterMove */
12424 /* with the move registered when the conditions for registering no */
12426 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12427 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12428 nCmailMovesRegistered --;
12430 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
12432 free(cmailCommentList[lastLoadGameNumber - 1]);
12433 cmailCommentList[lastLoadGameNumber - 1] = NULL;
12437 if (cmailOldMove == -1) {
12438 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
12442 if (currentMove > cmailOldMove + 1) {
12443 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
12447 if (currentMove < cmailOldMove) {
12448 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
12452 if (forwardMostMove > currentMove) {
12453 /* Silently truncate extra moves */
12457 if ( (currentMove == cmailOldMove + 1)
12458 || ( (currentMove == cmailOldMove)
12459 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
12460 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
12461 if (gameInfo.result != GameUnfinished) {
12462 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
12465 if (commentList[currentMove] != NULL) {
12466 cmailCommentList[lastLoadGameNumber - 1]
12467 = StrSave(commentList[currentMove]);
12469 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
12471 if (appData.debugMode)
12472 fprintf(debugFP, "Saving %s for game %d\n",
12473 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12475 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
12477 f = fopen(string, "w");
12478 if (appData.oldSaveStyle) {
12479 SaveGameOldStyle(f); /* also closes the file */
12481 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
12482 f = fopen(string, "w");
12483 SavePosition(f, 0, NULL); /* also closes the file */
12485 fprintf(f, "{--------------\n");
12486 PrintPosition(f, currentMove);
12487 fprintf(f, "--------------}\n\n");
12489 SaveGame(f, 0, NULL); /* also closes the file*/
12492 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
12493 nCmailMovesRegistered ++;
12494 } else if (nCmailGames == 1) {
12495 DisplayError(_("You have not made a move yet"), 0);
12506 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
12507 FILE *commandOutput;
12508 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
12509 int nBytes = 0; /* Suppress warnings on uninitialized variables */
12515 if (! cmailMsgLoaded) {
12516 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
12520 if (nCmailGames == nCmailResults) {
12521 DisplayError(_("No unfinished games"), 0);
12525 #if CMAIL_PROHIBIT_REMAIL
12526 if (cmailMailedMove) {
12527 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);
12528 DisplayError(msg, 0);
12533 if (! (cmailMailedMove || RegisterMove())) return;
12535 if ( cmailMailedMove
12536 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
12537 snprintf(string, MSG_SIZ, partCommandString,
12538 appData.debugMode ? " -v" : "", appData.cmailGameName);
12539 commandOutput = popen(string, "r");
12541 if (commandOutput == NULL) {
12542 DisplayError(_("Failed to invoke cmail"), 0);
12544 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
12545 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
12547 if (nBuffers > 1) {
12548 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
12549 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
12550 nBytes = MSG_SIZ - 1;
12552 (void) memcpy(msg, buffer, nBytes);
12554 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
12556 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
12557 cmailMailedMove = TRUE; /* Prevent >1 moves */
12560 for (i = 0; i < nCmailGames; i ++) {
12561 if (cmailResult[i] == CMAIL_NOT_RESULT) {
12566 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
12568 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
12570 appData.cmailGameName,
12572 LoadGameFromFile(buffer, 1, buffer, FALSE);
12573 cmailMsgLoaded = FALSE;
12577 DisplayInformation(msg);
12578 pclose(commandOutput);
12581 if ((*cmailMsg) != '\0') {
12582 DisplayInformation(cmailMsg);
12587 #endif /* !WIN32 */
12596 int prependComma = 0;
12598 char string[MSG_SIZ]; /* Space for game-list */
12601 if (!cmailMsgLoaded) return "";
12603 if (cmailMailedMove) {
12604 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
12606 /* Create a list of games left */
12607 snprintf(string, MSG_SIZ, "[");
12608 for (i = 0; i < nCmailGames; i ++) {
12609 if (! ( cmailMoveRegistered[i]
12610 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
12611 if (prependComma) {
12612 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
12614 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
12618 strcat(string, number);
12621 strcat(string, "]");
12623 if (nCmailMovesRegistered + nCmailResults == 0) {
12624 switch (nCmailGames) {
12626 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
12630 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
12634 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
12639 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
12641 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
12646 if (nCmailResults == nCmailGames) {
12647 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
12649 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
12654 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
12666 if (gameMode == Training)
12667 SetTrainingModeOff();
12670 cmailMsgLoaded = FALSE;
12671 if (appData.icsActive) {
12672 SendToICS(ics_prefix);
12673 SendToICS("refresh\n");
12683 /* Give up on clean exit */
12687 /* Keep trying for clean exit */
12691 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
12693 if (telnetISR != NULL) {
12694 RemoveInputSource(telnetISR);
12696 if (icsPR != NoProc) {
12697 DestroyChildProcess(icsPR, TRUE);
12700 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
12701 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
12703 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
12704 /* make sure this other one finishes before killing it! */
12705 if(endingGame) { int count = 0;
12706 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
12707 while(endingGame && count++ < 10) DoSleep(1);
12708 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
12711 /* Kill off chess programs */
12712 if (first.pr != NoProc) {
12715 DoSleep( appData.delayBeforeQuit );
12716 SendToProgram("quit\n", &first);
12717 DoSleep( appData.delayAfterQuit );
12718 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
12720 if (second.pr != NoProc) {
12721 DoSleep( appData.delayBeforeQuit );
12722 SendToProgram("quit\n", &second);
12723 DoSleep( appData.delayAfterQuit );
12724 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
12726 if (first.isr != NULL) {
12727 RemoveInputSource(first.isr);
12729 if (second.isr != NULL) {
12730 RemoveInputSource(second.isr);
12733 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
12734 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
12736 ShutDownFrontEnd();
12743 if (appData.debugMode)
12744 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
12748 if (gameMode == MachinePlaysWhite ||
12749 gameMode == MachinePlaysBlack) {
12752 DisplayBothClocks();
12754 if (gameMode == PlayFromGameFile) {
12755 if (appData.timeDelay >= 0)
12756 AutoPlayGameLoop();
12757 } else if (gameMode == IcsExamining && pauseExamInvalid) {
12758 Reset(FALSE, TRUE);
12759 SendToICS(ics_prefix);
12760 SendToICS("refresh\n");
12761 } else if (currentMove < forwardMostMove) {
12762 ForwardInner(forwardMostMove);
12764 pauseExamInvalid = FALSE;
12766 switch (gameMode) {
12770 pauseExamForwardMostMove = forwardMostMove;
12771 pauseExamInvalid = FALSE;
12774 case IcsPlayingWhite:
12775 case IcsPlayingBlack:
12779 case PlayFromGameFile:
12780 (void) StopLoadGameTimer();
12784 case BeginningOfGame:
12785 if (appData.icsActive) return;
12786 /* else fall through */
12787 case MachinePlaysWhite:
12788 case MachinePlaysBlack:
12789 case TwoMachinesPlay:
12790 if (forwardMostMove == 0)
12791 return; /* don't pause if no one has moved */
12792 if ((gameMode == MachinePlaysWhite &&
12793 !WhiteOnMove(forwardMostMove)) ||
12794 (gameMode == MachinePlaysBlack &&
12795 WhiteOnMove(forwardMostMove))) {
12808 char title[MSG_SIZ];
12810 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
12811 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
12813 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
12814 WhiteOnMove(currentMove - 1) ? " " : ".. ",
12815 parseList[currentMove - 1]);
12818 EditCommentPopUp(currentMove, title, commentList[currentMove]);
12825 char *tags = PGNTags(&gameInfo);
12827 EditTagsPopUp(tags, NULL);
12834 if (appData.noChessProgram || gameMode == AnalyzeMode)
12837 if (gameMode != AnalyzeFile) {
12838 if (!appData.icsEngineAnalyze) {
12840 if (gameMode != EditGame) return;
12842 ResurrectChessProgram();
12843 SendToProgram("analyze\n", &first);
12844 first.analyzing = TRUE;
12845 /*first.maybeThinking = TRUE;*/
12846 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12847 EngineOutputPopUp();
12849 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
12854 StartAnalysisClock();
12855 GetTimeMark(&lastNodeCountTime);
12862 if (appData.noChessProgram || gameMode == AnalyzeFile)
12865 if (gameMode != AnalyzeMode) {
12867 if (gameMode != EditGame) return;
12868 ResurrectChessProgram();
12869 SendToProgram("analyze\n", &first);
12870 first.analyzing = TRUE;
12871 /*first.maybeThinking = TRUE;*/
12872 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12873 EngineOutputPopUp();
12875 gameMode = AnalyzeFile;
12880 StartAnalysisClock();
12881 GetTimeMark(&lastNodeCountTime);
12886 MachineWhiteEvent()
12889 char *bookHit = NULL;
12891 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
12895 if (gameMode == PlayFromGameFile ||
12896 gameMode == TwoMachinesPlay ||
12897 gameMode == Training ||
12898 gameMode == AnalyzeMode ||
12899 gameMode == EndOfGame)
12902 if (gameMode == EditPosition)
12903 EditPositionDone(TRUE);
12905 if (!WhiteOnMove(currentMove)) {
12906 DisplayError(_("It is not White's turn"), 0);
12910 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
12913 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12914 gameMode == AnalyzeFile)
12917 ResurrectChessProgram(); /* in case it isn't running */
12918 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
12919 gameMode = MachinePlaysWhite;
12922 gameMode = MachinePlaysWhite;
12926 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12928 if (first.sendName) {
12929 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
12930 SendToProgram(buf, &first);
12932 if (first.sendTime) {
12933 if (first.useColors) {
12934 SendToProgram("black\n", &first); /*gnu kludge*/
12936 SendTimeRemaining(&first, TRUE);
12938 if (first.useColors) {
12939 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
12941 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12942 SetMachineThinkingEnables();
12943 first.maybeThinking = TRUE;
12947 if (appData.autoFlipView && !flipView) {
12948 flipView = !flipView;
12949 DrawPosition(FALSE, NULL);
12950 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12953 if(bookHit) { // [HGM] book: simulate book reply
12954 static char bookMove[MSG_SIZ]; // a bit generous?
12956 programStats.nodes = programStats.depth = programStats.time =
12957 programStats.score = programStats.got_only_move = 0;
12958 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12960 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12961 strcat(bookMove, bookHit);
12962 HandleMachineMove(bookMove, &first);
12967 MachineBlackEvent()
12970 char *bookHit = NULL;
12972 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
12976 if (gameMode == PlayFromGameFile ||
12977 gameMode == TwoMachinesPlay ||
12978 gameMode == Training ||
12979 gameMode == AnalyzeMode ||
12980 gameMode == EndOfGame)
12983 if (gameMode == EditPosition)
12984 EditPositionDone(TRUE);
12986 if (WhiteOnMove(currentMove)) {
12987 DisplayError(_("It is not Black's turn"), 0);
12991 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
12994 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12995 gameMode == AnalyzeFile)
12998 ResurrectChessProgram(); /* in case it isn't running */
12999 gameMode = MachinePlaysBlack;
13003 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
13005 if (first.sendName) {
13006 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
13007 SendToProgram(buf, &first);
13009 if (first.sendTime) {
13010 if (first.useColors) {
13011 SendToProgram("white\n", &first); /*gnu kludge*/
13013 SendTimeRemaining(&first, FALSE);
13015 if (first.useColors) {
13016 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
13018 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13019 SetMachineThinkingEnables();
13020 first.maybeThinking = TRUE;
13023 if (appData.autoFlipView && flipView) {
13024 flipView = !flipView;
13025 DrawPosition(FALSE, NULL);
13026 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13028 if(bookHit) { // [HGM] book: simulate book reply
13029 static char bookMove[MSG_SIZ]; // a bit generous?
13031 programStats.nodes = programStats.depth = programStats.time =
13032 programStats.score = programStats.got_only_move = 0;
13033 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13035 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13036 strcat(bookMove, bookHit);
13037 HandleMachineMove(bookMove, &first);
13043 DisplayTwoMachinesTitle()
13046 if (appData.matchGames > 0) {
13047 if(appData.tourneyFile[0]) {
13048 snprintf(buf, MSG_SIZ, "%s vs. %s (%d/%d%s)",
13049 gameInfo.white, gameInfo.black,
13050 nextGame+1, appData.matchGames+1,
13051 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
13053 if (first.twoMachinesColor[0] == 'w') {
13054 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
13055 gameInfo.white, gameInfo.black,
13056 first.matchWins, second.matchWins,
13057 matchGame - 1 - (first.matchWins + second.matchWins));
13059 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
13060 gameInfo.white, gameInfo.black,
13061 second.matchWins, first.matchWins,
13062 matchGame - 1 - (first.matchWins + second.matchWins));
13065 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
13071 SettingsMenuIfReady()
13073 if (second.lastPing != second.lastPong) {
13074 DisplayMessage("", _("Waiting for second chess program"));
13075 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
13079 DisplayMessage("", "");
13080 SettingsPopUp(&second);
13084 WaitForEngine(ChessProgramState *cps, DelayedEventCallback retry)
13087 if (cps->pr == NULL) {
13088 StartChessProgram(cps);
13089 if (cps->protocolVersion == 1) {
13092 /* kludge: allow timeout for initial "feature" command */
13094 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), cps->which);
13095 DisplayMessage("", buf);
13096 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
13104 TwoMachinesEvent P((void))
13108 ChessProgramState *onmove;
13109 char *bookHit = NULL;
13110 static int stalling = 0;
13114 if (appData.noChessProgram) return;
13116 switch (gameMode) {
13117 case TwoMachinesPlay:
13119 case MachinePlaysWhite:
13120 case MachinePlaysBlack:
13121 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13122 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13126 case BeginningOfGame:
13127 case PlayFromGameFile:
13130 if (gameMode != EditGame) return;
13133 EditPositionDone(TRUE);
13144 // forwardMostMove = currentMove;
13145 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
13147 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
13149 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
13150 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
13151 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13155 InitChessProgram(&second, FALSE); // unbalances ping of second engine
13156 SendToProgram("force\n", &second);
13158 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13161 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
13162 if(appData.matchPause>10000 || appData.matchPause<10)
13163 appData.matchPause = 10000; /* [HGM] make pause adjustable */
13164 wait = SubtractTimeMarks(&now, &pauseStart);
13165 if(wait < appData.matchPause) {
13166 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
13170 DisplayMessage("", "");
13171 if (startedFromSetupPosition) {
13172 SendBoard(&second, backwardMostMove);
13173 if (appData.debugMode) {
13174 fprintf(debugFP, "Two Machines\n");
13177 for (i = backwardMostMove; i < forwardMostMove; i++) {
13178 SendMoveToProgram(i, &second);
13181 gameMode = TwoMachinesPlay;
13183 ModeHighlight(); // [HGM] logo: this triggers display update of logos
13185 DisplayTwoMachinesTitle();
13187 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
13192 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
13193 SendToProgram(first.computerString, &first);
13194 if (first.sendName) {
13195 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
13196 SendToProgram(buf, &first);
13198 SendToProgram(second.computerString, &second);
13199 if (second.sendName) {
13200 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
13201 SendToProgram(buf, &second);
13205 if (!first.sendTime || !second.sendTime) {
13206 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13207 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13209 if (onmove->sendTime) {
13210 if (onmove->useColors) {
13211 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
13213 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
13215 if (onmove->useColors) {
13216 SendToProgram(onmove->twoMachinesColor, onmove);
13218 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
13219 // SendToProgram("go\n", onmove);
13220 onmove->maybeThinking = TRUE;
13221 SetMachineThinkingEnables();
13225 if(bookHit) { // [HGM] book: simulate book reply
13226 static char bookMove[MSG_SIZ]; // a bit generous?
13228 programStats.nodes = programStats.depth = programStats.time =
13229 programStats.score = programStats.got_only_move = 0;
13230 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13232 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13233 strcat(bookMove, bookHit);
13234 savedMessage = bookMove; // args for deferred call
13235 savedState = onmove;
13236 ScheduleDelayedEvent(DeferredBookMove, 1);
13243 if (gameMode == Training) {
13244 SetTrainingModeOff();
13245 gameMode = PlayFromGameFile;
13246 DisplayMessage("", _("Training mode off"));
13248 gameMode = Training;
13249 animateTraining = appData.animate;
13251 /* make sure we are not already at the end of the game */
13252 if (currentMove < forwardMostMove) {
13253 SetTrainingModeOn();
13254 DisplayMessage("", _("Training mode on"));
13256 gameMode = PlayFromGameFile;
13257 DisplayError(_("Already at end of game"), 0);
13266 if (!appData.icsActive) return;
13267 switch (gameMode) {
13268 case IcsPlayingWhite:
13269 case IcsPlayingBlack:
13272 case BeginningOfGame:
13280 EditPositionDone(TRUE);
13293 gameMode = IcsIdle;
13304 switch (gameMode) {
13306 SetTrainingModeOff();
13308 case MachinePlaysWhite:
13309 case MachinePlaysBlack:
13310 case BeginningOfGame:
13311 SendToProgram("force\n", &first);
13312 SetUserThinkingEnables();
13314 case PlayFromGameFile:
13315 (void) StopLoadGameTimer();
13316 if (gameFileFP != NULL) {
13321 EditPositionDone(TRUE);
13326 SendToProgram("force\n", &first);
13328 case TwoMachinesPlay:
13329 GameEnds(EndOfFile, NULL, GE_PLAYER);
13330 ResurrectChessProgram();
13331 SetUserThinkingEnables();
13334 ResurrectChessProgram();
13336 case IcsPlayingBlack:
13337 case IcsPlayingWhite:
13338 DisplayError(_("Warning: You are still playing a game"), 0);
13341 DisplayError(_("Warning: You are still observing a game"), 0);
13344 DisplayError(_("Warning: You are still examining a game"), 0);
13355 first.offeredDraw = second.offeredDraw = 0;
13357 if (gameMode == PlayFromGameFile) {
13358 whiteTimeRemaining = timeRemaining[0][currentMove];
13359 blackTimeRemaining = timeRemaining[1][currentMove];
13363 if (gameMode == MachinePlaysWhite ||
13364 gameMode == MachinePlaysBlack ||
13365 gameMode == TwoMachinesPlay ||
13366 gameMode == EndOfGame) {
13367 i = forwardMostMove;
13368 while (i > currentMove) {
13369 SendToProgram("undo\n", &first);
13372 whiteTimeRemaining = timeRemaining[0][currentMove];
13373 blackTimeRemaining = timeRemaining[1][currentMove];
13374 DisplayBothClocks();
13375 if (whiteFlag || blackFlag) {
13376 whiteFlag = blackFlag = 0;
13381 gameMode = EditGame;
13388 EditPositionEvent()
13390 if (gameMode == EditPosition) {
13396 if (gameMode != EditGame) return;
13398 gameMode = EditPosition;
13401 if (currentMove > 0)
13402 CopyBoard(boards[0], boards[currentMove]);
13404 blackPlaysFirst = !WhiteOnMove(currentMove);
13406 currentMove = forwardMostMove = backwardMostMove = 0;
13407 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13414 /* [DM] icsEngineAnalyze - possible call from other functions */
13415 if (appData.icsEngineAnalyze) {
13416 appData.icsEngineAnalyze = FALSE;
13418 DisplayMessage("",_("Close ICS engine analyze..."));
13420 if (first.analysisSupport && first.analyzing) {
13421 SendToProgram("exit\n", &first);
13422 first.analyzing = FALSE;
13424 thinkOutput[0] = NULLCHAR;
13428 EditPositionDone(Boolean fakeRights)
13430 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
13432 startedFromSetupPosition = TRUE;
13433 InitChessProgram(&first, FALSE);
13434 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
13435 boards[0][EP_STATUS] = EP_NONE;
13436 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
13437 if(boards[0][0][BOARD_WIDTH>>1] == king) {
13438 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
13439 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
13440 } else boards[0][CASTLING][2] = NoRights;
13441 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
13442 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
13443 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
13444 } else boards[0][CASTLING][5] = NoRights;
13446 SendToProgram("force\n", &first);
13447 if (blackPlaysFirst) {
13448 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13449 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13450 currentMove = forwardMostMove = backwardMostMove = 1;
13451 CopyBoard(boards[1], boards[0]);
13453 currentMove = forwardMostMove = backwardMostMove = 0;
13455 SendBoard(&first, forwardMostMove);
13456 if (appData.debugMode) {
13457 fprintf(debugFP, "EditPosDone\n");
13460 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13461 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13462 gameMode = EditGame;
13464 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13465 ClearHighlights(); /* [AS] */
13468 /* Pause for `ms' milliseconds */
13469 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
13479 } while (SubtractTimeMarks(&m2, &m1) < ms);
13482 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
13484 SendMultiLineToICS(buf)
13487 char temp[MSG_SIZ+1], *p;
13494 strncpy(temp, buf, len);
13499 if (*p == '\n' || *p == '\r')
13504 strcat(temp, "\n");
13506 SendToPlayer(temp, strlen(temp));
13510 SetWhiteToPlayEvent()
13512 if (gameMode == EditPosition) {
13513 blackPlaysFirst = FALSE;
13514 DisplayBothClocks(); /* works because currentMove is 0 */
13515 } else if (gameMode == IcsExamining) {
13516 SendToICS(ics_prefix);
13517 SendToICS("tomove white\n");
13522 SetBlackToPlayEvent()
13524 if (gameMode == EditPosition) {
13525 blackPlaysFirst = TRUE;
13526 currentMove = 1; /* kludge */
13527 DisplayBothClocks();
13529 } else if (gameMode == IcsExamining) {
13530 SendToICS(ics_prefix);
13531 SendToICS("tomove black\n");
13536 EditPositionMenuEvent(selection, x, y)
13537 ChessSquare selection;
13541 ChessSquare piece = boards[0][y][x];
13543 if (gameMode != EditPosition && gameMode != IcsExamining) return;
13545 switch (selection) {
13547 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
13548 SendToICS(ics_prefix);
13549 SendToICS("bsetup clear\n");
13550 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
13551 SendToICS(ics_prefix);
13552 SendToICS("clearboard\n");
13554 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
13555 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
13556 for (y = 0; y < BOARD_HEIGHT; y++) {
13557 if (gameMode == IcsExamining) {
13558 if (boards[currentMove][y][x] != EmptySquare) {
13559 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
13564 boards[0][y][x] = p;
13569 if (gameMode == EditPosition) {
13570 DrawPosition(FALSE, boards[0]);
13575 SetWhiteToPlayEvent();
13579 SetBlackToPlayEvent();
13583 if (gameMode == IcsExamining) {
13584 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
13585 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
13588 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
13589 if(x == BOARD_LEFT-2) {
13590 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
13591 boards[0][y][1] = 0;
13593 if(x == BOARD_RGHT+1) {
13594 if(y >= gameInfo.holdingsSize) break;
13595 boards[0][y][BOARD_WIDTH-2] = 0;
13598 boards[0][y][x] = EmptySquare;
13599 DrawPosition(FALSE, boards[0]);
13604 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
13605 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
13606 selection = (ChessSquare) (PROMOTED piece);
13607 } else if(piece == EmptySquare) selection = WhiteSilver;
13608 else selection = (ChessSquare)((int)piece - 1);
13612 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
13613 piece > (int)BlackMan && piece <= (int)BlackKing ) {
13614 selection = (ChessSquare) (DEMOTED piece);
13615 } else if(piece == EmptySquare) selection = BlackSilver;
13616 else selection = (ChessSquare)((int)piece + 1);
13621 if(gameInfo.variant == VariantShatranj ||
13622 gameInfo.variant == VariantXiangqi ||
13623 gameInfo.variant == VariantCourier ||
13624 gameInfo.variant == VariantMakruk )
13625 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
13630 if(gameInfo.variant == VariantXiangqi)
13631 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
13632 if(gameInfo.variant == VariantKnightmate)
13633 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
13636 if (gameMode == IcsExamining) {
13637 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
13638 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
13639 PieceToChar(selection), AAA + x, ONE + y);
13642 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
13644 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
13645 n = PieceToNumber(selection - BlackPawn);
13646 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
13647 boards[0][BOARD_HEIGHT-1-n][0] = selection;
13648 boards[0][BOARD_HEIGHT-1-n][1]++;
13650 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
13651 n = PieceToNumber(selection);
13652 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
13653 boards[0][n][BOARD_WIDTH-1] = selection;
13654 boards[0][n][BOARD_WIDTH-2]++;
13657 boards[0][y][x] = selection;
13658 DrawPosition(TRUE, boards[0]);
13666 DropMenuEvent(selection, x, y)
13667 ChessSquare selection;
13670 ChessMove moveType;
13672 switch (gameMode) {
13673 case IcsPlayingWhite:
13674 case MachinePlaysBlack:
13675 if (!WhiteOnMove(currentMove)) {
13676 DisplayMoveError(_("It is Black's turn"));
13679 moveType = WhiteDrop;
13681 case IcsPlayingBlack:
13682 case MachinePlaysWhite:
13683 if (WhiteOnMove(currentMove)) {
13684 DisplayMoveError(_("It is White's turn"));
13687 moveType = BlackDrop;
13690 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
13696 if (moveType == BlackDrop && selection < BlackPawn) {
13697 selection = (ChessSquare) ((int) selection
13698 + (int) BlackPawn - (int) WhitePawn);
13700 if (boards[currentMove][y][x] != EmptySquare) {
13701 DisplayMoveError(_("That square is occupied"));
13705 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
13711 /* Accept a pending offer of any kind from opponent */
13713 if (appData.icsActive) {
13714 SendToICS(ics_prefix);
13715 SendToICS("accept\n");
13716 } else if (cmailMsgLoaded) {
13717 if (currentMove == cmailOldMove &&
13718 commentList[cmailOldMove] != NULL &&
13719 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
13720 "Black offers a draw" : "White offers a draw")) {
13722 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
13723 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
13725 DisplayError(_("There is no pending offer on this move"), 0);
13726 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
13729 /* Not used for offers from chess program */
13736 /* Decline a pending offer of any kind from opponent */
13738 if (appData.icsActive) {
13739 SendToICS(ics_prefix);
13740 SendToICS("decline\n");
13741 } else if (cmailMsgLoaded) {
13742 if (currentMove == cmailOldMove &&
13743 commentList[cmailOldMove] != NULL &&
13744 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
13745 "Black offers a draw" : "White offers a draw")) {
13747 AppendComment(cmailOldMove, "Draw declined", TRUE);
13748 DisplayComment(cmailOldMove - 1, "Draw declined");
13751 DisplayError(_("There is no pending offer on this move"), 0);
13754 /* Not used for offers from chess program */
13761 /* Issue ICS rematch command */
13762 if (appData.icsActive) {
13763 SendToICS(ics_prefix);
13764 SendToICS("rematch\n");
13771 /* Call your opponent's flag (claim a win on time) */
13772 if (appData.icsActive) {
13773 SendToICS(ics_prefix);
13774 SendToICS("flag\n");
13776 switch (gameMode) {
13779 case MachinePlaysWhite:
13782 GameEnds(GameIsDrawn, "Both players ran out of time",
13785 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
13787 DisplayError(_("Your opponent is not out of time"), 0);
13790 case MachinePlaysBlack:
13793 GameEnds(GameIsDrawn, "Both players ran out of time",
13796 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
13798 DisplayError(_("Your opponent is not out of time"), 0);
13806 ClockClick(int which)
13807 { // [HGM] code moved to back-end from winboard.c
13808 if(which) { // black clock
13809 if (gameMode == EditPosition || gameMode == IcsExamining) {
13810 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
13811 SetBlackToPlayEvent();
13812 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !blackFlag && WhiteOnMove(currentMove)) {
13813 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
13814 } else if (shiftKey) {
13815 AdjustClock(which, -1);
13816 } else if (gameMode == IcsPlayingWhite ||
13817 gameMode == MachinePlaysBlack) {
13820 } else { // white clock
13821 if (gameMode == EditPosition || gameMode == IcsExamining) {
13822 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
13823 SetWhiteToPlayEvent();
13824 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !whiteFlag && !WhiteOnMove(currentMove)) {
13825 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
13826 } else if (shiftKey) {
13827 AdjustClock(which, -1);
13828 } else if (gameMode == IcsPlayingBlack ||
13829 gameMode == MachinePlaysWhite) {
13838 /* Offer draw or accept pending draw offer from opponent */
13840 if (appData.icsActive) {
13841 /* Note: tournament rules require draw offers to be
13842 made after you make your move but before you punch
13843 your clock. Currently ICS doesn't let you do that;
13844 instead, you immediately punch your clock after making
13845 a move, but you can offer a draw at any time. */
13847 SendToICS(ics_prefix);
13848 SendToICS("draw\n");
13849 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
13850 } else if (cmailMsgLoaded) {
13851 if (currentMove == cmailOldMove &&
13852 commentList[cmailOldMove] != NULL &&
13853 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
13854 "Black offers a draw" : "White offers a draw")) {
13855 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
13856 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
13857 } else if (currentMove == cmailOldMove + 1) {
13858 char *offer = WhiteOnMove(cmailOldMove) ?
13859 "White offers a draw" : "Black offers a draw";
13860 AppendComment(currentMove, offer, TRUE);
13861 DisplayComment(currentMove - 1, offer);
13862 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
13864 DisplayError(_("You must make your move before offering a draw"), 0);
13865 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
13867 } else if (first.offeredDraw) {
13868 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
13870 if (first.sendDrawOffers) {
13871 SendToProgram("draw\n", &first);
13872 userOfferedDraw = TRUE;
13880 /* Offer Adjourn or accept pending Adjourn offer from opponent */
13882 if (appData.icsActive) {
13883 SendToICS(ics_prefix);
13884 SendToICS("adjourn\n");
13886 /* Currently GNU Chess doesn't offer or accept Adjourns */
13894 /* Offer Abort or accept pending Abort offer from opponent */
13896 if (appData.icsActive) {
13897 SendToICS(ics_prefix);
13898 SendToICS("abort\n");
13900 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
13907 /* Resign. You can do this even if it's not your turn. */
13909 if (appData.icsActive) {
13910 SendToICS(ics_prefix);
13911 SendToICS("resign\n");
13913 switch (gameMode) {
13914 case MachinePlaysWhite:
13915 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
13917 case MachinePlaysBlack:
13918 GameEnds(BlackWins, "White resigns", GE_PLAYER);
13921 if (cmailMsgLoaded) {
13923 if (WhiteOnMove(cmailOldMove)) {
13924 GameEnds(BlackWins, "White resigns", GE_PLAYER);
13926 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
13928 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
13939 StopObservingEvent()
13941 /* Stop observing current games */
13942 SendToICS(ics_prefix);
13943 SendToICS("unobserve\n");
13947 StopExaminingEvent()
13949 /* Stop observing current game */
13950 SendToICS(ics_prefix);
13951 SendToICS("unexamine\n");
13955 ForwardInner(target)
13960 if (appData.debugMode)
13961 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
13962 target, currentMove, forwardMostMove);
13964 if (gameMode == EditPosition)
13967 if (gameMode == PlayFromGameFile && !pausing)
13970 if (gameMode == IcsExamining && pausing)
13971 limit = pauseExamForwardMostMove;
13973 limit = forwardMostMove;
13975 if (target > limit) target = limit;
13977 if (target > 0 && moveList[target - 1][0]) {
13978 int fromX, fromY, toX, toY;
13979 toX = moveList[target - 1][2] - AAA;
13980 toY = moveList[target - 1][3] - ONE;
13981 if (moveList[target - 1][1] == '@') {
13982 if (appData.highlightLastMove) {
13983 SetHighlights(-1, -1, toX, toY);
13986 fromX = moveList[target - 1][0] - AAA;
13987 fromY = moveList[target - 1][1] - ONE;
13988 if (target == currentMove + 1) {
13989 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
13991 if (appData.highlightLastMove) {
13992 SetHighlights(fromX, fromY, toX, toY);
13996 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13997 gameMode == Training || gameMode == PlayFromGameFile ||
13998 gameMode == AnalyzeFile) {
13999 while (currentMove < target) {
14000 SendMoveToProgram(currentMove++, &first);
14003 currentMove = target;
14006 if (gameMode == EditGame || gameMode == EndOfGame) {
14007 whiteTimeRemaining = timeRemaining[0][currentMove];
14008 blackTimeRemaining = timeRemaining[1][currentMove];
14010 DisplayBothClocks();
14011 DisplayMove(currentMove - 1);
14012 DrawPosition(FALSE, boards[currentMove]);
14013 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14014 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
14015 DisplayComment(currentMove - 1, commentList[currentMove]);
14017 DisplayBook(currentMove);
14024 if (gameMode == IcsExamining && !pausing) {
14025 SendToICS(ics_prefix);
14026 SendToICS("forward\n");
14028 ForwardInner(currentMove + 1);
14035 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14036 /* to optimze, we temporarily turn off analysis mode while we feed
14037 * the remaining moves to the engine. Otherwise we get analysis output
14040 if (first.analysisSupport) {
14041 SendToProgram("exit\nforce\n", &first);
14042 first.analyzing = FALSE;
14046 if (gameMode == IcsExamining && !pausing) {
14047 SendToICS(ics_prefix);
14048 SendToICS("forward 999999\n");
14050 ForwardInner(forwardMostMove);
14053 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14054 /* we have fed all the moves, so reactivate analysis mode */
14055 SendToProgram("analyze\n", &first);
14056 first.analyzing = TRUE;
14057 /*first.maybeThinking = TRUE;*/
14058 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14063 BackwardInner(target)
14066 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
14068 if (appData.debugMode)
14069 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
14070 target, currentMove, forwardMostMove);
14072 if (gameMode == EditPosition) return;
14073 if (currentMove <= backwardMostMove) {
14075 DrawPosition(full_redraw, boards[currentMove]);
14078 if (gameMode == PlayFromGameFile && !pausing)
14081 if (moveList[target][0]) {
14082 int fromX, fromY, toX, toY;
14083 toX = moveList[target][2] - AAA;
14084 toY = moveList[target][3] - ONE;
14085 if (moveList[target][1] == '@') {
14086 if (appData.highlightLastMove) {
14087 SetHighlights(-1, -1, toX, toY);
14090 fromX = moveList[target][0] - AAA;
14091 fromY = moveList[target][1] - ONE;
14092 if (target == currentMove - 1) {
14093 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
14095 if (appData.highlightLastMove) {
14096 SetHighlights(fromX, fromY, toX, toY);
14100 if (gameMode == EditGame || gameMode==AnalyzeMode ||
14101 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
14102 while (currentMove > target) {
14103 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
14104 // null move cannot be undone. Reload program with move history before it.
14106 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
14107 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
14109 SendBoard(&first, i);
14110 for(currentMove=i; currentMove<target; currentMove++) SendMoveToProgram(currentMove, &first);
14113 SendToProgram("undo\n", &first);
14117 currentMove = target;
14120 if (gameMode == EditGame || gameMode == EndOfGame) {
14121 whiteTimeRemaining = timeRemaining[0][currentMove];
14122 blackTimeRemaining = timeRemaining[1][currentMove];
14124 DisplayBothClocks();
14125 DisplayMove(currentMove - 1);
14126 DrawPosition(full_redraw, boards[currentMove]);
14127 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14128 // [HGM] PV info: routine tests if comment empty
14129 DisplayComment(currentMove - 1, commentList[currentMove]);
14130 DisplayBook(currentMove);
14136 if (gameMode == IcsExamining && !pausing) {
14137 SendToICS(ics_prefix);
14138 SendToICS("backward\n");
14140 BackwardInner(currentMove - 1);
14147 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14148 /* to optimize, we temporarily turn off analysis mode while we undo
14149 * all the moves. Otherwise we get analysis output after each undo.
14151 if (first.analysisSupport) {
14152 SendToProgram("exit\nforce\n", &first);
14153 first.analyzing = FALSE;
14157 if (gameMode == IcsExamining && !pausing) {
14158 SendToICS(ics_prefix);
14159 SendToICS("backward 999999\n");
14161 BackwardInner(backwardMostMove);
14164 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14165 /* we have fed all the moves, so reactivate analysis mode */
14166 SendToProgram("analyze\n", &first);
14167 first.analyzing = TRUE;
14168 /*first.maybeThinking = TRUE;*/
14169 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14176 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
14177 if (to >= forwardMostMove) to = forwardMostMove;
14178 if (to <= backwardMostMove) to = backwardMostMove;
14179 if (to < currentMove) {
14187 RevertEvent(Boolean annotate)
14189 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
14192 if (gameMode != IcsExamining) {
14193 DisplayError(_("You are not examining a game"), 0);
14197 DisplayError(_("You can't revert while pausing"), 0);
14200 SendToICS(ics_prefix);
14201 SendToICS("revert\n");
14207 switch (gameMode) {
14208 case MachinePlaysWhite:
14209 case MachinePlaysBlack:
14210 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
14211 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
14214 if (forwardMostMove < 2) return;
14215 currentMove = forwardMostMove = forwardMostMove - 2;
14216 whiteTimeRemaining = timeRemaining[0][currentMove];
14217 blackTimeRemaining = timeRemaining[1][currentMove];
14218 DisplayBothClocks();
14219 DisplayMove(currentMove - 1);
14220 ClearHighlights();/*!! could figure this out*/
14221 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
14222 SendToProgram("remove\n", &first);
14223 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
14226 case BeginningOfGame:
14230 case IcsPlayingWhite:
14231 case IcsPlayingBlack:
14232 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
14233 SendToICS(ics_prefix);
14234 SendToICS("takeback 2\n");
14236 SendToICS(ics_prefix);
14237 SendToICS("takeback 1\n");
14246 ChessProgramState *cps;
14248 switch (gameMode) {
14249 case MachinePlaysWhite:
14250 if (!WhiteOnMove(forwardMostMove)) {
14251 DisplayError(_("It is your turn"), 0);
14256 case MachinePlaysBlack:
14257 if (WhiteOnMove(forwardMostMove)) {
14258 DisplayError(_("It is your turn"), 0);
14263 case TwoMachinesPlay:
14264 if (WhiteOnMove(forwardMostMove) ==
14265 (first.twoMachinesColor[0] == 'w')) {
14271 case BeginningOfGame:
14275 SendToProgram("?\n", cps);
14279 TruncateGameEvent()
14282 if (gameMode != EditGame) return;
14289 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
14290 if (forwardMostMove > currentMove) {
14291 if (gameInfo.resultDetails != NULL) {
14292 free(gameInfo.resultDetails);
14293 gameInfo.resultDetails = NULL;
14294 gameInfo.result = GameUnfinished;
14296 forwardMostMove = currentMove;
14297 HistorySet(parseList, backwardMostMove, forwardMostMove,
14305 if (appData.noChessProgram) return;
14306 switch (gameMode) {
14307 case MachinePlaysWhite:
14308 if (WhiteOnMove(forwardMostMove)) {
14309 DisplayError(_("Wait until your turn"), 0);
14313 case BeginningOfGame:
14314 case MachinePlaysBlack:
14315 if (!WhiteOnMove(forwardMostMove)) {
14316 DisplayError(_("Wait until your turn"), 0);
14321 DisplayError(_("No hint available"), 0);
14324 SendToProgram("hint\n", &first);
14325 hintRequested = TRUE;
14331 if (appData.noChessProgram) return;
14332 switch (gameMode) {
14333 case MachinePlaysWhite:
14334 if (WhiteOnMove(forwardMostMove)) {
14335 DisplayError(_("Wait until your turn"), 0);
14339 case BeginningOfGame:
14340 case MachinePlaysBlack:
14341 if (!WhiteOnMove(forwardMostMove)) {
14342 DisplayError(_("Wait until your turn"), 0);
14347 EditPositionDone(TRUE);
14349 case TwoMachinesPlay:
14354 SendToProgram("bk\n", &first);
14355 bookOutput[0] = NULLCHAR;
14356 bookRequested = TRUE;
14362 char *tags = PGNTags(&gameInfo);
14363 TagsPopUp(tags, CmailMsg());
14367 /* end button procedures */
14370 PrintPosition(fp, move)
14376 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14377 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
14378 char c = PieceToChar(boards[move][i][j]);
14379 fputc(c == 'x' ? '.' : c, fp);
14380 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
14383 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
14384 fprintf(fp, "white to play\n");
14386 fprintf(fp, "black to play\n");
14393 if (gameInfo.white != NULL) {
14394 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
14400 /* Find last component of program's own name, using some heuristics */
14402 TidyProgramName(prog, host, buf)
14403 char *prog, *host, buf[MSG_SIZ];
14406 int local = (strcmp(host, "localhost") == 0);
14407 while (!local && (p = strchr(prog, ';')) != NULL) {
14409 while (*p == ' ') p++;
14412 if (*prog == '"' || *prog == '\'') {
14413 q = strchr(prog + 1, *prog);
14415 q = strchr(prog, ' ');
14417 if (q == NULL) q = prog + strlen(prog);
14419 while (p >= prog && *p != '/' && *p != '\\') p--;
14421 if(p == prog && *p == '"') p++;
14422 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
14423 memcpy(buf, p, q - p);
14424 buf[q - p] = NULLCHAR;
14432 TimeControlTagValue()
14435 if (!appData.clockMode) {
14436 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
14437 } else if (movesPerSession > 0) {
14438 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
14439 } else if (timeIncrement == 0) {
14440 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
14442 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
14444 return StrSave(buf);
14450 /* This routine is used only for certain modes */
14451 VariantClass v = gameInfo.variant;
14452 ChessMove r = GameUnfinished;
14455 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
14456 r = gameInfo.result;
14457 p = gameInfo.resultDetails;
14458 gameInfo.resultDetails = NULL;
14460 ClearGameInfo(&gameInfo);
14461 gameInfo.variant = v;
14463 switch (gameMode) {
14464 case MachinePlaysWhite:
14465 gameInfo.event = StrSave( appData.pgnEventHeader );
14466 gameInfo.site = StrSave(HostName());
14467 gameInfo.date = PGNDate();
14468 gameInfo.round = StrSave("-");
14469 gameInfo.white = StrSave(first.tidy);
14470 gameInfo.black = StrSave(UserName());
14471 gameInfo.timeControl = TimeControlTagValue();
14474 case MachinePlaysBlack:
14475 gameInfo.event = StrSave( appData.pgnEventHeader );
14476 gameInfo.site = StrSave(HostName());
14477 gameInfo.date = PGNDate();
14478 gameInfo.round = StrSave("-");
14479 gameInfo.white = StrSave(UserName());
14480 gameInfo.black = StrSave(first.tidy);
14481 gameInfo.timeControl = TimeControlTagValue();
14484 case TwoMachinesPlay:
14485 gameInfo.event = StrSave( appData.pgnEventHeader );
14486 gameInfo.site = StrSave(HostName());
14487 gameInfo.date = PGNDate();
14490 snprintf(buf, MSG_SIZ, "%d", roundNr);
14491 gameInfo.round = StrSave(buf);
14493 gameInfo.round = StrSave("-");
14495 if (first.twoMachinesColor[0] == 'w') {
14496 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
14497 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
14499 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
14500 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
14502 gameInfo.timeControl = TimeControlTagValue();
14506 gameInfo.event = StrSave("Edited game");
14507 gameInfo.site = StrSave(HostName());
14508 gameInfo.date = PGNDate();
14509 gameInfo.round = StrSave("-");
14510 gameInfo.white = StrSave("-");
14511 gameInfo.black = StrSave("-");
14512 gameInfo.result = r;
14513 gameInfo.resultDetails = p;
14517 gameInfo.event = StrSave("Edited position");
14518 gameInfo.site = StrSave(HostName());
14519 gameInfo.date = PGNDate();
14520 gameInfo.round = StrSave("-");
14521 gameInfo.white = StrSave("-");
14522 gameInfo.black = StrSave("-");
14525 case IcsPlayingWhite:
14526 case IcsPlayingBlack:
14531 case PlayFromGameFile:
14532 gameInfo.event = StrSave("Game from non-PGN file");
14533 gameInfo.site = StrSave(HostName());
14534 gameInfo.date = PGNDate();
14535 gameInfo.round = StrSave("-");
14536 gameInfo.white = StrSave("?");
14537 gameInfo.black = StrSave("?");
14546 ReplaceComment(index, text)
14554 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
14555 pvInfoList[index-1].depth == len &&
14556 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
14557 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
14558 while (*text == '\n') text++;
14559 len = strlen(text);
14560 while (len > 0 && text[len - 1] == '\n') len--;
14562 if (commentList[index] != NULL)
14563 free(commentList[index]);
14566 commentList[index] = NULL;
14569 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
14570 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
14571 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
14572 commentList[index] = (char *) malloc(len + 2);
14573 strncpy(commentList[index], text, len);
14574 commentList[index][len] = '\n';
14575 commentList[index][len + 1] = NULLCHAR;
14577 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
14579 commentList[index] = (char *) malloc(len + 7);
14580 safeStrCpy(commentList[index], "{\n", 3);
14581 safeStrCpy(commentList[index]+2, text, len+1);
14582 commentList[index][len+2] = NULLCHAR;
14583 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
14584 strcat(commentList[index], "\n}\n");
14598 if (ch == '\r') continue;
14600 } while (ch != '\0');
14604 AppendComment(index, text, addBraces)
14607 Boolean addBraces; // [HGM] braces: tells if we should add {}
14612 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
14613 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
14616 while (*text == '\n') text++;
14617 len = strlen(text);
14618 while (len > 0 && text[len - 1] == '\n') len--;
14620 if (len == 0) return;
14622 if (commentList[index] != NULL) {
14623 old = commentList[index];
14624 oldlen = strlen(old);
14625 while(commentList[index][oldlen-1] == '\n')
14626 commentList[index][--oldlen] = NULLCHAR;
14627 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
14628 safeStrCpy(commentList[index], old, oldlen + len + 6);
14630 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
14631 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
14632 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
14633 while (*text == '\n') { text++; len--; }
14634 commentList[index][--oldlen] = NULLCHAR;
14636 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
14637 else strcat(commentList[index], "\n");
14638 strcat(commentList[index], text);
14639 if(addBraces) strcat(commentList[index], addBraces == 2 ? ")\n" : "\n}\n");
14640 else strcat(commentList[index], "\n");
14642 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
14644 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
14645 else commentList[index][0] = NULLCHAR;
14646 strcat(commentList[index], text);
14647 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
14648 if(addBraces == TRUE) strcat(commentList[index], "}\n");
14652 static char * FindStr( char * text, char * sub_text )
14654 char * result = strstr( text, sub_text );
14656 if( result != NULL ) {
14657 result += strlen( sub_text );
14663 /* [AS] Try to extract PV info from PGN comment */
14664 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
14665 char *GetInfoFromComment( int index, char * text )
14667 char * sep = text, *p;
14669 if( text != NULL && index > 0 ) {
14672 int time = -1, sec = 0, deci;
14673 char * s_eval = FindStr( text, "[%eval " );
14674 char * s_emt = FindStr( text, "[%emt " );
14676 if( s_eval != NULL || s_emt != NULL ) {
14680 if( s_eval != NULL ) {
14681 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
14685 if( delim != ']' ) {
14690 if( s_emt != NULL ) {
14695 /* We expect something like: [+|-]nnn.nn/dd */
14698 if(*text != '{') return text; // [HGM] braces: must be normal comment
14700 sep = strchr( text, '/' );
14701 if( sep == NULL || sep < (text+4) ) {
14706 if(p[1] == '(') { // comment starts with PV
14707 p = strchr(p, ')'); // locate end of PV
14708 if(p == NULL || sep < p+5) return text;
14709 // at this point we have something like "{(.*) +0.23/6 ..."
14710 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
14711 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
14712 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
14714 time = -1; sec = -1; deci = -1;
14715 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
14716 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
14717 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
14718 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
14722 if( score_lo < 0 || score_lo >= 100 ) {
14726 if(sec >= 0) time = 600*time + 10*sec; else
14727 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
14729 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
14731 /* [HGM] PV time: now locate end of PV info */
14732 while( *++sep >= '0' && *sep <= '9'); // strip depth
14734 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
14736 while( *++sep >= '0' && *sep <= '9'); // strip seconds
14738 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
14739 while(*sep == ' ') sep++;
14750 pvInfoList[index-1].depth = depth;
14751 pvInfoList[index-1].score = score;
14752 pvInfoList[index-1].time = 10*time; // centi-sec
14753 if(*sep == '}') *sep = 0; else *--sep = '{';
14754 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
14760 SendToProgram(message, cps)
14762 ChessProgramState *cps;
14764 int count, outCount, error;
14767 if (cps->pr == NULL) return;
14770 if (appData.debugMode) {
14773 fprintf(debugFP, "%ld >%-6s: %s",
14774 SubtractTimeMarks(&now, &programStartTime),
14775 cps->which, message);
14778 count = strlen(message);
14779 outCount = OutputToProcess(cps->pr, message, count, &error);
14780 if (outCount < count && !exiting
14781 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
14782 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
14783 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
14784 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
14785 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
14786 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
14787 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
14788 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
14790 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
14791 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
14792 gameInfo.result = res;
14794 gameInfo.resultDetails = StrSave(buf);
14796 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
14797 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
14802 ReceiveFromProgram(isr, closure, message, count, error)
14803 InputSourceRef isr;
14811 ChessProgramState *cps = (ChessProgramState *)closure;
14813 if (isr != cps->isr) return; /* Killed intentionally */
14816 RemoveInputSource(cps->isr);
14817 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
14818 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
14819 _(cps->which), cps->program);
14820 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
14821 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
14822 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
14823 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
14824 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
14826 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
14827 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
14828 gameInfo.result = res;
14830 gameInfo.resultDetails = StrSave(buf);
14832 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
14833 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
14835 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
14836 _(cps->which), cps->program);
14837 RemoveInputSource(cps->isr);
14839 /* [AS] Program is misbehaving badly... kill it */
14840 if( count == -2 ) {
14841 DestroyChildProcess( cps->pr, 9 );
14845 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
14850 if ((end_str = strchr(message, '\r')) != NULL)
14851 *end_str = NULLCHAR;
14852 if ((end_str = strchr(message, '\n')) != NULL)
14853 *end_str = NULLCHAR;
14855 if (appData.debugMode) {
14856 TimeMark now; int print = 1;
14857 char *quote = ""; char c; int i;
14859 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
14860 char start = message[0];
14861 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
14862 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
14863 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
14864 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
14865 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
14866 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
14867 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
14868 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
14869 sscanf(message, "hint: %c", &c)!=1 &&
14870 sscanf(message, "pong %c", &c)!=1 && start != '#') {
14871 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
14872 print = (appData.engineComments >= 2);
14874 message[0] = start; // restore original message
14878 fprintf(debugFP, "%ld <%-6s: %s%s\n",
14879 SubtractTimeMarks(&now, &programStartTime), cps->which,
14885 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
14886 if (appData.icsEngineAnalyze) {
14887 if (strstr(message, "whisper") != NULL ||
14888 strstr(message, "kibitz") != NULL ||
14889 strstr(message, "tellics") != NULL) return;
14892 HandleMachineMove(message, cps);
14897 SendTimeControl(cps, mps, tc, inc, sd, st)
14898 ChessProgramState *cps;
14899 int mps, inc, sd, st;
14905 if( timeControl_2 > 0 ) {
14906 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
14907 tc = timeControl_2;
14910 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
14911 inc /= cps->timeOdds;
14912 st /= cps->timeOdds;
14914 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
14917 /* Set exact time per move, normally using st command */
14918 if (cps->stKludge) {
14919 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
14921 if (seconds == 0) {
14922 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
14924 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
14927 snprintf(buf, MSG_SIZ, "st %d\n", st);
14930 /* Set conventional or incremental time control, using level command */
14931 if (seconds == 0) {
14932 /* Note old gnuchess bug -- minutes:seconds used to not work.
14933 Fixed in later versions, but still avoid :seconds
14934 when seconds is 0. */
14935 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
14937 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
14938 seconds, inc/1000.);
14941 SendToProgram(buf, cps);
14943 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
14944 /* Orthogonally, limit search to given depth */
14946 if (cps->sdKludge) {
14947 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
14949 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
14951 SendToProgram(buf, cps);
14954 if(cps->nps >= 0) { /* [HGM] nps */
14955 if(cps->supportsNPS == FALSE)
14956 cps->nps = -1; // don't use if engine explicitly says not supported!
14958 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
14959 SendToProgram(buf, cps);
14964 ChessProgramState *WhitePlayer()
14965 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
14967 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
14968 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
14974 SendTimeRemaining(cps, machineWhite)
14975 ChessProgramState *cps;
14976 int /*boolean*/ machineWhite;
14978 char message[MSG_SIZ];
14981 /* Note: this routine must be called when the clocks are stopped
14982 or when they have *just* been set or switched; otherwise
14983 it will be off by the time since the current tick started.
14985 if (machineWhite) {
14986 time = whiteTimeRemaining / 10;
14987 otime = blackTimeRemaining / 10;
14989 time = blackTimeRemaining / 10;
14990 otime = whiteTimeRemaining / 10;
14992 /* [HGM] translate opponent's time by time-odds factor */
14993 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
14994 if (appData.debugMode) {
14995 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
14998 if (time <= 0) time = 1;
14999 if (otime <= 0) otime = 1;
15001 snprintf(message, MSG_SIZ, "time %ld\n", time);
15002 SendToProgram(message, cps);
15004 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
15005 SendToProgram(message, cps);
15009 BoolFeature(p, name, loc, cps)
15013 ChessProgramState *cps;
15016 int len = strlen(name);
15019 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15021 sscanf(*p, "%d", &val);
15023 while (**p && **p != ' ')
15025 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15026 SendToProgram(buf, cps);
15033 IntFeature(p, name, loc, cps)
15037 ChessProgramState *cps;
15040 int len = strlen(name);
15041 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15043 sscanf(*p, "%d", loc);
15044 while (**p && **p != ' ') (*p)++;
15045 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15046 SendToProgram(buf, cps);
15053 StringFeature(p, name, loc, cps)
15057 ChessProgramState *cps;
15060 int len = strlen(name);
15061 if (strncmp((*p), name, len) == 0
15062 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
15064 sscanf(*p, "%[^\"]", loc);
15065 while (**p && **p != '\"') (*p)++;
15066 if (**p == '\"') (*p)++;
15067 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15068 SendToProgram(buf, cps);
15075 ParseOption(Option *opt, ChessProgramState *cps)
15076 // [HGM] options: process the string that defines an engine option, and determine
15077 // name, type, default value, and allowed value range
15079 char *p, *q, buf[MSG_SIZ];
15080 int n, min = (-1)<<31, max = 1<<31, def;
15082 if(p = strstr(opt->name, " -spin ")) {
15083 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15084 if(max < min) max = min; // enforce consistency
15085 if(def < min) def = min;
15086 if(def > max) def = max;
15091 } else if((p = strstr(opt->name, " -slider "))) {
15092 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
15093 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15094 if(max < min) max = min; // enforce consistency
15095 if(def < min) def = min;
15096 if(def > max) def = max;
15100 opt->type = Spin; // Slider;
15101 } else if((p = strstr(opt->name, " -string "))) {
15102 opt->textValue = p+9;
15103 opt->type = TextBox;
15104 } else if((p = strstr(opt->name, " -file "))) {
15105 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15106 opt->textValue = p+7;
15107 opt->type = FileName; // FileName;
15108 } else if((p = strstr(opt->name, " -path "))) {
15109 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15110 opt->textValue = p+7;
15111 opt->type = PathName; // PathName;
15112 } else if(p = strstr(opt->name, " -check ")) {
15113 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
15114 opt->value = (def != 0);
15115 opt->type = CheckBox;
15116 } else if(p = strstr(opt->name, " -combo ")) {
15117 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
15118 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
15119 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
15120 opt->value = n = 0;
15121 while(q = StrStr(q, " /// ")) {
15122 n++; *q = 0; // count choices, and null-terminate each of them
15124 if(*q == '*') { // remember default, which is marked with * prefix
15128 cps->comboList[cps->comboCnt++] = q;
15130 cps->comboList[cps->comboCnt++] = NULL;
15132 opt->type = ComboBox;
15133 } else if(p = strstr(opt->name, " -button")) {
15134 opt->type = Button;
15135 } else if(p = strstr(opt->name, " -save")) {
15136 opt->type = SaveButton;
15137 } else return FALSE;
15138 *p = 0; // terminate option name
15139 // now look if the command-line options define a setting for this engine option.
15140 if(cps->optionSettings && cps->optionSettings[0])
15141 p = strstr(cps->optionSettings, opt->name); else p = NULL;
15142 if(p && (p == cps->optionSettings || p[-1] == ',')) {
15143 snprintf(buf, MSG_SIZ, "option %s", p);
15144 if(p = strstr(buf, ",")) *p = 0;
15145 if(q = strchr(buf, '=')) switch(opt->type) {
15147 for(n=0; n<opt->max; n++)
15148 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
15151 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
15155 opt->value = atoi(q+1);
15160 SendToProgram(buf, cps);
15166 FeatureDone(cps, val)
15167 ChessProgramState* cps;
15170 DelayedEventCallback cb = GetDelayedEvent();
15171 if ((cb == InitBackEnd3 && cps == &first) ||
15172 (cb == SettingsMenuIfReady && cps == &second) ||
15173 (cb == LoadEngine) ||
15174 (cb == TwoMachinesEventIfReady)) {
15175 CancelDelayedEvent();
15176 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
15178 cps->initDone = val;
15181 /* Parse feature command from engine */
15183 ParseFeatures(args, cps)
15185 ChessProgramState *cps;
15193 while (*p == ' ') p++;
15194 if (*p == NULLCHAR) return;
15196 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
15197 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
15198 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
15199 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
15200 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
15201 if (BoolFeature(&p, "reuse", &val, cps)) {
15202 /* Engine can disable reuse, but can't enable it if user said no */
15203 if (!val) cps->reuse = FALSE;
15206 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
15207 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
15208 if (gameMode == TwoMachinesPlay) {
15209 DisplayTwoMachinesTitle();
15215 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
15216 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
15217 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
15218 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
15219 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
15220 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
15221 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
15222 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
15223 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
15224 if (IntFeature(&p, "done", &val, cps)) {
15225 FeatureDone(cps, val);
15228 /* Added by Tord: */
15229 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
15230 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
15231 /* End of additions by Tord */
15233 /* [HGM] added features: */
15234 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
15235 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
15236 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
15237 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
15238 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
15239 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
15240 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
15241 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
15242 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
15243 SendToProgram(buf, cps);
15246 if(cps->nrOptions >= MAX_OPTIONS) {
15248 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
15249 DisplayError(buf, 0);
15253 /* End of additions by HGM */
15255 /* unknown feature: complain and skip */
15257 while (*q && *q != '=') q++;
15258 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
15259 SendToProgram(buf, cps);
15265 while (*p && *p != '\"') p++;
15266 if (*p == '\"') p++;
15268 while (*p && *p != ' ') p++;
15276 PeriodicUpdatesEvent(newState)
15279 if (newState == appData.periodicUpdates)
15282 appData.periodicUpdates=newState;
15284 /* Display type changes, so update it now */
15285 // DisplayAnalysis();
15287 /* Get the ball rolling again... */
15289 AnalysisPeriodicEvent(1);
15290 StartAnalysisClock();
15295 PonderNextMoveEvent(newState)
15298 if (newState == appData.ponderNextMove) return;
15299 if (gameMode == EditPosition) EditPositionDone(TRUE);
15301 SendToProgram("hard\n", &first);
15302 if (gameMode == TwoMachinesPlay) {
15303 SendToProgram("hard\n", &second);
15306 SendToProgram("easy\n", &first);
15307 thinkOutput[0] = NULLCHAR;
15308 if (gameMode == TwoMachinesPlay) {
15309 SendToProgram("easy\n", &second);
15312 appData.ponderNextMove = newState;
15316 NewSettingEvent(option, feature, command, value)
15318 int option, value, *feature;
15322 if (gameMode == EditPosition) EditPositionDone(TRUE);
15323 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
15324 if(feature == NULL || *feature) SendToProgram(buf, &first);
15325 if (gameMode == TwoMachinesPlay) {
15326 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
15331 ShowThinkingEvent()
15332 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
15334 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
15335 int newState = appData.showThinking
15336 // [HGM] thinking: other features now need thinking output as well
15337 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
15339 if (oldState == newState) return;
15340 oldState = newState;
15341 if (gameMode == EditPosition) EditPositionDone(TRUE);
15343 SendToProgram("post\n", &first);
15344 if (gameMode == TwoMachinesPlay) {
15345 SendToProgram("post\n", &second);
15348 SendToProgram("nopost\n", &first);
15349 thinkOutput[0] = NULLCHAR;
15350 if (gameMode == TwoMachinesPlay) {
15351 SendToProgram("nopost\n", &second);
15354 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
15358 AskQuestionEvent(title, question, replyPrefix, which)
15359 char *title; char *question; char *replyPrefix; char *which;
15361 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
15362 if (pr == NoProc) return;
15363 AskQuestion(title, question, replyPrefix, pr);
15367 TypeInEvent(char firstChar)
15369 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
15370 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
15371 gameMode == AnalyzeMode || gameMode == EditGame ||
15372 gameMode == EditPosition || gameMode == IcsExamining ||
15373 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
15374 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
15375 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
15376 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
15377 gameMode == Training) PopUpMoveDialog(firstChar);
15381 TypeInDoneEvent(char *move)
15384 int n, fromX, fromY, toX, toY;
15386 ChessMove moveType;
15389 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
15390 EditPositionPasteFEN(move);
15393 // [HGM] movenum: allow move number to be typed in any mode
15394 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
15399 if (gameMode != EditGame && currentMove != forwardMostMove &&
15400 gameMode != Training) {
15401 DisplayMoveError(_("Displayed move is not current"));
15403 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
15404 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
15405 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
15406 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
15407 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
15408 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
15410 DisplayMoveError(_("Could not parse move"));
15416 DisplayMove(moveNumber)
15419 char message[MSG_SIZ];
15421 char cpThinkOutput[MSG_SIZ];
15423 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
15425 if (moveNumber == forwardMostMove - 1 ||
15426 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15428 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
15430 if (strchr(cpThinkOutput, '\n')) {
15431 *strchr(cpThinkOutput, '\n') = NULLCHAR;
15434 *cpThinkOutput = NULLCHAR;
15437 /* [AS] Hide thinking from human user */
15438 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
15439 *cpThinkOutput = NULLCHAR;
15440 if( thinkOutput[0] != NULLCHAR ) {
15443 for( i=0; i<=hiddenThinkOutputState; i++ ) {
15444 cpThinkOutput[i] = '.';
15446 cpThinkOutput[i] = NULLCHAR;
15447 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
15451 if (moveNumber == forwardMostMove - 1 &&
15452 gameInfo.resultDetails != NULL) {
15453 if (gameInfo.resultDetails[0] == NULLCHAR) {
15454 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
15456 snprintf(res, MSG_SIZ, " {%s} %s",
15457 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
15463 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
15464 DisplayMessage(res, cpThinkOutput);
15466 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
15467 WhiteOnMove(moveNumber) ? " " : ".. ",
15468 parseList[moveNumber], res);
15469 DisplayMessage(message, cpThinkOutput);
15474 DisplayComment(moveNumber, text)
15478 char title[MSG_SIZ];
15480 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
15481 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
15483 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
15484 WhiteOnMove(moveNumber) ? " " : ".. ",
15485 parseList[moveNumber]);
15487 if (text != NULL && (appData.autoDisplayComment || commentUp))
15488 CommentPopUp(title, text);
15491 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
15492 * might be busy thinking or pondering. It can be omitted if your
15493 * gnuchess is configured to stop thinking immediately on any user
15494 * input. However, that gnuchess feature depends on the FIONREAD
15495 * ioctl, which does not work properly on some flavors of Unix.
15499 ChessProgramState *cps;
15502 if (!cps->useSigint) return;
15503 if (appData.noChessProgram || (cps->pr == NoProc)) return;
15504 switch (gameMode) {
15505 case MachinePlaysWhite:
15506 case MachinePlaysBlack:
15507 case TwoMachinesPlay:
15508 case IcsPlayingWhite:
15509 case IcsPlayingBlack:
15512 /* Skip if we know it isn't thinking */
15513 if (!cps->maybeThinking) return;
15514 if (appData.debugMode)
15515 fprintf(debugFP, "Interrupting %s\n", cps->which);
15516 InterruptChildProcess(cps->pr);
15517 cps->maybeThinking = FALSE;
15522 #endif /*ATTENTION*/
15528 if (whiteTimeRemaining <= 0) {
15531 if (appData.icsActive) {
15532 if (appData.autoCallFlag &&
15533 gameMode == IcsPlayingBlack && !blackFlag) {
15534 SendToICS(ics_prefix);
15535 SendToICS("flag\n");
15539 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
15541 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
15542 if (appData.autoCallFlag) {
15543 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
15550 if (blackTimeRemaining <= 0) {
15553 if (appData.icsActive) {
15554 if (appData.autoCallFlag &&
15555 gameMode == IcsPlayingWhite && !whiteFlag) {
15556 SendToICS(ics_prefix);
15557 SendToICS("flag\n");
15561 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
15563 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
15564 if (appData.autoCallFlag) {
15565 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
15578 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
15579 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
15582 * add time to clocks when time control is achieved ([HGM] now also used for increment)
15584 if ( !WhiteOnMove(forwardMostMove) ) {
15585 /* White made time control */
15586 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
15587 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
15588 /* [HGM] time odds: correct new time quota for time odds! */
15589 / WhitePlayer()->timeOdds;
15590 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
15592 lastBlack -= blackTimeRemaining;
15593 /* Black made time control */
15594 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
15595 / WhitePlayer()->other->timeOdds;
15596 lastWhite = whiteTimeRemaining;
15601 DisplayBothClocks()
15603 int wom = gameMode == EditPosition ?
15604 !blackPlaysFirst : WhiteOnMove(currentMove);
15605 DisplayWhiteClock(whiteTimeRemaining, wom);
15606 DisplayBlackClock(blackTimeRemaining, !wom);
15610 /* Timekeeping seems to be a portability nightmare. I think everyone
15611 has ftime(), but I'm really not sure, so I'm including some ifdefs
15612 to use other calls if you don't. Clocks will be less accurate if
15613 you have neither ftime nor gettimeofday.
15616 /* VS 2008 requires the #include outside of the function */
15617 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
15618 #include <sys/timeb.h>
15621 /* Get the current time as a TimeMark */
15626 #if HAVE_GETTIMEOFDAY
15628 struct timeval timeVal;
15629 struct timezone timeZone;
15631 gettimeofday(&timeVal, &timeZone);
15632 tm->sec = (long) timeVal.tv_sec;
15633 tm->ms = (int) (timeVal.tv_usec / 1000L);
15635 #else /*!HAVE_GETTIMEOFDAY*/
15638 // include <sys/timeb.h> / moved to just above start of function
15639 struct timeb timeB;
15642 tm->sec = (long) timeB.time;
15643 tm->ms = (int) timeB.millitm;
15645 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
15646 tm->sec = (long) time(NULL);
15652 /* Return the difference in milliseconds between two
15653 time marks. We assume the difference will fit in a long!
15656 SubtractTimeMarks(tm2, tm1)
15657 TimeMark *tm2, *tm1;
15659 return 1000L*(tm2->sec - tm1->sec) +
15660 (long) (tm2->ms - tm1->ms);
15665 * Code to manage the game clocks.
15667 * In tournament play, black starts the clock and then white makes a move.
15668 * We give the human user a slight advantage if he is playing white---the
15669 * clocks don't run until he makes his first move, so it takes zero time.
15670 * Also, we don't account for network lag, so we could get out of sync
15671 * with GNU Chess's clock -- but then, referees are always right.
15674 static TimeMark tickStartTM;
15675 static long intendedTickLength;
15678 NextTickLength(timeRemaining)
15679 long timeRemaining;
15681 long nominalTickLength, nextTickLength;
15683 if (timeRemaining > 0L && timeRemaining <= 10000L)
15684 nominalTickLength = 100L;
15686 nominalTickLength = 1000L;
15687 nextTickLength = timeRemaining % nominalTickLength;
15688 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
15690 return nextTickLength;
15693 /* Adjust clock one minute up or down */
15695 AdjustClock(Boolean which, int dir)
15697 if(which) blackTimeRemaining += 60000*dir;
15698 else whiteTimeRemaining += 60000*dir;
15699 DisplayBothClocks();
15702 /* Stop clocks and reset to a fresh time control */
15706 (void) StopClockTimer();
15707 if (appData.icsActive) {
15708 whiteTimeRemaining = blackTimeRemaining = 0;
15709 } else if (searchTime) {
15710 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
15711 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
15712 } else { /* [HGM] correct new time quote for time odds */
15713 whiteTC = blackTC = fullTimeControlString;
15714 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
15715 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
15717 if (whiteFlag || blackFlag) {
15719 whiteFlag = blackFlag = FALSE;
15721 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
15722 DisplayBothClocks();
15725 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
15727 /* Decrement running clock by amount of time that has passed */
15731 long timeRemaining;
15732 long lastTickLength, fudge;
15735 if (!appData.clockMode) return;
15736 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
15740 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
15742 /* Fudge if we woke up a little too soon */
15743 fudge = intendedTickLength - lastTickLength;
15744 if (fudge < 0 || fudge > FUDGE) fudge = 0;
15746 if (WhiteOnMove(forwardMostMove)) {
15747 if(whiteNPS >= 0) lastTickLength = 0;
15748 timeRemaining = whiteTimeRemaining -= lastTickLength;
15749 if(timeRemaining < 0 && !appData.icsActive) {
15750 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
15751 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
15752 whiteStartMove = forwardMostMove; whiteTC = nextSession;
15753 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
15756 DisplayWhiteClock(whiteTimeRemaining - fudge,
15757 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
15759 if(blackNPS >= 0) lastTickLength = 0;
15760 timeRemaining = blackTimeRemaining -= lastTickLength;
15761 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
15762 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
15764 blackStartMove = forwardMostMove;
15765 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
15768 DisplayBlackClock(blackTimeRemaining - fudge,
15769 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
15771 if (CheckFlags()) return;
15774 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
15775 StartClockTimer(intendedTickLength);
15777 /* if the time remaining has fallen below the alarm threshold, sound the
15778 * alarm. if the alarm has sounded and (due to a takeback or time control
15779 * with increment) the time remaining has increased to a level above the
15780 * threshold, reset the alarm so it can sound again.
15783 if (appData.icsActive && appData.icsAlarm) {
15785 /* make sure we are dealing with the user's clock */
15786 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
15787 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
15790 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
15791 alarmSounded = FALSE;
15792 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
15794 alarmSounded = TRUE;
15800 /* A player has just moved, so stop the previously running
15801 clock and (if in clock mode) start the other one.
15802 We redisplay both clocks in case we're in ICS mode, because
15803 ICS gives us an update to both clocks after every move.
15804 Note that this routine is called *after* forwardMostMove
15805 is updated, so the last fractional tick must be subtracted
15806 from the color that is *not* on move now.
15809 SwitchClocks(int newMoveNr)
15811 long lastTickLength;
15813 int flagged = FALSE;
15817 if (StopClockTimer() && appData.clockMode) {
15818 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
15819 if (!WhiteOnMove(forwardMostMove)) {
15820 if(blackNPS >= 0) lastTickLength = 0;
15821 blackTimeRemaining -= lastTickLength;
15822 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
15823 // if(pvInfoList[forwardMostMove].time == -1)
15824 pvInfoList[forwardMostMove].time = // use GUI time
15825 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
15827 if(whiteNPS >= 0) lastTickLength = 0;
15828 whiteTimeRemaining -= lastTickLength;
15829 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
15830 // if(pvInfoList[forwardMostMove].time == -1)
15831 pvInfoList[forwardMostMove].time =
15832 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
15834 flagged = CheckFlags();
15836 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
15837 CheckTimeControl();
15839 if (flagged || !appData.clockMode) return;
15841 switch (gameMode) {
15842 case MachinePlaysBlack:
15843 case MachinePlaysWhite:
15844 case BeginningOfGame:
15845 if (pausing) return;
15849 case PlayFromGameFile:
15857 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
15858 if(WhiteOnMove(forwardMostMove))
15859 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
15860 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
15864 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
15865 whiteTimeRemaining : blackTimeRemaining);
15866 StartClockTimer(intendedTickLength);
15870 /* Stop both clocks */
15874 long lastTickLength;
15877 if (!StopClockTimer()) return;
15878 if (!appData.clockMode) return;
15882 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
15883 if (WhiteOnMove(forwardMostMove)) {
15884 if(whiteNPS >= 0) lastTickLength = 0;
15885 whiteTimeRemaining -= lastTickLength;
15886 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
15888 if(blackNPS >= 0) lastTickLength = 0;
15889 blackTimeRemaining -= lastTickLength;
15890 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
15895 /* Start clock of player on move. Time may have been reset, so
15896 if clock is already running, stop and restart it. */
15900 (void) StopClockTimer(); /* in case it was running already */
15901 DisplayBothClocks();
15902 if (CheckFlags()) return;
15904 if (!appData.clockMode) return;
15905 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
15907 GetTimeMark(&tickStartTM);
15908 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
15909 whiteTimeRemaining : blackTimeRemaining);
15911 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
15912 whiteNPS = blackNPS = -1;
15913 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
15914 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
15915 whiteNPS = first.nps;
15916 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
15917 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
15918 blackNPS = first.nps;
15919 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
15920 whiteNPS = second.nps;
15921 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
15922 blackNPS = second.nps;
15923 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
15925 StartClockTimer(intendedTickLength);
15932 long second, minute, hour, day;
15934 static char buf[32];
15936 if (ms > 0 && ms <= 9900) {
15937 /* convert milliseconds to tenths, rounding up */
15938 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
15940 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
15944 /* convert milliseconds to seconds, rounding up */
15945 /* use floating point to avoid strangeness of integer division
15946 with negative dividends on many machines */
15947 second = (long) floor(((double) (ms + 999L)) / 1000.0);
15954 day = second / (60 * 60 * 24);
15955 second = second % (60 * 60 * 24);
15956 hour = second / (60 * 60);
15957 second = second % (60 * 60);
15958 minute = second / 60;
15959 second = second % 60;
15962 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
15963 sign, day, hour, minute, second);
15965 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
15967 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
15974 * This is necessary because some C libraries aren't ANSI C compliant yet.
15977 StrStr(string, match)
15978 char *string, *match;
15982 length = strlen(match);
15984 for (i = strlen(string) - length; i >= 0; i--, string++)
15985 if (!strncmp(match, string, length))
15992 StrCaseStr(string, match)
15993 char *string, *match;
15997 length = strlen(match);
15999 for (i = strlen(string) - length; i >= 0; i--, string++) {
16000 for (j = 0; j < length; j++) {
16001 if (ToLower(match[j]) != ToLower(string[j]))
16004 if (j == length) return string;
16018 c1 = ToLower(*s1++);
16019 c2 = ToLower(*s2++);
16020 if (c1 > c2) return 1;
16021 if (c1 < c2) return -1;
16022 if (c1 == NULLCHAR) return 0;
16031 return isupper(c) ? tolower(c) : c;
16039 return islower(c) ? toupper(c) : c;
16041 #endif /* !_amigados */
16049 if ((ret = (char *) malloc(strlen(s) + 1)))
16051 safeStrCpy(ret, s, strlen(s)+1);
16057 StrSavePtr(s, savePtr)
16058 char *s, **savePtr;
16063 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
16064 safeStrCpy(*savePtr, s, strlen(s)+1);
16076 clock = time((time_t *)NULL);
16077 tm = localtime(&clock);
16078 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
16079 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
16080 return StrSave(buf);
16085 PositionToFEN(move, overrideCastling)
16087 char *overrideCastling;
16089 int i, j, fromX, fromY, toX, toY;
16096 whiteToPlay = (gameMode == EditPosition) ?
16097 !blackPlaysFirst : (move % 2 == 0);
16100 /* Piece placement data */
16101 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16102 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
16104 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16105 if (boards[move][i][j] == EmptySquare) {
16107 } else { ChessSquare piece = boards[move][i][j];
16108 if (emptycount > 0) {
16109 if(emptycount<10) /* [HGM] can be >= 10 */
16110 *p++ = '0' + emptycount;
16111 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16114 if(PieceToChar(piece) == '+') {
16115 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
16117 piece = (ChessSquare)(DEMOTED piece);
16119 *p++ = PieceToChar(piece);
16121 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
16122 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
16127 if (emptycount > 0) {
16128 if(emptycount<10) /* [HGM] can be >= 10 */
16129 *p++ = '0' + emptycount;
16130 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16137 /* [HGM] print Crazyhouse or Shogi holdings */
16138 if( gameInfo.holdingsWidth ) {
16139 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
16141 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
16142 piece = boards[move][i][BOARD_WIDTH-1];
16143 if( piece != EmptySquare )
16144 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
16145 *p++ = PieceToChar(piece);
16147 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
16148 piece = boards[move][BOARD_HEIGHT-i-1][0];
16149 if( piece != EmptySquare )
16150 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
16151 *p++ = PieceToChar(piece);
16154 if( q == p ) *p++ = '-';
16160 *p++ = whiteToPlay ? 'w' : 'b';
16163 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
16164 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
16166 if(nrCastlingRights) {
16168 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
16169 /* [HGM] write directly from rights */
16170 if(boards[move][CASTLING][2] != NoRights &&
16171 boards[move][CASTLING][0] != NoRights )
16172 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
16173 if(boards[move][CASTLING][2] != NoRights &&
16174 boards[move][CASTLING][1] != NoRights )
16175 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
16176 if(boards[move][CASTLING][5] != NoRights &&
16177 boards[move][CASTLING][3] != NoRights )
16178 *p++ = boards[move][CASTLING][3] + AAA;
16179 if(boards[move][CASTLING][5] != NoRights &&
16180 boards[move][CASTLING][4] != NoRights )
16181 *p++ = boards[move][CASTLING][4] + AAA;
16184 /* [HGM] write true castling rights */
16185 if( nrCastlingRights == 6 ) {
16186 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
16187 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
16188 if(boards[move][CASTLING][1] == BOARD_LEFT &&
16189 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
16190 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
16191 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
16192 if(boards[move][CASTLING][4] == BOARD_LEFT &&
16193 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
16196 if (q == p) *p++ = '-'; /* No castling rights */
16200 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
16201 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
16202 /* En passant target square */
16203 if (move > backwardMostMove) {
16204 fromX = moveList[move - 1][0] - AAA;
16205 fromY = moveList[move - 1][1] - ONE;
16206 toX = moveList[move - 1][2] - AAA;
16207 toY = moveList[move - 1][3] - ONE;
16208 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
16209 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
16210 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
16212 /* 2-square pawn move just happened */
16214 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16218 } else if(move == backwardMostMove) {
16219 // [HGM] perhaps we should always do it like this, and forget the above?
16220 if((signed char)boards[move][EP_STATUS] >= 0) {
16221 *p++ = boards[move][EP_STATUS] + AAA;
16222 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16233 /* [HGM] find reversible plies */
16234 { int i = 0, j=move;
16236 if (appData.debugMode) { int k;
16237 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
16238 for(k=backwardMostMove; k<=forwardMostMove; k++)
16239 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
16243 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
16244 if( j == backwardMostMove ) i += initialRulePlies;
16245 sprintf(p, "%d ", i);
16246 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
16248 /* Fullmove number */
16249 sprintf(p, "%d", (move / 2) + 1);
16251 return StrSave(buf);
16255 ParseFEN(board, blackPlaysFirst, fen)
16257 int *blackPlaysFirst;
16267 /* [HGM] by default clear Crazyhouse holdings, if present */
16268 if(gameInfo.holdingsWidth) {
16269 for(i=0; i<BOARD_HEIGHT; i++) {
16270 board[i][0] = EmptySquare; /* black holdings */
16271 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
16272 board[i][1] = (ChessSquare) 0; /* black counts */
16273 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
16277 /* Piece placement data */
16278 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16281 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
16282 if (*p == '/') p++;
16283 emptycount = gameInfo.boardWidth - j;
16284 while (emptycount--)
16285 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16287 #if(BOARD_FILES >= 10)
16288 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
16289 p++; emptycount=10;
16290 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16291 while (emptycount--)
16292 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16294 } else if (isdigit(*p)) {
16295 emptycount = *p++ - '0';
16296 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
16297 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16298 while (emptycount--)
16299 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16300 } else if (*p == '+' || isalpha(*p)) {
16301 if (j >= gameInfo.boardWidth) return FALSE;
16303 piece = CharToPiece(*++p);
16304 if(piece == EmptySquare) return FALSE; /* unknown piece */
16305 piece = (ChessSquare) (PROMOTED piece ); p++;
16306 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
16307 } else piece = CharToPiece(*p++);
16309 if(piece==EmptySquare) return FALSE; /* unknown piece */
16310 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
16311 piece = (ChessSquare) (PROMOTED piece);
16312 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
16315 board[i][(j++)+gameInfo.holdingsWidth] = piece;
16321 while (*p == '/' || *p == ' ') p++;
16323 /* [HGM] look for Crazyhouse holdings here */
16324 while(*p==' ') p++;
16325 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
16327 if(*p == '-' ) p++; /* empty holdings */ else {
16328 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
16329 /* if we would allow FEN reading to set board size, we would */
16330 /* have to add holdings and shift the board read so far here */
16331 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
16333 if((int) piece >= (int) BlackPawn ) {
16334 i = (int)piece - (int)BlackPawn;
16335 i = PieceToNumber((ChessSquare)i);
16336 if( i >= gameInfo.holdingsSize ) return FALSE;
16337 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
16338 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
16340 i = (int)piece - (int)WhitePawn;
16341 i = PieceToNumber((ChessSquare)i);
16342 if( i >= gameInfo.holdingsSize ) return FALSE;
16343 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
16344 board[i][BOARD_WIDTH-2]++; /* black holdings */
16351 while(*p == ' ') p++;
16355 if(appData.colorNickNames) {
16356 if( c == appData.colorNickNames[0] ) c = 'w'; else
16357 if( c == appData.colorNickNames[1] ) c = 'b';
16361 *blackPlaysFirst = FALSE;
16364 *blackPlaysFirst = TRUE;
16370 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
16371 /* return the extra info in global variiables */
16373 /* set defaults in case FEN is incomplete */
16374 board[EP_STATUS] = EP_UNKNOWN;
16375 for(i=0; i<nrCastlingRights; i++ ) {
16376 board[CASTLING][i] =
16377 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
16378 } /* assume possible unless obviously impossible */
16379 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
16380 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
16381 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
16382 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
16383 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
16384 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
16385 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
16386 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
16389 while(*p==' ') p++;
16390 if(nrCastlingRights) {
16391 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
16392 /* castling indicator present, so default becomes no castlings */
16393 for(i=0; i<nrCastlingRights; i++ ) {
16394 board[CASTLING][i] = NoRights;
16397 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
16398 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
16399 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
16400 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
16401 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
16403 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
16404 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
16405 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
16407 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
16408 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
16409 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
16410 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
16411 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
16412 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
16415 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
16416 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
16417 board[CASTLING][2] = whiteKingFile;
16420 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
16421 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
16422 board[CASTLING][2] = whiteKingFile;
16425 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
16426 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
16427 board[CASTLING][5] = blackKingFile;
16430 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
16431 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
16432 board[CASTLING][5] = blackKingFile;
16435 default: /* FRC castlings */
16436 if(c >= 'a') { /* black rights */
16437 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
16438 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
16439 if(i == BOARD_RGHT) break;
16440 board[CASTLING][5] = i;
16442 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
16443 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
16445 board[CASTLING][3] = c;
16447 board[CASTLING][4] = c;
16448 } else { /* white rights */
16449 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
16450 if(board[0][i] == WhiteKing) break;
16451 if(i == BOARD_RGHT) break;
16452 board[CASTLING][2] = i;
16453 c -= AAA - 'a' + 'A';
16454 if(board[0][c] >= WhiteKing) break;
16456 board[CASTLING][0] = c;
16458 board[CASTLING][1] = c;
16462 for(i=0; i<nrCastlingRights; i++)
16463 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
16464 if (appData.debugMode) {
16465 fprintf(debugFP, "FEN castling rights:");
16466 for(i=0; i<nrCastlingRights; i++)
16467 fprintf(debugFP, " %d", board[CASTLING][i]);
16468 fprintf(debugFP, "\n");
16471 while(*p==' ') p++;
16474 /* read e.p. field in games that know e.p. capture */
16475 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
16476 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
16478 p++; board[EP_STATUS] = EP_NONE;
16480 char c = *p++ - AAA;
16482 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
16483 if(*p >= '0' && *p <='9') p++;
16484 board[EP_STATUS] = c;
16489 if(sscanf(p, "%d", &i) == 1) {
16490 FENrulePlies = i; /* 50-move ply counter */
16491 /* (The move number is still ignored) */
16498 EditPositionPasteFEN(char *fen)
16501 Board initial_position;
16503 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
16504 DisplayError(_("Bad FEN position in clipboard"), 0);
16507 int savedBlackPlaysFirst = blackPlaysFirst;
16508 EditPositionEvent();
16509 blackPlaysFirst = savedBlackPlaysFirst;
16510 CopyBoard(boards[0], initial_position);
16511 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
16512 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
16513 DisplayBothClocks();
16514 DrawPosition(FALSE, boards[currentMove]);
16519 static char cseq[12] = "\\ ";
16521 Boolean set_cont_sequence(char *new_seq)
16526 // handle bad attempts to set the sequence
16528 return 0; // acceptable error - no debug
16530 len = strlen(new_seq);
16531 ret = (len > 0) && (len < sizeof(cseq));
16533 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
16534 else if (appData.debugMode)
16535 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
16540 reformat a source message so words don't cross the width boundary. internal
16541 newlines are not removed. returns the wrapped size (no null character unless
16542 included in source message). If dest is NULL, only calculate the size required
16543 for the dest buffer. lp argument indicats line position upon entry, and it's
16544 passed back upon exit.
16546 int wrap(char *dest, char *src, int count, int width, int *lp)
16548 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
16550 cseq_len = strlen(cseq);
16551 old_line = line = *lp;
16552 ansi = len = clen = 0;
16554 for (i=0; i < count; i++)
16556 if (src[i] == '\033')
16559 // if we hit the width, back up
16560 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
16562 // store i & len in case the word is too long
16563 old_i = i, old_len = len;
16565 // find the end of the last word
16566 while (i && src[i] != ' ' && src[i] != '\n')
16572 // word too long? restore i & len before splitting it
16573 if ((old_i-i+clen) >= width)
16580 if (i && src[i-1] == ' ')
16583 if (src[i] != ' ' && src[i] != '\n')
16590 // now append the newline and continuation sequence
16595 strncpy(dest+len, cseq, cseq_len);
16603 dest[len] = src[i];
16607 if (src[i] == '\n')
16612 if (dest && appData.debugMode)
16614 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
16615 count, width, line, len, *lp);
16616 show_bytes(debugFP, src, count);
16617 fprintf(debugFP, "\ndest: ");
16618 show_bytes(debugFP, dest, len);
16619 fprintf(debugFP, "\n");
16621 *lp = dest ? line : old_line;
16626 // [HGM] vari: routines for shelving variations
16627 Boolean modeRestore = FALSE;
16630 PushInner(int firstMove, int lastMove)
16632 int i, j, nrMoves = lastMove - firstMove;
16634 // push current tail of game on stack
16635 savedResult[storedGames] = gameInfo.result;
16636 savedDetails[storedGames] = gameInfo.resultDetails;
16637 gameInfo.resultDetails = NULL;
16638 savedFirst[storedGames] = firstMove;
16639 savedLast [storedGames] = lastMove;
16640 savedFramePtr[storedGames] = framePtr;
16641 framePtr -= nrMoves; // reserve space for the boards
16642 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
16643 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
16644 for(j=0; j<MOVE_LEN; j++)
16645 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
16646 for(j=0; j<2*MOVE_LEN; j++)
16647 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
16648 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
16649 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
16650 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
16651 pvInfoList[firstMove+i-1].depth = 0;
16652 commentList[framePtr+i] = commentList[firstMove+i];
16653 commentList[firstMove+i] = NULL;
16657 forwardMostMove = firstMove; // truncate game so we can start variation
16661 PushTail(int firstMove, int lastMove)
16663 if(appData.icsActive) { // only in local mode
16664 forwardMostMove = currentMove; // mimic old ICS behavior
16667 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
16669 PushInner(firstMove, lastMove);
16670 if(storedGames == 1) GreyRevert(FALSE);
16671 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
16675 PopInner(Boolean annotate)
16678 char buf[8000], moveBuf[20];
16680 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
16681 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
16682 nrMoves = savedLast[storedGames] - currentMove;
16685 if(!WhiteOnMove(currentMove))
16686 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
16687 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
16688 for(i=currentMove; i<forwardMostMove; i++) {
16690 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
16691 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
16692 strcat(buf, moveBuf);
16693 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
16694 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
16698 for(i=1; i<=nrMoves; i++) { // copy last variation back
16699 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
16700 for(j=0; j<MOVE_LEN; j++)
16701 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
16702 for(j=0; j<2*MOVE_LEN; j++)
16703 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
16704 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
16705 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
16706 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
16707 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
16708 commentList[currentMove+i] = commentList[framePtr+i];
16709 commentList[framePtr+i] = NULL;
16711 if(annotate) AppendComment(currentMove+1, buf, FALSE);
16712 framePtr = savedFramePtr[storedGames];
16713 gameInfo.result = savedResult[storedGames];
16714 if(gameInfo.resultDetails != NULL) {
16715 free(gameInfo.resultDetails);
16717 gameInfo.resultDetails = savedDetails[storedGames];
16718 forwardMostMove = currentMove + nrMoves;
16722 PopTail(Boolean annotate)
16724 if(appData.icsActive) return FALSE; // only in local mode
16725 if(!storedGames) return FALSE; // sanity
16726 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
16728 PopInner(annotate);
16729 if(currentMove < forwardMostMove) ForwardEvent(); else
16730 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
16732 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
16738 { // remove all shelved variations
16740 for(i=0; i<storedGames; i++) {
16741 if(savedDetails[i])
16742 free(savedDetails[i]);
16743 savedDetails[i] = NULL;
16745 for(i=framePtr; i<MAX_MOVES; i++) {
16746 if(commentList[i]) free(commentList[i]);
16747 commentList[i] = NULL;
16749 framePtr = MAX_MOVES-1;
16754 LoadVariation(int index, char *text)
16755 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
16756 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
16757 int level = 0, move;
16759 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
16760 // first find outermost bracketing variation
16761 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
16762 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
16763 if(*p == '{') wait = '}'; else
16764 if(*p == '[') wait = ']'; else
16765 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
16766 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
16768 if(*p == wait) wait = NULLCHAR; // closing ]} found
16771 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
16772 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
16773 end[1] = NULLCHAR; // clip off comment beyond variation
16774 ToNrEvent(currentMove-1);
16775 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
16776 // kludge: use ParsePV() to append variation to game
16777 move = currentMove;
16778 ParsePV(start, TRUE, TRUE);
16779 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
16780 ClearPremoveHighlights();
16782 ToNrEvent(currentMove+1);