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 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) );
62 #define DoSleep( n ) if( (n) >= 0) sleep(n)
72 #include <sys/types.h>
81 #else /* not STDC_HEADERS */
84 # else /* not HAVE_STRING_H */
86 # endif /* not HAVE_STRING_H */
87 #endif /* not STDC_HEADERS */
90 # include <sys/fcntl.h>
91 #else /* not HAVE_SYS_FCNTL_H */
94 # endif /* HAVE_FCNTL_H */
95 #endif /* not HAVE_SYS_FCNTL_H */
97 #if TIME_WITH_SYS_TIME
98 # include <sys/time.h>
102 # include <sys/time.h>
108 #if defined(_amigados) && !defined(__GNUC__)
113 extern int gettimeofday(struct timeval *, struct timezone *);
121 #include "frontend.h"
128 #include "backendz.h"
132 # define _(s) gettext (s)
133 # define N_(s) gettext_noop (s)
134 # define T_(s) gettext(s)
147 /* A point in time */
149 long sec; /* Assuming this is >= 32 bits */
150 int ms; /* Assuming this is >= 16 bits */
153 int establish P((void));
154 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
155 char *buf, int count, int error));
156 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
157 char *buf, int count, int error));
158 void ics_printf P((char *format, ...));
159 void SendToICS P((char *s));
160 void SendToICSDelayed P((char *s, long msdelay));
161 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
162 void HandleMachineMove P((char *message, ChessProgramState *cps));
163 int AutoPlayOneMove P((void));
164 int LoadGameOneMove P((ChessMove readAhead));
165 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
166 int LoadPositionFromFile P((char *filename, int n, char *title));
167 int SavePositionToFile P((char *filename));
168 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
170 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
171 void ShowMove P((int fromX, int fromY, int toX, int toY));
172 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
173 /*char*/int promoChar));
174 void BackwardInner P((int target));
175 void ForwardInner P((int target));
176 int Adjudicate P((ChessProgramState *cps));
177 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
178 void EditPositionDone P((Boolean fakeRights));
179 void PrintOpponents P((FILE *fp));
180 void PrintPosition P((FILE *fp, int move));
181 void StartChessProgram P((ChessProgramState *cps));
182 void SendToProgram P((char *message, ChessProgramState *cps));
183 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
184 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
185 char *buf, int count, int error));
186 void SendTimeControl P((ChessProgramState *cps,
187 int mps, long tc, int inc, int sd, int st));
188 char *TimeControlTagValue P((void));
189 void Attention P((ChessProgramState *cps));
190 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
191 void ResurrectChessProgram P((void));
192 void DisplayComment P((int moveNumber, char *text));
193 void DisplayMove P((int moveNumber));
195 void ParseGameHistory P((char *game));
196 void ParseBoard12 P((char *string));
197 void KeepAlive P((void));
198 void StartClocks P((void));
199 void SwitchClocks P((int nr));
200 void StopClocks P((void));
201 void ResetClocks P((void));
202 char *PGNDate P((void));
203 void SetGameInfo P((void));
204 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
205 int RegisterMove P((void));
206 void MakeRegisteredMove P((void));
207 void TruncateGame P((void));
208 int looking_at P((char *, int *, char *));
209 void CopyPlayerNameIntoFileName P((char **, char *));
210 char *SavePart P((char *));
211 int SaveGameOldStyle P((FILE *));
212 int SaveGamePGN P((FILE *));
213 void GetTimeMark P((TimeMark *));
214 long SubtractTimeMarks P((TimeMark *, TimeMark *));
215 int CheckFlags P((void));
216 long NextTickLength P((long));
217 void CheckTimeControl P((void));
218 void show_bytes P((FILE *, char *, int));
219 int string_to_rating P((char *str));
220 void ParseFeatures P((char* args, ChessProgramState *cps));
221 void InitBackEnd3 P((void));
222 void FeatureDone P((ChessProgramState* cps, int val));
223 void InitChessProgram P((ChessProgramState *cps, int setup));
224 void OutputKibitz(int window, char *text);
225 int PerpetualChase(int first, int last);
226 int EngineOutputIsUp();
227 void InitDrawingSizes(int x, int y);
230 extern void ConsoleCreate();
233 ChessProgramState *WhitePlayer();
234 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
235 int VerifyDisplayMode P(());
237 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
238 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
239 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
240 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
241 void ics_update_width P((int new_width));
242 extern char installDir[MSG_SIZ];
243 VariantClass startVariant; /* [HGM] nicks: initial variant */
245 extern int tinyLayout, smallLayout;
246 ChessProgramStats programStats;
247 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
249 static int exiting = 0; /* [HGM] moved to top */
250 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
251 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
252 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
253 int partnerHighlight[2];
254 Boolean partnerBoardValid = 0;
255 char partnerStatus[MSG_SIZ];
257 Boolean originalFlip;
258 Boolean twoBoards = 0;
259 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
260 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
261 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
262 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
263 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
264 int opponentKibitzes;
265 int lastSavedGame; /* [HGM] save: ID of game */
266 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
267 extern int chatCount;
269 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
271 /* States for ics_getting_history */
273 #define H_REQUESTED 1
274 #define H_GOT_REQ_HEADER 2
275 #define H_GOT_UNREQ_HEADER 3
276 #define H_GETTING_MOVES 4
277 #define H_GOT_UNWANTED_HEADER 5
279 /* whosays values for GameEnds */
288 /* Maximum number of games in a cmail message */
289 #define CMAIL_MAX_GAMES 20
291 /* Different types of move when calling RegisterMove */
293 #define CMAIL_RESIGN 1
295 #define CMAIL_ACCEPT 3
297 /* Different types of result to remember for each game */
298 #define CMAIL_NOT_RESULT 0
299 #define CMAIL_OLD_RESULT 1
300 #define CMAIL_NEW_RESULT 2
302 /* Telnet protocol constants */
313 safeStrCpy( char *dst, const char *src, size_t count )
315 /* see for example: https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/854-BSI.html
317 * usage: safeStrCpy( stringA, stringB, sizeof(stringA)/sizeof(stringA[0]);
320 assert( dst != NULL );
321 assert( src != NULL );
324 strncpy( dst, src, count );
325 if( dst[ count-1 ] != '\0' )
327 if(appData.debugMode)
328 printf("safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst,count);
330 dst[ count-1 ] = '\0';
335 /* Some compiler can't cast u64 to double
336 * This function do the job for us:
338 * We use the highest bit for cast, this only
339 * works if the highest bit is not
340 * in use (This should not happen)
342 * We used this for all compiler
345 u64ToDouble(u64 value)
348 u64 tmp = value & u64Const(0x7fffffffffffffff);
349 r = (double)(s64)tmp;
350 if (value & u64Const(0x8000000000000000))
351 r += 9.2233720368547758080e18; /* 2^63 */
355 /* Fake up flags for now, as we aren't keeping track of castling
356 availability yet. [HGM] Change of logic: the flag now only
357 indicates the type of castlings allowed by the rule of the game.
358 The actual rights themselves are maintained in the array
359 castlingRights, as part of the game history, and are not probed
365 int flags = F_ALL_CASTLE_OK;
366 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
367 switch (gameInfo.variant) {
369 flags &= ~F_ALL_CASTLE_OK;
370 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
371 flags |= F_IGNORE_CHECK;
373 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
376 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
378 case VariantKriegspiel:
379 flags |= F_KRIEGSPIEL_CAPTURE;
381 case VariantCapaRandom:
382 case VariantFischeRandom:
383 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
384 case VariantNoCastle:
385 case VariantShatranj:
388 flags &= ~F_ALL_CASTLE_OK;
396 FILE *gameFileFP, *debugFP;
399 [AS] Note: sometimes, the sscanf() function is used to parse the input
400 into a fixed-size buffer. Because of this, we must be prepared to
401 receive strings as long as the size of the input buffer, which is currently
402 set to 4K for Windows and 8K for the rest.
403 So, we must either allocate sufficiently large buffers here, or
404 reduce the size of the input buffer in the input reading part.
407 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
408 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
409 char thinkOutput1[MSG_SIZ*10];
411 ChessProgramState first, second;
413 /* premove variables */
416 int premoveFromX = 0;
417 int premoveFromY = 0;
418 int premovePromoChar = 0;
420 Boolean alarmSounded;
421 /* end premove variables */
423 char *ics_prefix = "$";
424 int ics_type = ICS_GENERIC;
426 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
427 int pauseExamForwardMostMove = 0;
428 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
429 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
430 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
431 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
432 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
433 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
434 int whiteFlag = FALSE, blackFlag = FALSE;
435 int userOfferedDraw = FALSE;
436 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
437 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
438 int cmailMoveType[CMAIL_MAX_GAMES];
439 long ics_clock_paused = 0;
440 ProcRef icsPR = NoProc, cmailPR = NoProc;
441 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
442 GameMode gameMode = BeginningOfGame;
443 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
444 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
445 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
446 int hiddenThinkOutputState = 0; /* [AS] */
447 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
448 int adjudicateLossPlies = 6;
449 char white_holding[64], black_holding[64];
450 TimeMark lastNodeCountTime;
451 long lastNodeCount=0;
452 int shiftKey; // [HGM] set by mouse handler
454 int have_sent_ICS_logon = 0;
455 int sending_ICS_login = 0;
456 int sending_ICS_password = 0;
459 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
460 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack;
461 long timeControl_2; /* [AS] Allow separate time controls */
462 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC; /* [HGM] secondary TC: merge of MPS, TC and inc */
463 long timeRemaining[2][MAX_MOVES];
465 TimeMark programStartTime;
466 char ics_handle[MSG_SIZ];
467 int have_set_title = 0;
469 /* animateTraining preserves the state of appData.animate
470 * when Training mode is activated. This allows the
471 * response to be animated when appData.animate == TRUE and
472 * appData.animateDragging == TRUE.
474 Boolean animateTraining;
480 Board boards[MAX_MOVES];
481 /* [HGM] Following 7 needed for accurate legality tests: */
482 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
483 signed char initialRights[BOARD_FILES];
484 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
485 int initialRulePlies, FENrulePlies;
486 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
489 int mute; // mute all sounds
491 // [HGM] vari: next 12 to save and restore variations
492 #define MAX_VARIATIONS 10
493 int framePtr = MAX_MOVES-1; // points to free stack entry
495 int savedFirst[MAX_VARIATIONS];
496 int savedLast[MAX_VARIATIONS];
497 int savedFramePtr[MAX_VARIATIONS];
498 char *savedDetails[MAX_VARIATIONS];
499 ChessMove savedResult[MAX_VARIATIONS];
501 void PushTail P((int firstMove, int lastMove));
502 Boolean PopTail P((Boolean annotate));
503 void CleanupTail P((void));
505 ChessSquare FIDEArray[2][BOARD_FILES] = {
506 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
507 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
508 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
509 BlackKing, BlackBishop, BlackKnight, BlackRook }
512 ChessSquare twoKingsArray[2][BOARD_FILES] = {
513 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
514 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
515 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
516 BlackKing, BlackKing, BlackKnight, BlackRook }
519 ChessSquare KnightmateArray[2][BOARD_FILES] = {
520 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
521 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
522 { BlackRook, BlackMan, BlackBishop, BlackQueen,
523 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
526 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
527 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
528 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
529 { BlackLance, BlackAlfil, BlackMarshall, BlackAngel,
530 BlackKing, BlackMarshall, BlackAlfil, BlackLance }
533 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
534 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
535 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
536 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
537 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
540 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
541 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
542 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackMan, BlackFerz,
544 BlackKing, BlackMan, BlackKnight, BlackRook }
548 #if (BOARD_FILES>=10)
549 ChessSquare ShogiArray[2][BOARD_FILES] = {
550 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
551 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
552 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
553 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
556 ChessSquare XiangqiArray[2][BOARD_FILES] = {
557 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
558 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
559 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
560 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
563 ChessSquare CapablancaArray[2][BOARD_FILES] = {
564 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
565 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
566 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
567 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
570 ChessSquare GreatArray[2][BOARD_FILES] = {
571 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
572 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
573 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
574 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
577 ChessSquare JanusArray[2][BOARD_FILES] = {
578 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
579 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
580 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
581 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
585 ChessSquare GothicArray[2][BOARD_FILES] = {
586 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
587 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
588 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
589 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
592 #define GothicArray CapablancaArray
596 ChessSquare FalconArray[2][BOARD_FILES] = {
597 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
598 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
599 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
600 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
603 #define FalconArray CapablancaArray
606 #else // !(BOARD_FILES>=10)
607 #define XiangqiPosition FIDEArray
608 #define CapablancaArray FIDEArray
609 #define GothicArray FIDEArray
610 #define GreatArray FIDEArray
611 #endif // !(BOARD_FILES>=10)
613 #if (BOARD_FILES>=12)
614 ChessSquare CourierArray[2][BOARD_FILES] = {
615 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
616 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
617 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
618 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
620 #else // !(BOARD_FILES>=12)
621 #define CourierArray CapablancaArray
622 #endif // !(BOARD_FILES>=12)
625 Board initialPosition;
628 /* Convert str to a rating. Checks for special cases of "----",
630 "++++", etc. Also strips ()'s */
632 string_to_rating(str)
635 while(*str && !isdigit(*str)) ++str;
637 return 0; /* One of the special "no rating" cases */
645 /* Init programStats */
646 programStats.movelist[0] = 0;
647 programStats.depth = 0;
648 programStats.nr_moves = 0;
649 programStats.moves_left = 0;
650 programStats.nodes = 0;
651 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
652 programStats.score = 0;
653 programStats.got_only_move = 0;
654 programStats.got_fail = 0;
655 programStats.line_is_book = 0;
661 int matched, min, sec;
663 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
664 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
666 GetTimeMark(&programStartTime);
667 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
670 programStats.ok_to_send = 1;
671 programStats.seen_stat = 0;
674 * Initialize game list
680 * Internet chess server status
682 if (appData.icsActive) {
683 appData.matchMode = FALSE;
684 appData.matchGames = 0;
686 appData.noChessProgram = !appData.zippyPlay;
688 appData.zippyPlay = FALSE;
689 appData.zippyTalk = FALSE;
690 appData.noChessProgram = TRUE;
692 if (*appData.icsHelper != NULLCHAR) {
693 appData.useTelnet = TRUE;
694 appData.telnetProgram = appData.icsHelper;
697 appData.zippyTalk = appData.zippyPlay = FALSE;
700 /* [AS] Initialize pv info list [HGM] and game state */
704 for( i=0; i<=framePtr; i++ ) {
705 pvInfoList[i].depth = -1;
706 boards[i][EP_STATUS] = EP_NONE;
707 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
712 * Parse timeControl resource
714 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
715 appData.movesPerSession)) {
717 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
718 DisplayFatalError(buf, 0, 2);
722 * Parse searchTime resource
724 if (*appData.searchTime != NULLCHAR) {
725 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
727 searchTime = min * 60;
728 } else if (matched == 2) {
729 searchTime = min * 60 + sec;
732 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
733 DisplayFatalError(buf, 0, 2);
737 /* [AS] Adjudication threshold */
738 adjudicateLossThreshold = appData.adjudicateLossThreshold;
740 first.which = _("first");
741 second.which = _("second");
742 first.maybeThinking = second.maybeThinking = FALSE;
743 first.pr = second.pr = NoProc;
744 first.isr = second.isr = NULL;
745 first.sendTime = second.sendTime = 2;
746 first.sendDrawOffers = 1;
747 if (appData.firstPlaysBlack) {
748 first.twoMachinesColor = "black\n";
749 second.twoMachinesColor = "white\n";
751 first.twoMachinesColor = "white\n";
752 second.twoMachinesColor = "black\n";
754 first.program = appData.firstChessProgram;
755 second.program = appData.secondChessProgram;
756 first.host = appData.firstHost;
757 second.host = appData.secondHost;
758 first.dir = appData.firstDirectory;
759 second.dir = appData.secondDirectory;
760 first.other = &second;
761 second.other = &first;
762 first.initString = appData.initString;
763 second.initString = appData.secondInitString;
764 first.computerString = appData.firstComputerString;
765 second.computerString = appData.secondComputerString;
766 first.useSigint = second.useSigint = TRUE;
767 first.useSigterm = second.useSigterm = TRUE;
768 first.reuse = appData.reuseFirst;
769 second.reuse = appData.reuseSecond;
770 first.nps = appData.firstNPS; // [HGM] nps: copy nodes per second
771 second.nps = appData.secondNPS;
772 first.useSetboard = second.useSetboard = FALSE;
773 first.useSAN = second.useSAN = FALSE;
774 first.usePing = second.usePing = FALSE;
775 first.lastPing = second.lastPing = 0;
776 first.lastPong = second.lastPong = 0;
777 first.usePlayother = second.usePlayother = FALSE;
778 first.useColors = second.useColors = TRUE;
779 first.useUsermove = second.useUsermove = FALSE;
780 first.sendICS = second.sendICS = FALSE;
781 first.sendName = second.sendName = appData.icsActive;
782 first.sdKludge = second.sdKludge = FALSE;
783 first.stKludge = second.stKludge = FALSE;
784 TidyProgramName(first.program, first.host, first.tidy);
785 TidyProgramName(second.program, second.host, second.tidy);
786 first.matchWins = second.matchWins = 0;
787 safeStrCpy(first.variants, appData.variant, sizeof(first.variants)/sizeof(first.variants[0]));
788 safeStrCpy(second.variants, appData.variant,sizeof(second.variants)/sizeof(second.variants[0]));
789 first.analysisSupport = second.analysisSupport = 2; /* detect */
790 first.analyzing = second.analyzing = FALSE;
791 first.initDone = second.initDone = FALSE;
793 /* New features added by Tord: */
794 first.useFEN960 = FALSE; second.useFEN960 = FALSE;
795 first.useOOCastle = TRUE; second.useOOCastle = TRUE;
796 /* End of new features added by Tord. */
797 first.fenOverride = appData.fenOverride1;
798 second.fenOverride = appData.fenOverride2;
800 /* [HGM] time odds: set factor for each machine */
801 first.timeOdds = appData.firstTimeOdds;
802 second.timeOdds = appData.secondTimeOdds;
804 if(appData.timeOddsMode) {
805 norm = first.timeOdds;
806 if(norm > second.timeOdds) norm = second.timeOdds;
808 first.timeOdds /= norm;
809 second.timeOdds /= norm;
812 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
813 first.accumulateTC = appData.firstAccumulateTC;
814 second.accumulateTC = appData.secondAccumulateTC;
815 first.maxNrOfSessions = second.maxNrOfSessions = 1;
818 first.debug = second.debug = FALSE;
819 first.supportsNPS = second.supportsNPS = UNKNOWN;
822 first.optionSettings = appData.firstOptions;
823 second.optionSettings = appData.secondOptions;
825 first.scoreIsAbsolute = appData.firstScoreIsAbsolute; /* [AS] */
826 second.scoreIsAbsolute = appData.secondScoreIsAbsolute; /* [AS] */
827 first.isUCI = appData.firstIsUCI; /* [AS] */
828 second.isUCI = appData.secondIsUCI; /* [AS] */
829 first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */
830 second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */
832 if (appData.firstProtocolVersion > PROTOVER
833 || appData.firstProtocolVersion < 1)
838 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
839 appData.firstProtocolVersion);
840 if( (len > MSG_SIZ) && appData.debugMode )
841 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
843 DisplayFatalError(buf, 0, 2);
847 first.protocolVersion = appData.firstProtocolVersion;
850 if (appData.secondProtocolVersion > PROTOVER
851 || appData.secondProtocolVersion < 1)
856 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
857 appData.secondProtocolVersion);
858 if( (len > MSG_SIZ) && appData.debugMode )
859 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
861 DisplayFatalError(buf, 0, 2);
865 second.protocolVersion = appData.secondProtocolVersion;
868 if (appData.icsActive) {
869 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
870 // } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
871 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
872 appData.clockMode = FALSE;
873 first.sendTime = second.sendTime = 0;
877 /* Override some settings from environment variables, for backward
878 compatibility. Unfortunately it's not feasible to have the env
879 vars just set defaults, at least in xboard. Ugh.
881 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
886 if (appData.noChessProgram) {
887 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
888 sprintf(programVersion, "%s", PACKAGE_STRING);
890 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
891 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
892 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
895 if (!appData.icsActive) {
899 /* Check for variants that are supported only in ICS mode,
900 or not at all. Some that are accepted here nevertheless
901 have bugs; see comments below.
903 VariantClass variant = StringToVariant(appData.variant);
905 case VariantBughouse: /* need four players and two boards */
906 case VariantKriegspiel: /* need to hide pieces and move details */
907 /* case VariantFischeRandom: (Fabien: moved below) */
908 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
909 if( (len > MSG_SIZ) && appData.debugMode )
910 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
912 DisplayFatalError(buf, 0, 2);
916 case VariantLoadable:
926 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
927 if( (len > MSG_SIZ) && appData.debugMode )
928 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
930 DisplayFatalError(buf, 0, 2);
933 case VariantXiangqi: /* [HGM] repetition rules not implemented */
934 case VariantFairy: /* [HGM] TestLegality definitely off! */
935 case VariantGothic: /* [HGM] should work */
936 case VariantCapablanca: /* [HGM] should work */
937 case VariantCourier: /* [HGM] initial forced moves not implemented */
938 case VariantShogi: /* [HGM] could still mate with pawn drop */
939 case VariantKnightmate: /* [HGM] should work */
940 case VariantCylinder: /* [HGM] untested */
941 case VariantFalcon: /* [HGM] untested */
942 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
943 offboard interposition not understood */
944 case VariantNormal: /* definitely works! */
945 case VariantWildCastle: /* pieces not automatically shuffled */
946 case VariantNoCastle: /* pieces not automatically shuffled */
947 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
948 case VariantLosers: /* should work except for win condition,
949 and doesn't know captures are mandatory */
950 case VariantSuicide: /* should work except for win condition,
951 and doesn't know captures are mandatory */
952 case VariantGiveaway: /* should work except for win condition,
953 and doesn't know captures are mandatory */
954 case VariantTwoKings: /* should work */
955 case VariantAtomic: /* should work except for win condition */
956 case Variant3Check: /* should work except for win condition */
957 case VariantShatranj: /* should work except for all win conditions */
958 case VariantMakruk: /* should work except for daw countdown */
959 case VariantBerolina: /* might work if TestLegality is off */
960 case VariantCapaRandom: /* should work */
961 case VariantJanus: /* should work */
962 case VariantSuper: /* experimental */
963 case VariantGreat: /* experimental, requires legality testing to be off */
968 InitEngineUCI( installDir, &first ); // [HGM] moved here from winboard.c, to make available in xboard
969 InitEngineUCI( installDir, &second );
972 int NextIntegerFromString( char ** str, long * value )
977 while( *s == ' ' || *s == '\t' ) {
983 if( *s >= '0' && *s <= '9' ) {
984 while( *s >= '0' && *s <= '9' ) {
985 *value = *value * 10 + (*s - '0');
997 int NextTimeControlFromString( char ** str, long * value )
1000 int result = NextIntegerFromString( str, &temp );
1003 *value = temp * 60; /* Minutes */
1004 if( **str == ':' ) {
1006 result = NextIntegerFromString( str, &temp );
1007 *value += temp; /* Seconds */
1014 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc, int *incType)
1015 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1016 int result = -1, type = 0; long temp, temp2;
1018 if(**str != ':') return -1; // old params remain in force!
1020 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1021 if( NextIntegerFromString( str, &temp ) ) return -1;
1022 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1025 /* time only: incremental or sudden-death time control */
1026 if(**str == '+') { /* increment follows; read it */
1028 if(**str == '!') type = *(*str)++; // Bronstein TC
1029 if(result = NextIntegerFromString( str, &temp2)) return -1;
1030 *inc = temp2 * 1000;
1031 if(**str == '.') { // read fraction of increment
1032 char *start = ++(*str);
1033 if(result = NextIntegerFromString( str, &temp2)) return -1;
1035 while(start++ < *str) temp2 /= 10;
1039 *moves = 0; *tc = temp * 1000; *incType = type;
1043 (*str)++; /* classical time control */
1044 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1055 int GetTimeQuota(int movenr, int lastUsed, char *tcString)
1056 { /* [HGM] get time to add from the multi-session time-control string */
1057 int incType, moves=1; /* kludge to force reading of first session */
1058 long time, increment;
1061 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1062 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", tcString);
1064 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1065 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1066 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1067 if(movenr == -1) return time; /* last move before new session */
1068 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1069 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1070 if(!moves) return increment; /* current session is incremental */
1071 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1072 } while(movenr >= -1); /* try again for next session */
1074 return 0; // no new time quota on this move
1078 ParseTimeControl(tc, ti, mps)
1085 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1088 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1089 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1090 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1094 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1096 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1099 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1101 snprintf(buf, MSG_SIZ, ":%s", mytc);
1103 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1105 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1110 /* Parse second time control */
1113 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1121 timeControl_2 = tc2 * 1000;
1131 timeControl = tc1 * 1000;
1134 timeIncrement = ti * 1000; /* convert to ms */
1135 movesPerSession = 0;
1138 movesPerSession = mps;
1146 if (appData.debugMode) {
1147 fprintf(debugFP, "%s\n", programVersion);
1150 set_cont_sequence(appData.wrapContSeq);
1151 if (appData.matchGames > 0) {
1152 appData.matchMode = TRUE;
1153 } else if (appData.matchMode) {
1154 appData.matchGames = 1;
1156 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1157 appData.matchGames = appData.sameColorGames;
1158 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1159 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1160 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1163 if (appData.noChessProgram || first.protocolVersion == 1) {
1166 /* kludge: allow timeout for initial "feature" commands */
1168 DisplayMessage("", _("Starting chess program"));
1169 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1174 InitBackEnd3 P((void))
1176 GameMode initialMode;
1180 InitChessProgram(&first, startedFromSetupPosition);
1182 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1183 free(programVersion);
1184 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1185 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1188 if (appData.icsActive) {
1190 /* [DM] Make a console window if needed [HGM] merged ifs */
1196 if (*appData.icsCommPort != NULLCHAR)
1197 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1198 appData.icsCommPort);
1200 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1201 appData.icsHost, appData.icsPort);
1203 if( (len > MSG_SIZ) && appData.debugMode )
1204 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1206 DisplayFatalError(buf, err, 1);
1211 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1213 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1214 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1215 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1216 } else if (appData.noChessProgram) {
1222 if (*appData.cmailGameName != NULLCHAR) {
1224 OpenLoopback(&cmailPR);
1226 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1230 DisplayMessage("", "");
1231 if (StrCaseCmp(appData.initialMode, "") == 0) {
1232 initialMode = BeginningOfGame;
1233 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1234 initialMode = TwoMachinesPlay;
1235 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1236 initialMode = AnalyzeFile;
1237 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1238 initialMode = AnalyzeMode;
1239 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1240 initialMode = MachinePlaysWhite;
1241 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1242 initialMode = MachinePlaysBlack;
1243 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1244 initialMode = EditGame;
1245 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1246 initialMode = EditPosition;
1247 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1248 initialMode = Training;
1250 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1251 if( (len > MSG_SIZ) && appData.debugMode )
1252 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1254 DisplayFatalError(buf, 0, 2);
1258 if (appData.matchMode) {
1259 /* Set up machine vs. machine match */
1260 if (appData.noChessProgram) {
1261 DisplayFatalError(_("Can't have a match with no chess programs"),
1267 if (*appData.loadGameFile != NULLCHAR) {
1268 int index = appData.loadGameIndex; // [HGM] autoinc
1269 if(index<0) lastIndex = index = 1;
1270 if (!LoadGameFromFile(appData.loadGameFile,
1272 appData.loadGameFile, FALSE)) {
1273 DisplayFatalError(_("Bad game file"), 0, 1);
1276 } else if (*appData.loadPositionFile != NULLCHAR) {
1277 int index = appData.loadPositionIndex; // [HGM] autoinc
1278 if(index<0) lastIndex = index = 1;
1279 if (!LoadPositionFromFile(appData.loadPositionFile,
1281 appData.loadPositionFile)) {
1282 DisplayFatalError(_("Bad position file"), 0, 1);
1287 } else if (*appData.cmailGameName != NULLCHAR) {
1288 /* Set up cmail mode */
1289 ReloadCmailMsgEvent(TRUE);
1291 /* Set up other modes */
1292 if (initialMode == AnalyzeFile) {
1293 if (*appData.loadGameFile == NULLCHAR) {
1294 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1298 if (*appData.loadGameFile != NULLCHAR) {
1299 (void) LoadGameFromFile(appData.loadGameFile,
1300 appData.loadGameIndex,
1301 appData.loadGameFile, TRUE);
1302 } else if (*appData.loadPositionFile != NULLCHAR) {
1303 (void) LoadPositionFromFile(appData.loadPositionFile,
1304 appData.loadPositionIndex,
1305 appData.loadPositionFile);
1306 /* [HGM] try to make self-starting even after FEN load */
1307 /* to allow automatic setup of fairy variants with wtm */
1308 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1309 gameMode = BeginningOfGame;
1310 setboardSpoiledMachineBlack = 1;
1312 /* [HGM] loadPos: make that every new game uses the setup */
1313 /* from file as long as we do not switch variant */
1314 if(!blackPlaysFirst) {
1315 startedFromPositionFile = TRUE;
1316 CopyBoard(filePosition, boards[0]);
1319 if (initialMode == AnalyzeMode) {
1320 if (appData.noChessProgram) {
1321 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1324 if (appData.icsActive) {
1325 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1329 } else if (initialMode == AnalyzeFile) {
1330 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1331 ShowThinkingEvent();
1333 AnalysisPeriodicEvent(1);
1334 } else if (initialMode == MachinePlaysWhite) {
1335 if (appData.noChessProgram) {
1336 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1340 if (appData.icsActive) {
1341 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1345 MachineWhiteEvent();
1346 } else if (initialMode == MachinePlaysBlack) {
1347 if (appData.noChessProgram) {
1348 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1352 if (appData.icsActive) {
1353 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1357 MachineBlackEvent();
1358 } else if (initialMode == TwoMachinesPlay) {
1359 if (appData.noChessProgram) {
1360 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1364 if (appData.icsActive) {
1365 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1370 } else if (initialMode == EditGame) {
1372 } else if (initialMode == EditPosition) {
1373 EditPositionEvent();
1374 } else if (initialMode == Training) {
1375 if (*appData.loadGameFile == NULLCHAR) {
1376 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1385 * Establish will establish a contact to a remote host.port.
1386 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1387 * used to talk to the host.
1388 * Returns 0 if okay, error code if not.
1395 if (*appData.icsCommPort != NULLCHAR) {
1396 /* Talk to the host through a serial comm port */
1397 return OpenCommPort(appData.icsCommPort, &icsPR);
1399 } else if (*appData.gateway != NULLCHAR) {
1400 if (*appData.remoteShell == NULLCHAR) {
1401 /* Use the rcmd protocol to run telnet program on a gateway host */
1402 snprintf(buf, sizeof(buf), "%s %s %s",
1403 appData.telnetProgram, appData.icsHost, appData.icsPort);
1404 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1407 /* Use the rsh program to run telnet program on a gateway host */
1408 if (*appData.remoteUser == NULLCHAR) {
1409 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1410 appData.gateway, appData.telnetProgram,
1411 appData.icsHost, appData.icsPort);
1413 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1414 appData.remoteShell, appData.gateway,
1415 appData.remoteUser, appData.telnetProgram,
1416 appData.icsHost, appData.icsPort);
1418 return StartChildProcess(buf, "", &icsPR);
1421 } else if (appData.useTelnet) {
1422 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1425 /* TCP socket interface differs somewhat between
1426 Unix and NT; handle details in the front end.
1428 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1432 void EscapeExpand(char *p, char *q)
1433 { // [HGM] initstring: routine to shape up string arguments
1434 while(*p++ = *q++) if(p[-1] == '\\')
1436 case 'n': p[-1] = '\n'; break;
1437 case 'r': p[-1] = '\r'; break;
1438 case 't': p[-1] = '\t'; break;
1439 case '\\': p[-1] = '\\'; break;
1440 case 0: *p = 0; return;
1441 default: p[-1] = q[-1]; break;
1446 show_bytes(fp, buf, count)
1452 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1453 fprintf(fp, "\\%03o", *buf & 0xff);
1462 /* Returns an errno value */
1464 OutputMaybeTelnet(pr, message, count, outError)
1470 char buf[8192], *p, *q, *buflim;
1471 int left, newcount, outcount;
1473 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1474 *appData.gateway != NULLCHAR) {
1475 if (appData.debugMode) {
1476 fprintf(debugFP, ">ICS: ");
1477 show_bytes(debugFP, message, count);
1478 fprintf(debugFP, "\n");
1480 return OutputToProcess(pr, message, count, outError);
1483 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1490 if (appData.debugMode) {
1491 fprintf(debugFP, ">ICS: ");
1492 show_bytes(debugFP, buf, newcount);
1493 fprintf(debugFP, "\n");
1495 outcount = OutputToProcess(pr, buf, newcount, outError);
1496 if (outcount < newcount) return -1; /* to be sure */
1503 } else if (((unsigned char) *p) == TN_IAC) {
1504 *q++ = (char) TN_IAC;
1511 if (appData.debugMode) {
1512 fprintf(debugFP, ">ICS: ");
1513 show_bytes(debugFP, buf, newcount);
1514 fprintf(debugFP, "\n");
1516 outcount = OutputToProcess(pr, buf, newcount, outError);
1517 if (outcount < newcount) return -1; /* to be sure */
1522 read_from_player(isr, closure, message, count, error)
1529 int outError, outCount;
1530 static int gotEof = 0;
1532 /* Pass data read from player on to ICS */
1535 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1536 if (outCount < count) {
1537 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1539 } else if (count < 0) {
1540 RemoveInputSource(isr);
1541 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1542 } else if (gotEof++ > 0) {
1543 RemoveInputSource(isr);
1544 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1550 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1551 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1552 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1553 SendToICS("date\n");
1554 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1557 /* added routine for printf style output to ics */
1558 void ics_printf(char *format, ...)
1560 char buffer[MSG_SIZ];
1563 va_start(args, format);
1564 vsnprintf(buffer, sizeof(buffer), format, args);
1565 buffer[sizeof(buffer)-1] = '\0';
1574 int count, outCount, outError;
1576 if (icsPR == NULL) return;
1579 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1580 if (outCount < count) {
1581 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1585 /* This is used for sending logon scripts to the ICS. Sending
1586 without a delay causes problems when using timestamp on ICC
1587 (at least on my machine). */
1589 SendToICSDelayed(s,msdelay)
1593 int count, outCount, outError;
1595 if (icsPR == NULL) return;
1598 if (appData.debugMode) {
1599 fprintf(debugFP, ">ICS: ");
1600 show_bytes(debugFP, s, count);
1601 fprintf(debugFP, "\n");
1603 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1605 if (outCount < count) {
1606 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1611 /* Remove all highlighting escape sequences in s
1612 Also deletes any suffix starting with '('
1615 StripHighlightAndTitle(s)
1618 static char retbuf[MSG_SIZ];
1621 while (*s != NULLCHAR) {
1622 while (*s == '\033') {
1623 while (*s != NULLCHAR && !isalpha(*s)) s++;
1624 if (*s != NULLCHAR) s++;
1626 while (*s != NULLCHAR && *s != '\033') {
1627 if (*s == '(' || *s == '[') {
1638 /* Remove all highlighting escape sequences in s */
1643 static char retbuf[MSG_SIZ];
1646 while (*s != NULLCHAR) {
1647 while (*s == '\033') {
1648 while (*s != NULLCHAR && !isalpha(*s)) s++;
1649 if (*s != NULLCHAR) s++;
1651 while (*s != NULLCHAR && *s != '\033') {
1659 char *variantNames[] = VARIANT_NAMES;
1664 return variantNames[v];
1668 /* Identify a variant from the strings the chess servers use or the
1669 PGN Variant tag names we use. */
1676 VariantClass v = VariantNormal;
1677 int i, found = FALSE;
1683 /* [HGM] skip over optional board-size prefixes */
1684 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1685 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1686 while( *e++ != '_');
1689 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1693 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1694 if (StrCaseStr(e, variantNames[i])) {
1695 v = (VariantClass) i;
1702 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1703 || StrCaseStr(e, "wild/fr")
1704 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1705 v = VariantFischeRandom;
1706 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1707 (i = 1, p = StrCaseStr(e, "w"))) {
1709 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1716 case 0: /* FICS only, actually */
1718 /* Castling legal even if K starts on d-file */
1719 v = VariantWildCastle;
1724 /* Castling illegal even if K & R happen to start in
1725 normal positions. */
1726 v = VariantNoCastle;
1739 /* Castling legal iff K & R start in normal positions */
1745 /* Special wilds for position setup; unclear what to do here */
1746 v = VariantLoadable;
1749 /* Bizarre ICC game */
1750 v = VariantTwoKings;
1753 v = VariantKriegspiel;
1759 v = VariantFischeRandom;
1762 v = VariantCrazyhouse;
1765 v = VariantBughouse;
1771 /* Not quite the same as FICS suicide! */
1772 v = VariantGiveaway;
1778 v = VariantShatranj;
1781 /* Temporary names for future ICC types. The name *will* change in
1782 the next xboard/WinBoard release after ICC defines it. */
1820 v = VariantCapablanca;
1823 v = VariantKnightmate;
1829 v = VariantCylinder;
1835 v = VariantCapaRandom;
1838 v = VariantBerolina;
1850 /* Found "wild" or "w" in the string but no number;
1851 must assume it's normal chess. */
1855 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
1856 if( (len > MSG_SIZ) && appData.debugMode )
1857 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
1859 DisplayError(buf, 0);
1865 if (appData.debugMode) {
1866 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1867 e, wnum, VariantName(v));
1872 static int leftover_start = 0, leftover_len = 0;
1873 char star_match[STAR_MATCH_N][MSG_SIZ];
1875 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1876 advance *index beyond it, and set leftover_start to the new value of
1877 *index; else return FALSE. If pattern contains the character '*', it
1878 matches any sequence of characters not containing '\r', '\n', or the
1879 character following the '*' (if any), and the matched sequence(s) are
1880 copied into star_match.
1883 looking_at(buf, index, pattern)
1888 char *bufp = &buf[*index], *patternp = pattern;
1890 char *matchp = star_match[0];
1893 if (*patternp == NULLCHAR) {
1894 *index = leftover_start = bufp - buf;
1898 if (*bufp == NULLCHAR) return FALSE;
1899 if (*patternp == '*') {
1900 if (*bufp == *(patternp + 1)) {
1902 matchp = star_match[++star_count];
1906 } else if (*bufp == '\n' || *bufp == '\r') {
1908 if (*patternp == NULLCHAR)
1913 *matchp++ = *bufp++;
1917 if (*patternp != *bufp) return FALSE;
1924 SendToPlayer(data, length)
1928 int error, outCount;
1929 outCount = OutputToProcess(NoProc, data, length, &error);
1930 if (outCount < length) {
1931 DisplayFatalError(_("Error writing to display"), error, 1);
1936 PackHolding(packed, holding)
1948 switch (runlength) {
1959 sprintf(q, "%d", runlength);
1971 /* Telnet protocol requests from the front end */
1973 TelnetRequest(ddww, option)
1974 unsigned char ddww, option;
1976 unsigned char msg[3];
1977 int outCount, outError;
1979 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1981 if (appData.debugMode) {
1982 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1998 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2007 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2010 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2015 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2017 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2024 if (!appData.icsActive) return;
2025 TelnetRequest(TN_DO, TN_ECHO);
2031 if (!appData.icsActive) return;
2032 TelnetRequest(TN_DONT, TN_ECHO);
2036 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2038 /* put the holdings sent to us by the server on the board holdings area */
2039 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2043 if(gameInfo.holdingsWidth < 2) return;
2044 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2045 return; // prevent overwriting by pre-board holdings
2047 if( (int)lowestPiece >= BlackPawn ) {
2050 holdingsStartRow = BOARD_HEIGHT-1;
2053 holdingsColumn = BOARD_WIDTH-1;
2054 countsColumn = BOARD_WIDTH-2;
2055 holdingsStartRow = 0;
2059 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2060 board[i][holdingsColumn] = EmptySquare;
2061 board[i][countsColumn] = (ChessSquare) 0;
2063 while( (p=*holdings++) != NULLCHAR ) {
2064 piece = CharToPiece( ToUpper(p) );
2065 if(piece == EmptySquare) continue;
2066 /*j = (int) piece - (int) WhitePawn;*/
2067 j = PieceToNumber(piece);
2068 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2069 if(j < 0) continue; /* should not happen */
2070 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2071 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2072 board[holdingsStartRow+j*direction][countsColumn]++;
2078 VariantSwitch(Board board, VariantClass newVariant)
2080 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2081 static Board oldBoard;
2083 startedFromPositionFile = FALSE;
2084 if(gameInfo.variant == newVariant) return;
2086 /* [HGM] This routine is called each time an assignment is made to
2087 * gameInfo.variant during a game, to make sure the board sizes
2088 * are set to match the new variant. If that means adding or deleting
2089 * holdings, we shift the playing board accordingly
2090 * This kludge is needed because in ICS observe mode, we get boards
2091 * of an ongoing game without knowing the variant, and learn about the
2092 * latter only later. This can be because of the move list we requested,
2093 * in which case the game history is refilled from the beginning anyway,
2094 * but also when receiving holdings of a crazyhouse game. In the latter
2095 * case we want to add those holdings to the already received position.
2099 if (appData.debugMode) {
2100 fprintf(debugFP, "Switch board from %s to %s\n",
2101 VariantName(gameInfo.variant), VariantName(newVariant));
2102 setbuf(debugFP, NULL);
2104 shuffleOpenings = 0; /* [HGM] shuffle */
2105 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2109 newWidth = 9; newHeight = 9;
2110 gameInfo.holdingsSize = 7;
2111 case VariantBughouse:
2112 case VariantCrazyhouse:
2113 newHoldingsWidth = 2; break;
2117 newHoldingsWidth = 2;
2118 gameInfo.holdingsSize = 8;
2121 case VariantCapablanca:
2122 case VariantCapaRandom:
2125 newHoldingsWidth = gameInfo.holdingsSize = 0;
2128 if(newWidth != gameInfo.boardWidth ||
2129 newHeight != gameInfo.boardHeight ||
2130 newHoldingsWidth != gameInfo.holdingsWidth ) {
2132 /* shift position to new playing area, if needed */
2133 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2134 for(i=0; i<BOARD_HEIGHT; i++)
2135 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2136 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2138 for(i=0; i<newHeight; i++) {
2139 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2140 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2142 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2143 for(i=0; i<BOARD_HEIGHT; i++)
2144 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2145 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2148 gameInfo.boardWidth = newWidth;
2149 gameInfo.boardHeight = newHeight;
2150 gameInfo.holdingsWidth = newHoldingsWidth;
2151 gameInfo.variant = newVariant;
2152 InitDrawingSizes(-2, 0);
2153 } else gameInfo.variant = newVariant;
2154 CopyBoard(oldBoard, board); // remember correctly formatted board
2155 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2156 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2159 static int loggedOn = FALSE;
2161 /*-- Game start info cache: --*/
2163 char gs_kind[MSG_SIZ];
2164 static char player1Name[128] = "";
2165 static char player2Name[128] = "";
2166 static char cont_seq[] = "\n\\ ";
2167 static int player1Rating = -1;
2168 static int player2Rating = -1;
2169 /*----------------------------*/
2171 ColorClass curColor = ColorNormal;
2172 int suppressKibitz = 0;
2175 Boolean soughtPending = FALSE;
2176 Boolean seekGraphUp;
2177 #define MAX_SEEK_ADS 200
2179 char *seekAdList[MAX_SEEK_ADS];
2180 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2181 float tcList[MAX_SEEK_ADS];
2182 char colorList[MAX_SEEK_ADS];
2183 int nrOfSeekAds = 0;
2184 int minRating = 1010, maxRating = 2800;
2185 int hMargin = 10, vMargin = 20, h, w;
2186 extern int squareSize, lineGap;
2191 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2192 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2193 if(r < minRating+100 && r >=0 ) r = minRating+100;
2194 if(r > maxRating) r = maxRating;
2195 if(tc < 1.) tc = 1.;
2196 if(tc > 95.) tc = 95.;
2197 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2198 y = ((double)r - minRating)/(maxRating - minRating)
2199 * (h-vMargin-squareSize/8-1) + vMargin;
2200 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2201 if(strstr(seekAdList[i], " u ")) color = 1;
2202 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2203 !strstr(seekAdList[i], "bullet") &&
2204 !strstr(seekAdList[i], "blitz") &&
2205 !strstr(seekAdList[i], "standard") ) color = 2;
2206 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2207 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2211 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2213 char buf[MSG_SIZ], *ext = "";
2214 VariantClass v = StringToVariant(type);
2215 if(strstr(type, "wild")) {
2216 ext = type + 4; // append wild number
2217 if(v == VariantFischeRandom) type = "chess960"; else
2218 if(v == VariantLoadable) type = "setup"; else
2219 type = VariantName(v);
2221 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2222 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2223 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2224 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2225 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2226 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2227 seekNrList[nrOfSeekAds] = nr;
2228 zList[nrOfSeekAds] = 0;
2229 seekAdList[nrOfSeekAds++] = StrSave(buf);
2230 if(plot) PlotSeekAd(nrOfSeekAds-1);
2237 int x = xList[i], y = yList[i], d=squareSize/4, k;
2238 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2239 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2240 // now replot every dot that overlapped
2241 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2242 int xx = xList[k], yy = yList[k];
2243 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2244 DrawSeekDot(xx, yy, colorList[k]);
2249 RemoveSeekAd(int nr)
2252 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2254 if(seekAdList[i]) free(seekAdList[i]);
2255 seekAdList[i] = seekAdList[--nrOfSeekAds];
2256 seekNrList[i] = seekNrList[nrOfSeekAds];
2257 ratingList[i] = ratingList[nrOfSeekAds];
2258 colorList[i] = colorList[nrOfSeekAds];
2259 tcList[i] = tcList[nrOfSeekAds];
2260 xList[i] = xList[nrOfSeekAds];
2261 yList[i] = yList[nrOfSeekAds];
2262 zList[i] = zList[nrOfSeekAds];
2263 seekAdList[nrOfSeekAds] = NULL;
2269 MatchSoughtLine(char *line)
2271 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2272 int nr, base, inc, u=0; char dummy;
2274 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2275 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2277 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2278 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2279 // match: compact and save the line
2280 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2290 if(!seekGraphUp) return FALSE;
2291 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2292 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2294 DrawSeekBackground(0, 0, w, h);
2295 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2296 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2297 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2298 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2300 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2303 snprintf(buf, MSG_SIZ, "%d", i);
2304 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2307 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2308 for(i=1; i<100; i+=(i<10?1:5)) {
2309 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2310 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2311 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2313 snprintf(buf, MSG_SIZ, "%d", i);
2314 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2317 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2321 int SeekGraphClick(ClickType click, int x, int y, int moving)
2323 static int lastDown = 0, displayed = 0, lastSecond;
2324 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2325 if(click == Release || moving) return FALSE;
2327 soughtPending = TRUE;
2328 SendToICS(ics_prefix);
2329 SendToICS("sought\n"); // should this be "sought all"?
2330 } else { // issue challenge based on clicked ad
2331 int dist = 10000; int i, closest = 0, second = 0;
2332 for(i=0; i<nrOfSeekAds; i++) {
2333 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2334 if(d < dist) { dist = d; closest = i; }
2335 second += (d - zList[i] < 120); // count in-range ads
2336 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2340 second = (second > 1);
2341 if(displayed != closest || second != lastSecond) {
2342 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2343 lastSecond = second; displayed = closest;
2345 if(click == Press) {
2346 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2349 } // on press 'hit', only show info
2350 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2351 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2352 SendToICS(ics_prefix);
2354 return TRUE; // let incoming board of started game pop down the graph
2355 } else if(click == Release) { // release 'miss' is ignored
2356 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2357 if(moving == 2) { // right up-click
2358 nrOfSeekAds = 0; // refresh graph
2359 soughtPending = TRUE;
2360 SendToICS(ics_prefix);
2361 SendToICS("sought\n"); // should this be "sought all"?
2364 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2365 // press miss or release hit 'pop down' seek graph
2366 seekGraphUp = FALSE;
2367 DrawPosition(TRUE, NULL);
2373 read_from_ics(isr, closure, data, count, error)
2380 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2381 #define STARTED_NONE 0
2382 #define STARTED_MOVES 1
2383 #define STARTED_BOARD 2
2384 #define STARTED_OBSERVE 3
2385 #define STARTED_HOLDINGS 4
2386 #define STARTED_CHATTER 5
2387 #define STARTED_COMMENT 6
2388 #define STARTED_MOVES_NOHIDE 7
2390 static int started = STARTED_NONE;
2391 static char parse[20000];
2392 static int parse_pos = 0;
2393 static char buf[BUF_SIZE + 1];
2394 static int firstTime = TRUE, intfSet = FALSE;
2395 static ColorClass prevColor = ColorNormal;
2396 static int savingComment = FALSE;
2397 static int cmatch = 0; // continuation sequence match
2404 int backup; /* [DM] For zippy color lines */
2406 char talker[MSG_SIZ]; // [HGM] chat
2409 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2411 if (appData.debugMode) {
2413 fprintf(debugFP, "<ICS: ");
2414 show_bytes(debugFP, data, count);
2415 fprintf(debugFP, "\n");
2419 if (appData.debugMode) { int f = forwardMostMove;
2420 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2421 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2422 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2425 /* If last read ended with a partial line that we couldn't parse,
2426 prepend it to the new read and try again. */
2427 if (leftover_len > 0) {
2428 for (i=0; i<leftover_len; i++)
2429 buf[i] = buf[leftover_start + i];
2432 /* copy new characters into the buffer */
2433 bp = buf + leftover_len;
2434 buf_len=leftover_len;
2435 for (i=0; i<count; i++)
2438 if (data[i] == '\r')
2441 // join lines split by ICS?
2442 if (!appData.noJoin)
2445 Joining just consists of finding matches against the
2446 continuation sequence, and discarding that sequence
2447 if found instead of copying it. So, until a match
2448 fails, there's nothing to do since it might be the
2449 complete sequence, and thus, something we don't want
2452 if (data[i] == cont_seq[cmatch])
2455 if (cmatch == strlen(cont_seq))
2457 cmatch = 0; // complete match. just reset the counter
2460 it's possible for the ICS to not include the space
2461 at the end of the last word, making our [correct]
2462 join operation fuse two separate words. the server
2463 does this when the space occurs at the width setting.
2465 if (!buf_len || buf[buf_len-1] != ' ')
2476 match failed, so we have to copy what matched before
2477 falling through and copying this character. In reality,
2478 this will only ever be just the newline character, but
2479 it doesn't hurt to be precise.
2481 strncpy(bp, cont_seq, cmatch);
2493 buf[buf_len] = NULLCHAR;
2494 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2499 while (i < buf_len) {
2500 /* Deal with part of the TELNET option negotiation
2501 protocol. We refuse to do anything beyond the
2502 defaults, except that we allow the WILL ECHO option,
2503 which ICS uses to turn off password echoing when we are
2504 directly connected to it. We reject this option
2505 if localLineEditing mode is on (always on in xboard)
2506 and we are talking to port 23, which might be a real
2507 telnet server that will try to keep WILL ECHO on permanently.
2509 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2510 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2511 unsigned char option;
2513 switch ((unsigned char) buf[++i]) {
2515 if (appData.debugMode)
2516 fprintf(debugFP, "\n<WILL ");
2517 switch (option = (unsigned char) buf[++i]) {
2519 if (appData.debugMode)
2520 fprintf(debugFP, "ECHO ");
2521 /* Reply only if this is a change, according
2522 to the protocol rules. */
2523 if (remoteEchoOption) break;
2524 if (appData.localLineEditing &&
2525 atoi(appData.icsPort) == TN_PORT) {
2526 TelnetRequest(TN_DONT, TN_ECHO);
2529 TelnetRequest(TN_DO, TN_ECHO);
2530 remoteEchoOption = TRUE;
2534 if (appData.debugMode)
2535 fprintf(debugFP, "%d ", option);
2536 /* Whatever this is, we don't want it. */
2537 TelnetRequest(TN_DONT, option);
2542 if (appData.debugMode)
2543 fprintf(debugFP, "\n<WONT ");
2544 switch (option = (unsigned char) buf[++i]) {
2546 if (appData.debugMode)
2547 fprintf(debugFP, "ECHO ");
2548 /* Reply only if this is a change, according
2549 to the protocol rules. */
2550 if (!remoteEchoOption) break;
2552 TelnetRequest(TN_DONT, TN_ECHO);
2553 remoteEchoOption = FALSE;
2556 if (appData.debugMode)
2557 fprintf(debugFP, "%d ", (unsigned char) option);
2558 /* Whatever this is, it must already be turned
2559 off, because we never agree to turn on
2560 anything non-default, so according to the
2561 protocol rules, we don't reply. */
2566 if (appData.debugMode)
2567 fprintf(debugFP, "\n<DO ");
2568 switch (option = (unsigned char) buf[++i]) {
2570 /* Whatever this is, we refuse to do it. */
2571 if (appData.debugMode)
2572 fprintf(debugFP, "%d ", option);
2573 TelnetRequest(TN_WONT, option);
2578 if (appData.debugMode)
2579 fprintf(debugFP, "\n<DONT ");
2580 switch (option = (unsigned char) buf[++i]) {
2582 if (appData.debugMode)
2583 fprintf(debugFP, "%d ", option);
2584 /* Whatever this is, we are already not doing
2585 it, because we never agree to do anything
2586 non-default, so according to the protocol
2587 rules, we don't reply. */
2592 if (appData.debugMode)
2593 fprintf(debugFP, "\n<IAC ");
2594 /* Doubled IAC; pass it through */
2598 if (appData.debugMode)
2599 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2600 /* Drop all other telnet commands on the floor */
2603 if (oldi > next_out)
2604 SendToPlayer(&buf[next_out], oldi - next_out);
2610 /* OK, this at least will *usually* work */
2611 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2615 if (loggedOn && !intfSet) {
2616 if (ics_type == ICS_ICC) {
2617 snprintf(str, MSG_SIZ,
2618 "/set-quietly interface %s\n/set-quietly style 12\n",
2620 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2621 strcat(str, "/set-2 51 1\n/set seek 1\n");
2622 } else if (ics_type == ICS_CHESSNET) {
2623 snprintf(str, MSG_SIZ, "/style 12\n");
2625 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2626 strcat(str, programVersion);
2627 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2628 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2629 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2631 strcat(str, "$iset nohighlight 1\n");
2633 strcat(str, "$iset lock 1\n$style 12\n");
2636 NotifyFrontendLogin();
2640 if (started == STARTED_COMMENT) {
2641 /* Accumulate characters in comment */
2642 parse[parse_pos++] = buf[i];
2643 if (buf[i] == '\n') {
2644 parse[parse_pos] = NULLCHAR;
2645 if(chattingPartner>=0) {
2647 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2648 OutputChatMessage(chattingPartner, mess);
2649 chattingPartner = -1;
2650 next_out = i+1; // [HGM] suppress printing in ICS window
2652 if(!suppressKibitz) // [HGM] kibitz
2653 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2654 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2655 int nrDigit = 0, nrAlph = 0, j;
2656 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2657 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2658 parse[parse_pos] = NULLCHAR;
2659 // try to be smart: if it does not look like search info, it should go to
2660 // ICS interaction window after all, not to engine-output window.
2661 for(j=0; j<parse_pos; j++) { // count letters and digits
2662 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2663 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2664 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2666 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2667 int depth=0; float score;
2668 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2669 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2670 pvInfoList[forwardMostMove-1].depth = depth;
2671 pvInfoList[forwardMostMove-1].score = 100*score;
2673 OutputKibitz(suppressKibitz, parse);
2676 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2677 SendToPlayer(tmp, strlen(tmp));
2679 next_out = i+1; // [HGM] suppress printing in ICS window
2681 started = STARTED_NONE;
2683 /* Don't match patterns against characters in comment */
2688 if (started == STARTED_CHATTER) {
2689 if (buf[i] != '\n') {
2690 /* Don't match patterns against characters in chatter */
2694 started = STARTED_NONE;
2695 if(suppressKibitz) next_out = i+1;
2698 /* Kludge to deal with rcmd protocol */
2699 if (firstTime && looking_at(buf, &i, "\001*")) {
2700 DisplayFatalError(&buf[1], 0, 1);
2706 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2709 if (appData.debugMode)
2710 fprintf(debugFP, "ics_type %d\n", ics_type);
2713 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2714 ics_type = ICS_FICS;
2716 if (appData.debugMode)
2717 fprintf(debugFP, "ics_type %d\n", ics_type);
2720 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2721 ics_type = ICS_CHESSNET;
2723 if (appData.debugMode)
2724 fprintf(debugFP, "ics_type %d\n", ics_type);
2729 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2730 looking_at(buf, &i, "Logging you in as \"*\"") ||
2731 looking_at(buf, &i, "will be \"*\""))) {
2732 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
2736 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2738 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2739 DisplayIcsInteractionTitle(buf);
2740 have_set_title = TRUE;
2743 /* skip finger notes */
2744 if (started == STARTED_NONE &&
2745 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2746 (buf[i] == '1' && buf[i+1] == '0')) &&
2747 buf[i+2] == ':' && buf[i+3] == ' ') {
2748 started = STARTED_CHATTER;
2754 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2755 if(appData.seekGraph) {
2756 if(soughtPending && MatchSoughtLine(buf+i)) {
2757 i = strstr(buf+i, "rated") - buf;
2758 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2759 next_out = leftover_start = i;
2760 started = STARTED_CHATTER;
2761 suppressKibitz = TRUE;
2764 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2765 && looking_at(buf, &i, "* ads displayed")) {
2766 soughtPending = FALSE;
2771 if(appData.autoRefresh) {
2772 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2773 int s = (ics_type == ICS_ICC); // ICC format differs
2775 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2776 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2777 looking_at(buf, &i, "*% "); // eat prompt
2778 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2779 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2780 next_out = i; // suppress
2783 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2784 char *p = star_match[0];
2786 if(seekGraphUp) RemoveSeekAd(atoi(p));
2787 while(*p && *p++ != ' '); // next
2789 looking_at(buf, &i, "*% "); // eat prompt
2790 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2797 /* skip formula vars */
2798 if (started == STARTED_NONE &&
2799 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2800 started = STARTED_CHATTER;
2805 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2806 if (appData.autoKibitz && started == STARTED_NONE &&
2807 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2808 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2809 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2810 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2811 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2812 suppressKibitz = TRUE;
2813 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2815 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2816 && (gameMode == IcsPlayingWhite)) ||
2817 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2818 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2819 started = STARTED_CHATTER; // own kibitz we simply discard
2821 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2822 parse_pos = 0; parse[0] = NULLCHAR;
2823 savingComment = TRUE;
2824 suppressKibitz = gameMode != IcsObserving ? 2 :
2825 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2829 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2830 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2831 && atoi(star_match[0])) {
2832 // suppress the acknowledgements of our own autoKibitz
2834 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2835 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2836 SendToPlayer(star_match[0], strlen(star_match[0]));
2837 if(looking_at(buf, &i, "*% ")) // eat prompt
2838 suppressKibitz = FALSE;
2842 } // [HGM] kibitz: end of patch
2844 // [HGM] chat: intercept tells by users for which we have an open chat window
2846 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2847 looking_at(buf, &i, "* whispers:") ||
2848 looking_at(buf, &i, "* kibitzes:") ||
2849 looking_at(buf, &i, "* shouts:") ||
2850 looking_at(buf, &i, "* c-shouts:") ||
2851 looking_at(buf, &i, "--> * ") ||
2852 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2853 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2854 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2855 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2857 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2858 chattingPartner = -1;
2860 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2861 for(p=0; p<MAX_CHAT; p++) {
2862 if(channel == atoi(chatPartner[p])) {
2863 talker[0] = '['; strcat(talker, "] ");
2864 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2865 chattingPartner = p; break;
2868 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2869 for(p=0; p<MAX_CHAT; p++) {
2870 if(!strcmp("kibitzes", chatPartner[p])) {
2871 talker[0] = '['; strcat(talker, "] ");
2872 chattingPartner = p; break;
2875 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2876 for(p=0; p<MAX_CHAT; p++) {
2877 if(!strcmp("whispers", chatPartner[p])) {
2878 talker[0] = '['; strcat(talker, "] ");
2879 chattingPartner = p; break;
2882 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2883 if(buf[i-8] == '-' && buf[i-3] == 't')
2884 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2885 if(!strcmp("c-shouts", chatPartner[p])) {
2886 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2887 chattingPartner = p; break;
2890 if(chattingPartner < 0)
2891 for(p=0; p<MAX_CHAT; p++) {
2892 if(!strcmp("shouts", chatPartner[p])) {
2893 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2894 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2895 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2896 chattingPartner = p; break;
2900 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2901 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2902 talker[0] = 0; Colorize(ColorTell, FALSE);
2903 chattingPartner = p; break;
2905 if(chattingPartner<0) i = oldi; else {
2906 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2907 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2908 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2909 started = STARTED_COMMENT;
2910 parse_pos = 0; parse[0] = NULLCHAR;
2911 savingComment = 3 + chattingPartner; // counts as TRUE
2912 suppressKibitz = TRUE;
2915 } // [HGM] chat: end of patch
2917 if (appData.zippyTalk || appData.zippyPlay) {
2918 /* [DM] Backup address for color zippy lines */
2921 if (loggedOn == TRUE)
2922 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2923 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2925 } // [DM] 'else { ' deleted
2927 /* Regular tells and says */
2928 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2929 looking_at(buf, &i, "* (your partner) tells you: ") ||
2930 looking_at(buf, &i, "* says: ") ||
2931 /* Don't color "message" or "messages" output */
2932 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2933 looking_at(buf, &i, "*. * at *:*: ") ||
2934 looking_at(buf, &i, "--* (*:*): ") ||
2935 /* Message notifications (same color as tells) */
2936 looking_at(buf, &i, "* has left a message ") ||
2937 looking_at(buf, &i, "* just sent you a message:\n") ||
2938 /* Whispers and kibitzes */
2939 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2940 looking_at(buf, &i, "* kibitzes: ") ||
2942 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2944 if (tkind == 1 && strchr(star_match[0], ':')) {
2945 /* Avoid "tells you:" spoofs in channels */
2948 if (star_match[0][0] == NULLCHAR ||
2949 strchr(star_match[0], ' ') ||
2950 (tkind == 3 && strchr(star_match[1], ' '))) {
2951 /* Reject bogus matches */
2954 if (appData.colorize) {
2955 if (oldi > next_out) {
2956 SendToPlayer(&buf[next_out], oldi - next_out);
2961 Colorize(ColorTell, FALSE);
2962 curColor = ColorTell;
2965 Colorize(ColorKibitz, FALSE);
2966 curColor = ColorKibitz;
2969 p = strrchr(star_match[1], '(');
2976 Colorize(ColorChannel1, FALSE);
2977 curColor = ColorChannel1;
2979 Colorize(ColorChannel, FALSE);
2980 curColor = ColorChannel;
2984 curColor = ColorNormal;
2988 if (started == STARTED_NONE && appData.autoComment &&
2989 (gameMode == IcsObserving ||
2990 gameMode == IcsPlayingWhite ||
2991 gameMode == IcsPlayingBlack)) {
2992 parse_pos = i - oldi;
2993 memcpy(parse, &buf[oldi], parse_pos);
2994 parse[parse_pos] = NULLCHAR;
2995 started = STARTED_COMMENT;
2996 savingComment = TRUE;
2998 started = STARTED_CHATTER;
2999 savingComment = FALSE;
3006 if (looking_at(buf, &i, "* s-shouts: ") ||
3007 looking_at(buf, &i, "* c-shouts: ")) {
3008 if (appData.colorize) {
3009 if (oldi > next_out) {
3010 SendToPlayer(&buf[next_out], oldi - next_out);
3013 Colorize(ColorSShout, FALSE);
3014 curColor = ColorSShout;
3017 started = STARTED_CHATTER;
3021 if (looking_at(buf, &i, "--->")) {
3026 if (looking_at(buf, &i, "* shouts: ") ||
3027 looking_at(buf, &i, "--> ")) {
3028 if (appData.colorize) {
3029 if (oldi > next_out) {
3030 SendToPlayer(&buf[next_out], oldi - next_out);
3033 Colorize(ColorShout, FALSE);
3034 curColor = ColorShout;
3037 started = STARTED_CHATTER;
3041 if (looking_at( buf, &i, "Challenge:")) {
3042 if (appData.colorize) {
3043 if (oldi > next_out) {
3044 SendToPlayer(&buf[next_out], oldi - next_out);
3047 Colorize(ColorChallenge, FALSE);
3048 curColor = ColorChallenge;
3054 if (looking_at(buf, &i, "* offers you") ||
3055 looking_at(buf, &i, "* offers to be") ||
3056 looking_at(buf, &i, "* would like to") ||
3057 looking_at(buf, &i, "* requests to") ||
3058 looking_at(buf, &i, "Your opponent offers") ||
3059 looking_at(buf, &i, "Your opponent requests")) {
3061 if (appData.colorize) {
3062 if (oldi > next_out) {
3063 SendToPlayer(&buf[next_out], oldi - next_out);
3066 Colorize(ColorRequest, FALSE);
3067 curColor = ColorRequest;
3072 if (looking_at(buf, &i, "* (*) seeking")) {
3073 if (appData.colorize) {
3074 if (oldi > next_out) {
3075 SendToPlayer(&buf[next_out], oldi - next_out);
3078 Colorize(ColorSeek, FALSE);
3079 curColor = ColorSeek;
3084 if (looking_at(buf, &i, "\\ ")) {
3085 if (prevColor != ColorNormal) {
3086 if (oldi > next_out) {
3087 SendToPlayer(&buf[next_out], oldi - next_out);
3090 Colorize(prevColor, TRUE);
3091 curColor = prevColor;
3093 if (savingComment) {
3094 parse_pos = i - oldi;
3095 memcpy(parse, &buf[oldi], parse_pos);
3096 parse[parse_pos] = NULLCHAR;
3097 started = STARTED_COMMENT;
3098 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3099 chattingPartner = savingComment - 3; // kludge to remember the box
3101 started = STARTED_CHATTER;
3106 if (looking_at(buf, &i, "Black Strength :") ||
3107 looking_at(buf, &i, "<<< style 10 board >>>") ||
3108 looking_at(buf, &i, "<10>") ||
3109 looking_at(buf, &i, "#@#")) {
3110 /* Wrong board style */
3112 SendToICS(ics_prefix);
3113 SendToICS("set style 12\n");
3114 SendToICS(ics_prefix);
3115 SendToICS("refresh\n");
3119 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3121 have_sent_ICS_logon = 1;
3122 /* if we don't send the login/password via icsLogon, use special readline
3124 if (strlen(appData.icsLogon)==0)
3126 sending_ICS_password = 0; // in case we come back to login
3127 sending_ICS_login = 1;
3131 /* need to shadow the password */
3132 if (!sending_ICS_password && looking_at(buf, &i, "password:")) {
3133 /* if we don't send the login/password via icsLogon, use special readline
3135 if (strlen(appData.icsLogon)==0)
3136 sending_ICS_password = 1;
3140 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3141 (looking_at(buf, &i, "\n<12> ") ||
3142 looking_at(buf, &i, "<12> "))) {
3144 if (oldi > next_out) {
3145 SendToPlayer(&buf[next_out], oldi - next_out);
3148 started = STARTED_BOARD;
3153 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3154 looking_at(buf, &i, "<b1> ")) {
3155 if (oldi > next_out) {
3156 SendToPlayer(&buf[next_out], oldi - next_out);
3159 started = STARTED_HOLDINGS;
3164 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3166 /* Header for a move list -- first line */
3168 switch (ics_getting_history) {
3172 case BeginningOfGame:
3173 /* User typed "moves" or "oldmoves" while we
3174 were idle. Pretend we asked for these
3175 moves and soak them up so user can step
3176 through them and/or save them.
3179 gameMode = IcsObserving;
3182 ics_getting_history = H_GOT_UNREQ_HEADER;
3184 case EditGame: /*?*/
3185 case EditPosition: /*?*/
3186 /* Should above feature work in these modes too? */
3187 /* For now it doesn't */
3188 ics_getting_history = H_GOT_UNWANTED_HEADER;
3191 ics_getting_history = H_GOT_UNWANTED_HEADER;
3196 /* Is this the right one? */
3197 if (gameInfo.white && gameInfo.black &&
3198 strcmp(gameInfo.white, star_match[0]) == 0 &&
3199 strcmp(gameInfo.black, star_match[2]) == 0) {
3201 ics_getting_history = H_GOT_REQ_HEADER;
3204 case H_GOT_REQ_HEADER:
3205 case H_GOT_UNREQ_HEADER:
3206 case H_GOT_UNWANTED_HEADER:
3207 case H_GETTING_MOVES:
3208 /* Should not happen */
3209 DisplayError(_("Error gathering move list: two headers"), 0);
3210 ics_getting_history = H_FALSE;
3214 /* Save player ratings into gameInfo if needed */
3215 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3216 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3217 (gameInfo.whiteRating == -1 ||
3218 gameInfo.blackRating == -1)) {
3220 gameInfo.whiteRating = string_to_rating(star_match[1]);
3221 gameInfo.blackRating = string_to_rating(star_match[3]);
3222 if (appData.debugMode)
3223 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3224 gameInfo.whiteRating, gameInfo.blackRating);
3229 if (looking_at(buf, &i,
3230 "* * match, initial time: * minute*, increment: * second")) {
3231 /* Header for a move list -- second line */
3232 /* Initial board will follow if this is a wild game */
3233 if (gameInfo.event != NULL) free(gameInfo.event);
3234 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3235 gameInfo.event = StrSave(str);
3236 /* [HGM] we switched variant. Translate boards if needed. */
3237 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3241 if (looking_at(buf, &i, "Move ")) {
3242 /* Beginning of a move list */
3243 switch (ics_getting_history) {
3245 /* Normally should not happen */
3246 /* Maybe user hit reset while we were parsing */
3249 /* Happens if we are ignoring a move list that is not
3250 * the one we just requested. Common if the user
3251 * tries to observe two games without turning off
3254 case H_GETTING_MOVES:
3255 /* Should not happen */
3256 DisplayError(_("Error gathering move list: nested"), 0);
3257 ics_getting_history = H_FALSE;
3259 case H_GOT_REQ_HEADER:
3260 ics_getting_history = H_GETTING_MOVES;
3261 started = STARTED_MOVES;
3263 if (oldi > next_out) {
3264 SendToPlayer(&buf[next_out], oldi - next_out);
3267 case H_GOT_UNREQ_HEADER:
3268 ics_getting_history = H_GETTING_MOVES;
3269 started = STARTED_MOVES_NOHIDE;
3272 case H_GOT_UNWANTED_HEADER:
3273 ics_getting_history = H_FALSE;
3279 if (looking_at(buf, &i, "% ") ||
3280 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3281 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3282 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3283 soughtPending = FALSE;
3287 if(suppressKibitz) next_out = i;
3288 savingComment = FALSE;
3292 case STARTED_MOVES_NOHIDE:
3293 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3294 parse[parse_pos + i - oldi] = NULLCHAR;
3295 ParseGameHistory(parse);
3297 if (appData.zippyPlay && first.initDone) {
3298 FeedMovesToProgram(&first, forwardMostMove);
3299 if (gameMode == IcsPlayingWhite) {
3300 if (WhiteOnMove(forwardMostMove)) {
3301 if (first.sendTime) {
3302 if (first.useColors) {
3303 SendToProgram("black\n", &first);
3305 SendTimeRemaining(&first, TRUE);
3307 if (first.useColors) {
3308 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3310 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3311 first.maybeThinking = TRUE;
3313 if (first.usePlayother) {
3314 if (first.sendTime) {
3315 SendTimeRemaining(&first, TRUE);
3317 SendToProgram("playother\n", &first);
3323 } else if (gameMode == IcsPlayingBlack) {
3324 if (!WhiteOnMove(forwardMostMove)) {
3325 if (first.sendTime) {
3326 if (first.useColors) {
3327 SendToProgram("white\n", &first);
3329 SendTimeRemaining(&first, FALSE);
3331 if (first.useColors) {
3332 SendToProgram("black\n", &first);
3334 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3335 first.maybeThinking = TRUE;
3337 if (first.usePlayother) {
3338 if (first.sendTime) {
3339 SendTimeRemaining(&first, FALSE);
3341 SendToProgram("playother\n", &first);
3350 if (gameMode == IcsObserving && ics_gamenum == -1) {
3351 /* Moves came from oldmoves or moves command
3352 while we weren't doing anything else.
3354 currentMove = forwardMostMove;
3355 ClearHighlights();/*!!could figure this out*/
3356 flipView = appData.flipView;
3357 DrawPosition(TRUE, boards[currentMove]);
3358 DisplayBothClocks();
3359 snprintf(str, MSG_SIZ, "%s vs. %s",
3360 gameInfo.white, gameInfo.black);
3364 /* Moves were history of an active game */
3365 if (gameInfo.resultDetails != NULL) {
3366 free(gameInfo.resultDetails);
3367 gameInfo.resultDetails = NULL;
3370 HistorySet(parseList, backwardMostMove,
3371 forwardMostMove, currentMove-1);
3372 DisplayMove(currentMove - 1);
3373 if (started == STARTED_MOVES) next_out = i;
3374 started = STARTED_NONE;
3375 ics_getting_history = H_FALSE;
3378 case STARTED_OBSERVE:
3379 started = STARTED_NONE;
3380 SendToICS(ics_prefix);
3381 SendToICS("refresh\n");
3387 if(bookHit) { // [HGM] book: simulate book reply
3388 static char bookMove[MSG_SIZ]; // a bit generous?
3390 programStats.nodes = programStats.depth = programStats.time =
3391 programStats.score = programStats.got_only_move = 0;
3392 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3394 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3395 strcat(bookMove, bookHit);
3396 HandleMachineMove(bookMove, &first);
3401 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3402 started == STARTED_HOLDINGS ||
3403 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3404 /* Accumulate characters in move list or board */
3405 parse[parse_pos++] = buf[i];
3408 /* Start of game messages. Mostly we detect start of game
3409 when the first board image arrives. On some versions
3410 of the ICS, though, we need to do a "refresh" after starting
3411 to observe in order to get the current board right away. */
3412 if (looking_at(buf, &i, "Adding game * to observation list")) {
3413 started = STARTED_OBSERVE;
3417 /* Handle auto-observe */
3418 if (appData.autoObserve &&
3419 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3420 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3422 /* Choose the player that was highlighted, if any. */
3423 if (star_match[0][0] == '\033' ||
3424 star_match[1][0] != '\033') {
3425 player = star_match[0];
3427 player = star_match[2];
3429 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3430 ics_prefix, StripHighlightAndTitle(player));
3433 /* Save ratings from notify string */
3434 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3435 player1Rating = string_to_rating(star_match[1]);
3436 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3437 player2Rating = string_to_rating(star_match[3]);
3439 if (appData.debugMode)
3441 "Ratings from 'Game notification:' %s %d, %s %d\n",
3442 player1Name, player1Rating,
3443 player2Name, player2Rating);
3448 /* Deal with automatic examine mode after a game,
3449 and with IcsObserving -> IcsExamining transition */
3450 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3451 looking_at(buf, &i, "has made you an examiner of game *")) {
3453 int gamenum = atoi(star_match[0]);
3454 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3455 gamenum == ics_gamenum) {
3456 /* We were already playing or observing this game;
3457 no need to refetch history */
3458 gameMode = IcsExamining;
3460 pauseExamForwardMostMove = forwardMostMove;
3461 } else if (currentMove < forwardMostMove) {
3462 ForwardInner(forwardMostMove);
3465 /* I don't think this case really can happen */
3466 SendToICS(ics_prefix);
3467 SendToICS("refresh\n");
3472 /* Error messages */
3473 // if (ics_user_moved) {
3474 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3475 if (looking_at(buf, &i, "Illegal move") ||
3476 looking_at(buf, &i, "Not a legal move") ||
3477 looking_at(buf, &i, "Your king is in check") ||
3478 looking_at(buf, &i, "It isn't your turn") ||
3479 looking_at(buf, &i, "It is not your move")) {
3481 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3482 currentMove = forwardMostMove-1;
3483 DisplayMove(currentMove - 1); /* before DMError */
3484 DrawPosition(FALSE, boards[currentMove]);
3485 SwitchClocks(forwardMostMove-1); // [HGM] race
3486 DisplayBothClocks();
3488 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3494 if (looking_at(buf, &i, "still have time") ||
3495 looking_at(buf, &i, "not out of time") ||
3496 looking_at(buf, &i, "either player is out of time") ||
3497 looking_at(buf, &i, "has timeseal; checking")) {
3498 /* We must have called his flag a little too soon */
3499 whiteFlag = blackFlag = FALSE;
3503 if (looking_at(buf, &i, "added * seconds to") ||
3504 looking_at(buf, &i, "seconds were added to")) {
3505 /* Update the clocks */
3506 SendToICS(ics_prefix);
3507 SendToICS("refresh\n");
3511 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3512 ics_clock_paused = TRUE;
3517 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3518 ics_clock_paused = FALSE;
3523 /* Grab player ratings from the Creating: message.
3524 Note we have to check for the special case when
3525 the ICS inserts things like [white] or [black]. */
3526 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3527 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3529 0 player 1 name (not necessarily white)
3531 2 empty, white, or black (IGNORED)
3532 3 player 2 name (not necessarily black)
3535 The names/ratings are sorted out when the game
3536 actually starts (below).
3538 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3539 player1Rating = string_to_rating(star_match[1]);
3540 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3541 player2Rating = string_to_rating(star_match[4]);
3543 if (appData.debugMode)
3545 "Ratings from 'Creating:' %s %d, %s %d\n",
3546 player1Name, player1Rating,
3547 player2Name, player2Rating);
3552 /* Improved generic start/end-of-game messages */
3553 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3554 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3555 /* If tkind == 0: */
3556 /* star_match[0] is the game number */
3557 /* [1] is the white player's name */
3558 /* [2] is the black player's name */
3559 /* For end-of-game: */
3560 /* [3] is the reason for the game end */
3561 /* [4] is a PGN end game-token, preceded by " " */
3562 /* For start-of-game: */
3563 /* [3] begins with "Creating" or "Continuing" */
3564 /* [4] is " *" or empty (don't care). */
3565 int gamenum = atoi(star_match[0]);
3566 char *whitename, *blackname, *why, *endtoken;
3567 ChessMove endtype = EndOfFile;
3570 whitename = star_match[1];
3571 blackname = star_match[2];
3572 why = star_match[3];
3573 endtoken = star_match[4];
3575 whitename = star_match[1];
3576 blackname = star_match[3];
3577 why = star_match[5];
3578 endtoken = star_match[6];
3581 /* Game start messages */
3582 if (strncmp(why, "Creating ", 9) == 0 ||
3583 strncmp(why, "Continuing ", 11) == 0) {
3584 gs_gamenum = gamenum;
3585 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3586 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3588 if (appData.zippyPlay) {
3589 ZippyGameStart(whitename, blackname);
3592 partnerBoardValid = FALSE; // [HGM] bughouse
3596 /* Game end messages */
3597 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3598 ics_gamenum != gamenum) {
3601 while (endtoken[0] == ' ') endtoken++;
3602 switch (endtoken[0]) {
3605 endtype = GameUnfinished;
3608 endtype = BlackWins;
3611 if (endtoken[1] == '/')
3612 endtype = GameIsDrawn;
3614 endtype = WhiteWins;
3617 GameEnds(endtype, why, GE_ICS);
3619 if (appData.zippyPlay && first.initDone) {
3620 ZippyGameEnd(endtype, why);
3621 if (first.pr == NULL) {
3622 /* Start the next process early so that we'll
3623 be ready for the next challenge */
3624 StartChessProgram(&first);
3626 /* Send "new" early, in case this command takes
3627 a long time to finish, so that we'll be ready
3628 for the next challenge. */
3629 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3633 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3637 if (looking_at(buf, &i, "Removing game * from observation") ||
3638 looking_at(buf, &i, "no longer observing game *") ||
3639 looking_at(buf, &i, "Game * (*) has no examiners")) {
3640 if (gameMode == IcsObserving &&
3641 atoi(star_match[0]) == ics_gamenum)
3643 /* icsEngineAnalyze */
3644 if (appData.icsEngineAnalyze) {
3651 ics_user_moved = FALSE;
3656 if (looking_at(buf, &i, "no longer examining game *")) {
3657 if (gameMode == IcsExamining &&
3658 atoi(star_match[0]) == ics_gamenum)
3662 ics_user_moved = FALSE;
3667 /* Advance leftover_start past any newlines we find,
3668 so only partial lines can get reparsed */
3669 if (looking_at(buf, &i, "\n")) {
3670 prevColor = curColor;
3671 if (curColor != ColorNormal) {
3672 if (oldi > next_out) {
3673 SendToPlayer(&buf[next_out], oldi - next_out);
3676 Colorize(ColorNormal, FALSE);
3677 curColor = ColorNormal;
3679 if (started == STARTED_BOARD) {
3680 started = STARTED_NONE;
3681 parse[parse_pos] = NULLCHAR;
3682 ParseBoard12(parse);
3685 /* Send premove here */
3686 if (appData.premove) {
3688 if (currentMove == 0 &&
3689 gameMode == IcsPlayingWhite &&
3690 appData.premoveWhite) {
3691 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3692 if (appData.debugMode)
3693 fprintf(debugFP, "Sending premove:\n");
3695 } else if (currentMove == 1 &&
3696 gameMode == IcsPlayingBlack &&
3697 appData.premoveBlack) {
3698 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3699 if (appData.debugMode)
3700 fprintf(debugFP, "Sending premove:\n");
3702 } else if (gotPremove) {
3704 ClearPremoveHighlights();
3705 if (appData.debugMode)
3706 fprintf(debugFP, "Sending premove:\n");
3707 UserMoveEvent(premoveFromX, premoveFromY,
3708 premoveToX, premoveToY,
3713 /* Usually suppress following prompt */
3714 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3715 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3716 if (looking_at(buf, &i, "*% ")) {
3717 savingComment = FALSE;
3722 } else if (started == STARTED_HOLDINGS) {
3724 char new_piece[MSG_SIZ];
3725 started = STARTED_NONE;
3726 parse[parse_pos] = NULLCHAR;
3727 if (appData.debugMode)
3728 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3729 parse, currentMove);
3730 if (sscanf(parse, " game %d", &gamenum) == 1) {
3731 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3732 if (gameInfo.variant == VariantNormal) {
3733 /* [HGM] We seem to switch variant during a game!
3734 * Presumably no holdings were displayed, so we have
3735 * to move the position two files to the right to
3736 * create room for them!
3738 VariantClass newVariant;
3739 switch(gameInfo.boardWidth) { // base guess on board width
3740 case 9: newVariant = VariantShogi; break;
3741 case 10: newVariant = VariantGreat; break;
3742 default: newVariant = VariantCrazyhouse; break;
3744 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3745 /* Get a move list just to see the header, which
3746 will tell us whether this is really bug or zh */
3747 if (ics_getting_history == H_FALSE) {
3748 ics_getting_history = H_REQUESTED;
3749 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
3753 new_piece[0] = NULLCHAR;
3754 sscanf(parse, "game %d white [%s black [%s <- %s",
3755 &gamenum, white_holding, black_holding,
3757 white_holding[strlen(white_holding)-1] = NULLCHAR;
3758 black_holding[strlen(black_holding)-1] = NULLCHAR;
3759 /* [HGM] copy holdings to board holdings area */
3760 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3761 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3762 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3764 if (appData.zippyPlay && first.initDone) {
3765 ZippyHoldings(white_holding, black_holding,
3769 if (tinyLayout || smallLayout) {
3770 char wh[16], bh[16];
3771 PackHolding(wh, white_holding);
3772 PackHolding(bh, black_holding);
3773 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
3774 gameInfo.white, gameInfo.black);
3776 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
3777 gameInfo.white, white_holding,
3778 gameInfo.black, black_holding);
3780 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3781 DrawPosition(FALSE, boards[currentMove]);
3783 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3784 sscanf(parse, "game %d white [%s black [%s <- %s",
3785 &gamenum, white_holding, black_holding,
3787 white_holding[strlen(white_holding)-1] = NULLCHAR;
3788 black_holding[strlen(black_holding)-1] = NULLCHAR;
3789 /* [HGM] copy holdings to partner-board holdings area */
3790 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3791 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3792 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3793 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3794 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3797 /* Suppress following prompt */
3798 if (looking_at(buf, &i, "*% ")) {
3799 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3800 savingComment = FALSE;
3808 i++; /* skip unparsed character and loop back */
3811 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3812 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3813 // SendToPlayer(&buf[next_out], i - next_out);
3814 started != STARTED_HOLDINGS && leftover_start > next_out) {
3815 SendToPlayer(&buf[next_out], leftover_start - next_out);
3819 leftover_len = buf_len - leftover_start;
3820 /* if buffer ends with something we couldn't parse,
3821 reparse it after appending the next read */
3823 } else if (count == 0) {
3824 RemoveInputSource(isr);
3825 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3827 DisplayFatalError(_("Error reading from ICS"), error, 1);
3832 /* Board style 12 looks like this:
3834 <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
3836 * The "<12> " is stripped before it gets to this routine. The two
3837 * trailing 0's (flip state and clock ticking) are later addition, and
3838 * some chess servers may not have them, or may have only the first.
3839 * Additional trailing fields may be added in the future.
3842 #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"
3844 #define RELATION_OBSERVING_PLAYED 0
3845 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3846 #define RELATION_PLAYING_MYMOVE 1
3847 #define RELATION_PLAYING_NOTMYMOVE -1
3848 #define RELATION_EXAMINING 2
3849 #define RELATION_ISOLATED_BOARD -3
3850 #define RELATION_STARTING_POSITION -4 /* FICS only */
3853 ParseBoard12(string)
3856 GameMode newGameMode;
3857 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3858 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3859 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3860 char to_play, board_chars[200];
3861 char move_str[500], str[500], elapsed_time[500];
3862 char black[32], white[32];
3864 int prevMove = currentMove;
3867 int fromX, fromY, toX, toY;
3869 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3870 char *bookHit = NULL; // [HGM] book
3871 Boolean weird = FALSE, reqFlag = FALSE;
3873 fromX = fromY = toX = toY = -1;
3877 if (appData.debugMode)
3878 fprintf(debugFP, _("Parsing board: %s\n"), string);
3880 move_str[0] = NULLCHAR;
3881 elapsed_time[0] = NULLCHAR;
3882 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3884 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3885 if(string[i] == ' ') { ranks++; files = 0; }
3887 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3890 for(j = 0; j <i; j++) board_chars[j] = string[j];
3891 board_chars[i] = '\0';
3894 n = sscanf(string, PATTERN, &to_play, &double_push,
3895 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3896 &gamenum, white, black, &relation, &basetime, &increment,
3897 &white_stren, &black_stren, &white_time, &black_time,
3898 &moveNum, str, elapsed_time, move_str, &ics_flip,
3902 snprintf(str, sizeof(str), _("Failed to parse board string:\n\"%s\""), string);
3903 DisplayError(str, 0);
3907 /* Convert the move number to internal form */
3908 moveNum = (moveNum - 1) * 2;
3909 if (to_play == 'B') moveNum++;
3910 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3911 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3917 case RELATION_OBSERVING_PLAYED:
3918 case RELATION_OBSERVING_STATIC:
3919 if (gamenum == -1) {
3920 /* Old ICC buglet */
3921 relation = RELATION_OBSERVING_STATIC;
3923 newGameMode = IcsObserving;
3925 case RELATION_PLAYING_MYMOVE:
3926 case RELATION_PLAYING_NOTMYMOVE:
3928 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3929 IcsPlayingWhite : IcsPlayingBlack;
3931 case RELATION_EXAMINING:
3932 newGameMode = IcsExamining;
3934 case RELATION_ISOLATED_BOARD:
3936 /* Just display this board. If user was doing something else,
3937 we will forget about it until the next board comes. */
3938 newGameMode = IcsIdle;
3940 case RELATION_STARTING_POSITION:
3941 newGameMode = gameMode;
3945 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
3946 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
3947 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
3949 for (k = 0; k < ranks; k++) {
3950 for (j = 0; j < files; j++)
3951 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3952 if(gameInfo.holdingsWidth > 1) {
3953 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3954 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3957 CopyBoard(partnerBoard, board);
3958 if(toSqr = strchr(str, '/')) { // extract highlights from long move
3959 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
3960 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
3961 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
3962 if(toSqr = strchr(str, '-')) {
3963 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
3964 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
3965 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
3966 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
3967 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
3968 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3969 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
3970 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
3971 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
3972 DisplayMessage(partnerStatus, "");
3973 partnerBoardValid = TRUE;
3977 /* Modify behavior for initial board display on move listing
3980 switch (ics_getting_history) {
3984 case H_GOT_REQ_HEADER:
3985 case H_GOT_UNREQ_HEADER:
3986 /* This is the initial position of the current game */
3987 gamenum = ics_gamenum;
3988 moveNum = 0; /* old ICS bug workaround */
3989 if (to_play == 'B') {
3990 startedFromSetupPosition = TRUE;
3991 blackPlaysFirst = TRUE;
3993 if (forwardMostMove == 0) forwardMostMove = 1;
3994 if (backwardMostMove == 0) backwardMostMove = 1;
3995 if (currentMove == 0) currentMove = 1;
3997 newGameMode = gameMode;
3998 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4000 case H_GOT_UNWANTED_HEADER:
4001 /* This is an initial board that we don't want */
4003 case H_GETTING_MOVES:
4004 /* Should not happen */
4005 DisplayError(_("Error gathering move list: extra board"), 0);
4006 ics_getting_history = H_FALSE;
4010 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4011 weird && (int)gameInfo.variant < (int)VariantShogi) {
4012 /* [HGM] We seem to have switched variant unexpectedly
4013 * Try to guess new variant from board size
4015 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4016 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4017 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4018 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4019 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4020 if(!weird) newVariant = VariantNormal;
4021 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4022 /* Get a move list just to see the header, which
4023 will tell us whether this is really bug or zh */
4024 if (ics_getting_history == H_FALSE) {
4025 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4026 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4031 /* Take action if this is the first board of a new game, or of a
4032 different game than is currently being displayed. */
4033 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4034 relation == RELATION_ISOLATED_BOARD) {
4036 /* Forget the old game and get the history (if any) of the new one */
4037 if (gameMode != BeginningOfGame) {
4041 if (appData.autoRaiseBoard) BoardToTop();
4043 if (gamenum == -1) {
4044 newGameMode = IcsIdle;
4045 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4046 appData.getMoveList && !reqFlag) {
4047 /* Need to get game history */
4048 ics_getting_history = H_REQUESTED;
4049 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4053 /* Initially flip the board to have black on the bottom if playing
4054 black or if the ICS flip flag is set, but let the user change
4055 it with the Flip View button. */
4056 flipView = appData.autoFlipView ?
4057 (newGameMode == IcsPlayingBlack) || ics_flip :
4060 /* Done with values from previous mode; copy in new ones */
4061 gameMode = newGameMode;
4063 ics_gamenum = gamenum;
4064 if (gamenum == gs_gamenum) {
4065 int klen = strlen(gs_kind);
4066 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4067 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4068 gameInfo.event = StrSave(str);
4070 gameInfo.event = StrSave("ICS game");
4072 gameInfo.site = StrSave(appData.icsHost);
4073 gameInfo.date = PGNDate();
4074 gameInfo.round = StrSave("-");
4075 gameInfo.white = StrSave(white);
4076 gameInfo.black = StrSave(black);
4077 timeControl = basetime * 60 * 1000;
4079 timeIncrement = increment * 1000;
4080 movesPerSession = 0;
4081 gameInfo.timeControl = TimeControlTagValue();
4082 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4083 if (appData.debugMode) {
4084 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4085 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4086 setbuf(debugFP, NULL);
4089 gameInfo.outOfBook = NULL;
4091 /* Do we have the ratings? */
4092 if (strcmp(player1Name, white) == 0 &&
4093 strcmp(player2Name, black) == 0) {
4094 if (appData.debugMode)
4095 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4096 player1Rating, player2Rating);
4097 gameInfo.whiteRating = player1Rating;
4098 gameInfo.blackRating = player2Rating;
4099 } else if (strcmp(player2Name, white) == 0 &&
4100 strcmp(player1Name, black) == 0) {
4101 if (appData.debugMode)
4102 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4103 player2Rating, player1Rating);
4104 gameInfo.whiteRating = player2Rating;
4105 gameInfo.blackRating = player1Rating;
4107 player1Name[0] = player2Name[0] = NULLCHAR;
4109 /* Silence shouts if requested */
4110 if (appData.quietPlay &&
4111 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4112 SendToICS(ics_prefix);
4113 SendToICS("set shout 0\n");
4117 /* Deal with midgame name changes */
4119 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4120 if (gameInfo.white) free(gameInfo.white);
4121 gameInfo.white = StrSave(white);
4123 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4124 if (gameInfo.black) free(gameInfo.black);
4125 gameInfo.black = StrSave(black);
4129 /* Throw away game result if anything actually changes in examine mode */
4130 if (gameMode == IcsExamining && !newGame) {
4131 gameInfo.result = GameUnfinished;
4132 if (gameInfo.resultDetails != NULL) {
4133 free(gameInfo.resultDetails);
4134 gameInfo.resultDetails = NULL;
4138 /* In pausing && IcsExamining mode, we ignore boards coming
4139 in if they are in a different variation than we are. */
4140 if (pauseExamInvalid) return;
4141 if (pausing && gameMode == IcsExamining) {
4142 if (moveNum <= pauseExamForwardMostMove) {
4143 pauseExamInvalid = TRUE;
4144 forwardMostMove = pauseExamForwardMostMove;
4149 if (appData.debugMode) {
4150 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4152 /* Parse the board */
4153 for (k = 0; k < ranks; k++) {
4154 for (j = 0; j < files; j++)
4155 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4156 if(gameInfo.holdingsWidth > 1) {
4157 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4158 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4161 CopyBoard(boards[moveNum], board);
4162 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4164 startedFromSetupPosition =
4165 !CompareBoards(board, initialPosition);
4166 if(startedFromSetupPosition)
4167 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4170 /* [HGM] Set castling rights. Take the outermost Rooks,
4171 to make it also work for FRC opening positions. Note that board12
4172 is really defective for later FRC positions, as it has no way to
4173 indicate which Rook can castle if they are on the same side of King.
4174 For the initial position we grant rights to the outermost Rooks,
4175 and remember thos rights, and we then copy them on positions
4176 later in an FRC game. This means WB might not recognize castlings with
4177 Rooks that have moved back to their original position as illegal,
4178 but in ICS mode that is not its job anyway.
4180 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4181 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4183 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4184 if(board[0][i] == WhiteRook) j = i;
4185 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4186 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4187 if(board[0][i] == WhiteRook) j = i;
4188 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4189 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4190 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4191 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4192 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4193 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4194 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4196 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4197 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4198 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4199 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4200 if(board[BOARD_HEIGHT-1][k] == bKing)
4201 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4202 if(gameInfo.variant == VariantTwoKings) {
4203 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4204 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4205 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4208 r = boards[moveNum][CASTLING][0] = initialRights[0];
4209 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4210 r = boards[moveNum][CASTLING][1] = initialRights[1];
4211 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4212 r = boards[moveNum][CASTLING][3] = initialRights[3];
4213 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4214 r = boards[moveNum][CASTLING][4] = initialRights[4];
4215 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4216 /* wildcastle kludge: always assume King has rights */
4217 r = boards[moveNum][CASTLING][2] = initialRights[2];
4218 r = boards[moveNum][CASTLING][5] = initialRights[5];
4220 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4221 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4224 if (ics_getting_history == H_GOT_REQ_HEADER ||
4225 ics_getting_history == H_GOT_UNREQ_HEADER) {
4226 /* This was an initial position from a move list, not
4227 the current position */
4231 /* Update currentMove and known move number limits */
4232 newMove = newGame || moveNum > forwardMostMove;
4235 forwardMostMove = backwardMostMove = currentMove = moveNum;
4236 if (gameMode == IcsExamining && moveNum == 0) {
4237 /* Workaround for ICS limitation: we are not told the wild
4238 type when starting to examine a game. But if we ask for
4239 the move list, the move list header will tell us */
4240 ics_getting_history = H_REQUESTED;
4241 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4244 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4245 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4247 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4248 /* [HGM] applied this also to an engine that is silently watching */
4249 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4250 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4251 gameInfo.variant == currentlyInitializedVariant) {
4252 takeback = forwardMostMove - moveNum;
4253 for (i = 0; i < takeback; i++) {
4254 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4255 SendToProgram("undo\n", &first);
4260 forwardMostMove = moveNum;
4261 if (!pausing || currentMove > forwardMostMove)
4262 currentMove = forwardMostMove;
4264 /* New part of history that is not contiguous with old part */
4265 if (pausing && gameMode == IcsExamining) {
4266 pauseExamInvalid = TRUE;
4267 forwardMostMove = pauseExamForwardMostMove;
4270 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4272 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4273 // [HGM] when we will receive the move list we now request, it will be
4274 // fed to the engine from the first move on. So if the engine is not
4275 // in the initial position now, bring it there.
4276 InitChessProgram(&first, 0);
4279 ics_getting_history = H_REQUESTED;
4280 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4283 forwardMostMove = backwardMostMove = currentMove = moveNum;
4286 /* Update the clocks */
4287 if (strchr(elapsed_time, '.')) {
4289 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4290 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4292 /* Time is in seconds */
4293 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4294 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4299 if (appData.zippyPlay && newGame &&
4300 gameMode != IcsObserving && gameMode != IcsIdle &&
4301 gameMode != IcsExamining)
4302 ZippyFirstBoard(moveNum, basetime, increment);
4305 /* Put the move on the move list, first converting
4306 to canonical algebraic form. */
4308 if (appData.debugMode) {
4309 if (appData.debugMode) { int f = forwardMostMove;
4310 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4311 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4312 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4314 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4315 fprintf(debugFP, "moveNum = %d\n", moveNum);
4316 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4317 setbuf(debugFP, NULL);
4319 if (moveNum <= backwardMostMove) {
4320 /* We don't know what the board looked like before
4322 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4323 strcat(parseList[moveNum - 1], " ");
4324 strcat(parseList[moveNum - 1], elapsed_time);
4325 moveList[moveNum - 1][0] = NULLCHAR;
4326 } else if (strcmp(move_str, "none") == 0) {
4327 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4328 /* Again, we don't know what the board looked like;
4329 this is really the start of the game. */
4330 parseList[moveNum - 1][0] = NULLCHAR;
4331 moveList[moveNum - 1][0] = NULLCHAR;
4332 backwardMostMove = moveNum;
4333 startedFromSetupPosition = TRUE;
4334 fromX = fromY = toX = toY = -1;
4336 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4337 // So we parse the long-algebraic move string in stead of the SAN move
4338 int valid; char buf[MSG_SIZ], *prom;
4340 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4341 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4342 // str looks something like "Q/a1-a2"; kill the slash
4344 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4345 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4346 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4347 strcat(buf, prom); // long move lacks promo specification!
4348 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4349 if(appData.debugMode)
4350 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4351 safeStrCpy(move_str, buf, sizeof(move_str)/sizeof(move_str[0]));
4353 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4354 &fromX, &fromY, &toX, &toY, &promoChar)
4355 || ParseOneMove(buf, moveNum - 1, &moveType,
4356 &fromX, &fromY, &toX, &toY, &promoChar);
4357 // end of long SAN patch
4359 (void) CoordsToAlgebraic(boards[moveNum - 1],
4360 PosFlags(moveNum - 1),
4361 fromY, fromX, toY, toX, promoChar,
4362 parseList[moveNum-1]);
4363 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4369 if(gameInfo.variant != VariantShogi)
4370 strcat(parseList[moveNum - 1], "+");
4373 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4374 strcat(parseList[moveNum - 1], "#");
4377 strcat(parseList[moveNum - 1], " ");
4378 strcat(parseList[moveNum - 1], elapsed_time);
4379 /* currentMoveString is set as a side-effect of ParseOneMove */
4380 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4381 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4382 strcat(moveList[moveNum - 1], "\n");
4384 if(gameInfo.holdingsWidth && !appData.disguise) // inherit info that ICS does not give from previous board
4385 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4386 ChessSquare old, new = boards[moveNum][k][j];
4387 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4388 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4389 if(old == new) continue;
4390 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4391 else if(new == WhiteWazir || new == BlackWazir) {
4392 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4393 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4394 else boards[moveNum][k][j] = old; // preserve type of Gold
4395 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4396 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4399 /* Move from ICS was illegal!? Punt. */
4400 if (appData.debugMode) {
4401 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4402 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4404 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4405 strcat(parseList[moveNum - 1], " ");
4406 strcat(parseList[moveNum - 1], elapsed_time);
4407 moveList[moveNum - 1][0] = NULLCHAR;
4408 fromX = fromY = toX = toY = -1;
4411 if (appData.debugMode) {
4412 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4413 setbuf(debugFP, NULL);
4417 /* Send move to chess program (BEFORE animating it). */
4418 if (appData.zippyPlay && !newGame && newMove &&
4419 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4421 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4422 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4423 if (moveList[moveNum - 1][0] == NULLCHAR) {
4424 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4426 DisplayError(str, 0);
4428 if (first.sendTime) {
4429 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4431 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4432 if (firstMove && !bookHit) {
4434 if (first.useColors) {
4435 SendToProgram(gameMode == IcsPlayingWhite ?
4437 "black\ngo\n", &first);
4439 SendToProgram("go\n", &first);
4441 first.maybeThinking = TRUE;
4444 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4445 if (moveList[moveNum - 1][0] == NULLCHAR) {
4446 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4447 DisplayError(str, 0);
4449 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4450 SendMoveToProgram(moveNum - 1, &first);
4457 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4458 /* If move comes from a remote source, animate it. If it
4459 isn't remote, it will have already been animated. */
4460 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4461 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4463 if (!pausing && appData.highlightLastMove) {
4464 SetHighlights(fromX, fromY, toX, toY);
4468 /* Start the clocks */
4469 whiteFlag = blackFlag = FALSE;
4470 appData.clockMode = !(basetime == 0 && increment == 0);
4472 ics_clock_paused = TRUE;
4474 } else if (ticking == 1) {
4475 ics_clock_paused = FALSE;
4477 if (gameMode == IcsIdle ||
4478 relation == RELATION_OBSERVING_STATIC ||
4479 relation == RELATION_EXAMINING ||
4481 DisplayBothClocks();
4485 /* Display opponents and material strengths */
4486 if (gameInfo.variant != VariantBughouse &&
4487 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4488 if (tinyLayout || smallLayout) {
4489 if(gameInfo.variant == VariantNormal)
4490 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4491 gameInfo.white, white_stren, gameInfo.black, black_stren,
4492 basetime, increment);
4494 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4495 gameInfo.white, white_stren, gameInfo.black, black_stren,
4496 basetime, increment, (int) gameInfo.variant);
4498 if(gameInfo.variant == VariantNormal)
4499 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4500 gameInfo.white, white_stren, gameInfo.black, black_stren,
4501 basetime, increment);
4503 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4504 gameInfo.white, white_stren, gameInfo.black, black_stren,
4505 basetime, increment, VariantName(gameInfo.variant));
4508 if (appData.debugMode) {
4509 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4514 /* Display the board */
4515 if (!pausing && !appData.noGUI) {
4517 if (appData.premove)
4519 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4520 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4521 ClearPremoveHighlights();
4523 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4524 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4525 DrawPosition(j, boards[currentMove]);
4527 DisplayMove(moveNum - 1);
4528 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4529 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4530 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4531 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4535 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4537 if(bookHit) { // [HGM] book: simulate book reply
4538 static char bookMove[MSG_SIZ]; // a bit generous?
4540 programStats.nodes = programStats.depth = programStats.time =
4541 programStats.score = programStats.got_only_move = 0;
4542 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4544 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4545 strcat(bookMove, bookHit);
4546 HandleMachineMove(bookMove, &first);
4555 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4556 ics_getting_history = H_REQUESTED;
4557 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4563 AnalysisPeriodicEvent(force)
4566 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4567 && !force) || !appData.periodicUpdates)
4570 /* Send . command to Crafty to collect stats */
4571 SendToProgram(".\n", &first);
4573 /* Don't send another until we get a response (this makes
4574 us stop sending to old Crafty's which don't understand
4575 the "." command (sending illegal cmds resets node count & time,
4576 which looks bad)) */
4577 programStats.ok_to_send = 0;
4580 void ics_update_width(new_width)
4583 ics_printf("set width %d\n", new_width);
4587 SendMoveToProgram(moveNum, cps)
4589 ChessProgramState *cps;
4593 if (cps->useUsermove) {
4594 SendToProgram("usermove ", cps);
4598 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4599 int len = space - parseList[moveNum];
4600 memcpy(buf, parseList[moveNum], len);
4602 buf[len] = NULLCHAR;
4604 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4606 SendToProgram(buf, cps);
4608 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4609 AlphaRank(moveList[moveNum], 4);
4610 SendToProgram(moveList[moveNum], cps);
4611 AlphaRank(moveList[moveNum], 4); // and back
4613 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4614 * the engine. It would be nice to have a better way to identify castle
4616 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4617 && cps->useOOCastle) {
4618 int fromX = moveList[moveNum][0] - AAA;
4619 int fromY = moveList[moveNum][1] - ONE;
4620 int toX = moveList[moveNum][2] - AAA;
4621 int toY = moveList[moveNum][3] - ONE;
4622 if((boards[moveNum][fromY][fromX] == WhiteKing
4623 && boards[moveNum][toY][toX] == WhiteRook)
4624 || (boards[moveNum][fromY][fromX] == BlackKing
4625 && boards[moveNum][toY][toX] == BlackRook)) {
4626 if(toX > fromX) SendToProgram("O-O\n", cps);
4627 else SendToProgram("O-O-O\n", cps);
4629 else SendToProgram(moveList[moveNum], cps);
4631 else SendToProgram(moveList[moveNum], cps);
4632 /* End of additions by Tord */
4635 /* [HGM] setting up the opening has brought engine in force mode! */
4636 /* Send 'go' if we are in a mode where machine should play. */
4637 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4638 (gameMode == TwoMachinesPlay ||
4640 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4642 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4643 SendToProgram("go\n", cps);
4644 if (appData.debugMode) {
4645 fprintf(debugFP, "(extra)\n");
4648 setboardSpoiledMachineBlack = 0;
4652 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4654 int fromX, fromY, toX, toY;
4657 char user_move[MSG_SIZ];
4661 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4662 (int)moveType, fromX, fromY, toX, toY);
4663 DisplayError(user_move + strlen("say "), 0);
4665 case WhiteKingSideCastle:
4666 case BlackKingSideCastle:
4667 case WhiteQueenSideCastleWild:
4668 case BlackQueenSideCastleWild:
4670 case WhiteHSideCastleFR:
4671 case BlackHSideCastleFR:
4673 snprintf(user_move, MSG_SIZ, "o-o\n");
4675 case WhiteQueenSideCastle:
4676 case BlackQueenSideCastle:
4677 case WhiteKingSideCastleWild:
4678 case BlackKingSideCastleWild:
4680 case WhiteASideCastleFR:
4681 case BlackASideCastleFR:
4683 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4685 case WhiteNonPromotion:
4686 case BlackNonPromotion:
4687 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4689 case WhitePromotion:
4690 case BlackPromotion:
4691 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4692 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4693 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4694 PieceToChar(WhiteFerz));
4695 else if(gameInfo.variant == VariantGreat)
4696 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4697 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4698 PieceToChar(WhiteMan));
4700 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4701 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4707 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4708 ToUpper(PieceToChar((ChessSquare) fromX)),
4709 AAA + toX, ONE + toY);
4711 case IllegalMove: /* could be a variant we don't quite understand */
4712 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
4714 case WhiteCapturesEnPassant:
4715 case BlackCapturesEnPassant:
4716 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
4717 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4720 SendToICS(user_move);
4721 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4722 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4727 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4728 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4729 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4730 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4731 DisplayError("You cannot do this while you are playing or observing", 0);
4734 if(gameMode != IcsExamining) { // is this ever not the case?
4735 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4737 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4738 snprintf(command,MSG_SIZ, "match %s", ics_handle);
4739 } else { // on FICS we must first go to general examine mode
4740 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
4742 if(gameInfo.variant != VariantNormal) {
4743 // try figure out wild number, as xboard names are not always valid on ICS
4744 for(i=1; i<=36; i++) {
4745 snprintf(buf, MSG_SIZ, "wild/%d", i);
4746 if(StringToVariant(buf) == gameInfo.variant) break;
4748 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
4749 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
4750 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
4751 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4752 SendToICS(ics_prefix);
4754 if(startedFromSetupPosition || backwardMostMove != 0) {
4755 fen = PositionToFEN(backwardMostMove, NULL);
4756 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4757 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
4759 } else { // FICS: everything has to set by separate bsetup commands
4760 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4761 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
4763 if(!WhiteOnMove(backwardMostMove)) {
4764 SendToICS("bsetup tomove black\n");
4766 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4767 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
4769 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4770 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
4772 i = boards[backwardMostMove][EP_STATUS];
4773 if(i >= 0) { // set e.p.
4774 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
4780 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4781 SendToICS("bsetup done\n"); // switch to normal examining.
4783 for(i = backwardMostMove; i<last; i++) {
4785 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
4788 SendToICS(ics_prefix);
4789 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4793 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4798 if (rf == DROP_RANK) {
4799 sprintf(move, "%c@%c%c\n",
4800 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4802 if (promoChar == 'x' || promoChar == NULLCHAR) {
4803 sprintf(move, "%c%c%c%c\n",
4804 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4806 sprintf(move, "%c%c%c%c%c\n",
4807 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4813 ProcessICSInitScript(f)
4818 while (fgets(buf, MSG_SIZ, f)) {
4819 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4826 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4828 AlphaRank(char *move, int n)
4830 // char *p = move, c; int x, y;
4832 if (appData.debugMode) {
4833 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4837 move[2]>='0' && move[2]<='9' &&
4838 move[3]>='a' && move[3]<='x' ) {
4840 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4841 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4843 if(move[0]>='0' && move[0]<='9' &&
4844 move[1]>='a' && move[1]<='x' &&
4845 move[2]>='0' && move[2]<='9' &&
4846 move[3]>='a' && move[3]<='x' ) {
4847 /* input move, Shogi -> normal */
4848 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4849 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4850 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4851 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4854 move[3]>='0' && move[3]<='9' &&
4855 move[2]>='a' && move[2]<='x' ) {
4857 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4858 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4861 move[0]>='a' && move[0]<='x' &&
4862 move[3]>='0' && move[3]<='9' &&
4863 move[2]>='a' && move[2]<='x' ) {
4864 /* output move, normal -> Shogi */
4865 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4866 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4867 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4868 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4869 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4871 if (appData.debugMode) {
4872 fprintf(debugFP, " out = '%s'\n", move);
4876 char yy_textstr[8000];
4878 /* Parser for moves from gnuchess, ICS, or user typein box */
4880 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4883 ChessMove *moveType;
4884 int *fromX, *fromY, *toX, *toY;
4887 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
4889 switch (*moveType) {
4890 case WhitePromotion:
4891 case BlackPromotion:
4892 case WhiteNonPromotion:
4893 case BlackNonPromotion:
4895 case WhiteCapturesEnPassant:
4896 case BlackCapturesEnPassant:
4897 case WhiteKingSideCastle:
4898 case WhiteQueenSideCastle:
4899 case BlackKingSideCastle:
4900 case BlackQueenSideCastle:
4901 case WhiteKingSideCastleWild:
4902 case WhiteQueenSideCastleWild:
4903 case BlackKingSideCastleWild:
4904 case BlackQueenSideCastleWild:
4905 /* Code added by Tord: */
4906 case WhiteHSideCastleFR:
4907 case WhiteASideCastleFR:
4908 case BlackHSideCastleFR:
4909 case BlackASideCastleFR:
4910 /* End of code added by Tord */
4911 case IllegalMove: /* bug or odd chess variant */
4912 *fromX = currentMoveString[0] - AAA;
4913 *fromY = currentMoveString[1] - ONE;
4914 *toX = currentMoveString[2] - AAA;
4915 *toY = currentMoveString[3] - ONE;
4916 *promoChar = currentMoveString[4];
4917 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
4918 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
4919 if (appData.debugMode) {
4920 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
4922 *fromX = *fromY = *toX = *toY = 0;
4925 if (appData.testLegality) {
4926 return (*moveType != IllegalMove);
4928 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
4929 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
4934 *fromX = *moveType == WhiteDrop ?
4935 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4936 (int) CharToPiece(ToLower(currentMoveString[0]));
4938 *toX = currentMoveString[2] - AAA;
4939 *toY = currentMoveString[3] - ONE;
4940 *promoChar = NULLCHAR;
4944 case ImpossibleMove:
4954 if (appData.debugMode) {
4955 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
4958 *fromX = *fromY = *toX = *toY = 0;
4959 *promoChar = NULLCHAR;
4966 ParsePV(char *pv, Boolean storeComments)
4967 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
4968 int fromX, fromY, toX, toY; char promoChar;
4973 endPV = forwardMostMove;
4975 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
4976 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
4977 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
4978 if(appData.debugMode){
4979 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);
4981 if(!valid && nr == 0 &&
4982 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
4983 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
4984 // Hande case where played move is different from leading PV move
4985 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
4986 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
4987 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
4988 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
4989 endPV += 2; // if position different, keep this
4990 moveList[endPV-1][0] = fromX + AAA;
4991 moveList[endPV-1][1] = fromY + ONE;
4992 moveList[endPV-1][2] = toX + AAA;
4993 moveList[endPV-1][3] = toY + ONE;
4994 parseList[endPV-1][0] = NULLCHAR;
4995 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
4998 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
4999 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5000 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5001 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5002 valid++; // allow comments in PV
5006 if(endPV+1 > framePtr) break; // no space, truncate
5009 CopyBoard(boards[endPV], boards[endPV-1]);
5010 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5011 moveList[endPV-1][0] = fromX + AAA;
5012 moveList[endPV-1][1] = fromY + ONE;
5013 moveList[endPV-1][2] = toX + AAA;
5014 moveList[endPV-1][3] = toY + ONE;
5016 CoordsToAlgebraic(boards[endPV - 1],
5017 PosFlags(endPV - 1),
5018 fromY, fromX, toY, toX, promoChar,
5019 parseList[endPV - 1]);
5021 parseList[endPV-1][0] = NULLCHAR;
5023 currentMove = endPV;
5024 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5025 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5026 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5027 DrawPosition(TRUE, boards[currentMove]);
5030 static int lastX, lastY;
5033 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5038 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5039 lastX = x; lastY = y;
5040 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5042 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5043 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5045 do{ while(buf[index] && buf[index] != '\n') index++;
5046 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5048 ParsePV(buf+startPV, FALSE);
5049 *start = startPV; *end = index-1;
5054 LoadPV(int x, int y)
5055 { // called on right mouse click to load PV
5056 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5057 lastX = x; lastY = y;
5058 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
5065 if(endPV < 0) return;
5067 currentMove = forwardMostMove;
5068 ClearPremoveHighlights();
5069 DrawPosition(TRUE, boards[currentMove]);
5073 MovePV(int x, int y, int h)
5074 { // step through PV based on mouse coordinates (called on mouse move)
5075 int margin = h>>3, step = 0;
5077 if(endPV < 0) return;
5078 // we must somehow check if right button is still down (might be released off board!)
5079 if(y < margin && (abs(x - lastX) > 6 || abs(y - lastY) > 6)) step = 1; else
5080 if(y > h - margin && (abs(x - lastX) > 6 || abs(y - lastY) > 6)) step = -1; else
5081 if( y > lastY + 6 ) step = -1; else if(y < lastY - 6) step = 1;
5083 lastX = x; lastY = y;
5084 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5085 currentMove += step;
5086 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5087 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5088 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5089 DrawPosition(FALSE, boards[currentMove]);
5093 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5094 // All positions will have equal probability, but the current method will not provide a unique
5095 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5101 int piecesLeft[(int)BlackPawn];
5102 int seed, nrOfShuffles;
5104 void GetPositionNumber()
5105 { // sets global variable seed
5108 seed = appData.defaultFrcPosition;
5109 if(seed < 0) { // randomize based on time for negative FRC position numbers
5110 for(i=0; i<50; i++) seed += random();
5111 seed = random() ^ random() >> 8 ^ random() << 8;
5112 if(seed<0) seed = -seed;
5116 int put(Board board, int pieceType, int rank, int n, int shade)
5117 // put the piece on the (n-1)-th empty squares of the given shade
5121 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5122 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5123 board[rank][i] = (ChessSquare) pieceType;
5124 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5126 piecesLeft[pieceType]--;
5134 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5135 // calculate where the next piece goes, (any empty square), and put it there
5139 i = seed % squaresLeft[shade];
5140 nrOfShuffles *= squaresLeft[shade];
5141 seed /= squaresLeft[shade];
5142 put(board, pieceType, rank, i, shade);
5145 void AddTwoPieces(Board board, int pieceType, int rank)
5146 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5148 int i, n=squaresLeft[ANY], j=n-1, k;
5150 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5151 i = seed % k; // pick one
5154 while(i >= j) i -= j--;
5155 j = n - 1 - j; i += j;
5156 put(board, pieceType, rank, j, ANY);
5157 put(board, pieceType, rank, i, ANY);
5160 void SetUpShuffle(Board board, int number)
5164 GetPositionNumber(); nrOfShuffles = 1;
5166 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5167 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5168 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5170 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5172 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5173 p = (int) board[0][i];
5174 if(p < (int) BlackPawn) piecesLeft[p] ++;
5175 board[0][i] = EmptySquare;
5178 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5179 // shuffles restricted to allow normal castling put KRR first
5180 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5181 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5182 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5183 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5184 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5185 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5186 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5187 put(board, WhiteRook, 0, 0, ANY);
5188 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5191 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5192 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5193 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5194 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5195 while(piecesLeft[p] >= 2) {
5196 AddOnePiece(board, p, 0, LITE);
5197 AddOnePiece(board, p, 0, DARK);
5199 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5202 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5203 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5204 // but we leave King and Rooks for last, to possibly obey FRC restriction
5205 if(p == (int)WhiteRook) continue;
5206 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5207 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5210 // now everything is placed, except perhaps King (Unicorn) and Rooks
5212 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5213 // Last King gets castling rights
5214 while(piecesLeft[(int)WhiteUnicorn]) {
5215 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5216 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5219 while(piecesLeft[(int)WhiteKing]) {
5220 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5221 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5226 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5227 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5230 // Only Rooks can be left; simply place them all
5231 while(piecesLeft[(int)WhiteRook]) {
5232 i = put(board, WhiteRook, 0, 0, ANY);
5233 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5236 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5238 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5241 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5242 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5245 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5248 int SetCharTable( char *table, const char * map )
5249 /* [HGM] moved here from winboard.c because of its general usefulness */
5250 /* Basically a safe strcpy that uses the last character as King */
5252 int result = FALSE; int NrPieces;
5254 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5255 && NrPieces >= 12 && !(NrPieces&1)) {
5256 int i; /* [HGM] Accept even length from 12 to 34 */
5258 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5259 for( i=0; i<NrPieces/2-1; i++ ) {
5261 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5263 table[(int) WhiteKing] = map[NrPieces/2-1];
5264 table[(int) BlackKing] = map[NrPieces-1];
5272 void Prelude(Board board)
5273 { // [HGM] superchess: random selection of exo-pieces
5274 int i, j, k; ChessSquare p;
5275 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5277 GetPositionNumber(); // use FRC position number
5279 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5280 SetCharTable(pieceToChar, appData.pieceToCharTable);
5281 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5282 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5285 j = seed%4; seed /= 4;
5286 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5287 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5288 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5289 j = seed%3 + (seed%3 >= j); seed /= 3;
5290 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5291 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5292 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5293 j = seed%3; seed /= 3;
5294 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5295 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5296 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5297 j = seed%2 + (seed%2 >= j); seed /= 2;
5298 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5299 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5300 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5301 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5302 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5303 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5304 put(board, exoPieces[0], 0, 0, ANY);
5305 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5309 InitPosition(redraw)
5312 ChessSquare (* pieces)[BOARD_FILES];
5313 int i, j, pawnRow, overrule,
5314 oldx = gameInfo.boardWidth,
5315 oldy = gameInfo.boardHeight,
5316 oldh = gameInfo.holdingsWidth,
5317 oldv = gameInfo.variant;
5319 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5321 /* [AS] Initialize pv info list [HGM] and game status */
5323 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5324 pvInfoList[i].depth = 0;
5325 boards[i][EP_STATUS] = EP_NONE;
5326 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5329 initialRulePlies = 0; /* 50-move counter start */
5331 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5332 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5336 /* [HGM] logic here is completely changed. In stead of full positions */
5337 /* the initialized data only consist of the two backranks. The switch */
5338 /* selects which one we will use, which is than copied to the Board */
5339 /* initialPosition, which for the rest is initialized by Pawns and */
5340 /* empty squares. This initial position is then copied to boards[0], */
5341 /* possibly after shuffling, so that it remains available. */
5343 gameInfo.holdingsWidth = 0; /* default board sizes */
5344 gameInfo.boardWidth = 8;
5345 gameInfo.boardHeight = 8;
5346 gameInfo.holdingsSize = 0;
5347 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5348 for(i=0; i<BOARD_FILES-2; i++)
5349 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5350 initialPosition[EP_STATUS] = EP_NONE;
5351 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5352 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5353 SetCharTable(pieceNickName, appData.pieceNickNames);
5354 else SetCharTable(pieceNickName, "............");
5356 switch (gameInfo.variant) {
5357 case VariantFischeRandom:
5358 shuffleOpenings = TRUE;
5362 case VariantShatranj:
5363 pieces = ShatranjArray;
5364 nrCastlingRights = 0;
5365 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5368 pieces = makrukArray;
5369 nrCastlingRights = 0;
5370 startedFromSetupPosition = TRUE;
5371 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5373 case VariantTwoKings:
5374 pieces = twoKingsArray;
5376 case VariantCapaRandom:
5377 shuffleOpenings = TRUE;
5378 case VariantCapablanca:
5379 pieces = CapablancaArray;
5380 gameInfo.boardWidth = 10;
5381 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5384 pieces = GothicArray;
5385 gameInfo.boardWidth = 10;
5386 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5389 pieces = JanusArray;
5390 gameInfo.boardWidth = 10;
5391 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5392 nrCastlingRights = 6;
5393 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5394 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5395 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5396 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5397 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5398 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5401 pieces = FalconArray;
5402 gameInfo.boardWidth = 10;
5403 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5405 case VariantXiangqi:
5406 pieces = XiangqiArray;
5407 gameInfo.boardWidth = 9;
5408 gameInfo.boardHeight = 10;
5409 nrCastlingRights = 0;
5410 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5413 pieces = ShogiArray;
5414 gameInfo.boardWidth = 9;
5415 gameInfo.boardHeight = 9;
5416 gameInfo.holdingsSize = 7;
5417 nrCastlingRights = 0;
5418 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5420 case VariantCourier:
5421 pieces = CourierArray;
5422 gameInfo.boardWidth = 12;
5423 nrCastlingRights = 0;
5424 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5426 case VariantKnightmate:
5427 pieces = KnightmateArray;
5428 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5431 pieces = fairyArray;
5432 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5435 pieces = GreatArray;
5436 gameInfo.boardWidth = 10;
5437 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5438 gameInfo.holdingsSize = 8;
5442 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5443 gameInfo.holdingsSize = 8;
5444 startedFromSetupPosition = TRUE;
5446 case VariantCrazyhouse:
5447 case VariantBughouse:
5449 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5450 gameInfo.holdingsSize = 5;
5452 case VariantWildCastle:
5454 /* !!?shuffle with kings guaranteed to be on d or e file */
5455 shuffleOpenings = 1;
5457 case VariantNoCastle:
5459 nrCastlingRights = 0;
5460 /* !!?unconstrained back-rank shuffle */
5461 shuffleOpenings = 1;
5466 if(appData.NrFiles >= 0) {
5467 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5468 gameInfo.boardWidth = appData.NrFiles;
5470 if(appData.NrRanks >= 0) {
5471 gameInfo.boardHeight = appData.NrRanks;
5473 if(appData.holdingsSize >= 0) {
5474 i = appData.holdingsSize;
5475 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5476 gameInfo.holdingsSize = i;
5478 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5479 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5480 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5482 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5483 if(pawnRow < 1) pawnRow = 1;
5484 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5486 /* User pieceToChar list overrules defaults */
5487 if(appData.pieceToCharTable != NULL)
5488 SetCharTable(pieceToChar, appData.pieceToCharTable);
5490 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5492 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5493 s = (ChessSquare) 0; /* account holding counts in guard band */
5494 for( i=0; i<BOARD_HEIGHT; i++ )
5495 initialPosition[i][j] = s;
5497 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5498 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5499 initialPosition[pawnRow][j] = WhitePawn;
5500 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = BlackPawn;
5501 if(gameInfo.variant == VariantXiangqi) {
5503 initialPosition[pawnRow][j] =
5504 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5505 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5506 initialPosition[2][j] = WhiteCannon;
5507 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5511 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5513 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5516 initialPosition[1][j] = WhiteBishop;
5517 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5519 initialPosition[1][j] = WhiteRook;
5520 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5523 if( nrCastlingRights == -1) {
5524 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5525 /* This sets default castling rights from none to normal corners */
5526 /* Variants with other castling rights must set them themselves above */
5527 nrCastlingRights = 6;
5529 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5530 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5531 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5532 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5533 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5534 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5537 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5538 if(gameInfo.variant == VariantGreat) { // promotion commoners
5539 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5540 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5541 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5542 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5544 if (appData.debugMode) {
5545 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5547 if(shuffleOpenings) {
5548 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5549 startedFromSetupPosition = TRUE;
5551 if(startedFromPositionFile) {
5552 /* [HGM] loadPos: use PositionFile for every new game */
5553 CopyBoard(initialPosition, filePosition);
5554 for(i=0; i<nrCastlingRights; i++)
5555 initialRights[i] = filePosition[CASTLING][i];
5556 startedFromSetupPosition = TRUE;
5559 CopyBoard(boards[0], initialPosition);
5561 if(oldx != gameInfo.boardWidth ||
5562 oldy != gameInfo.boardHeight ||
5563 oldh != gameInfo.holdingsWidth
5565 || oldv == VariantGothic || // For licensing popups
5566 gameInfo.variant == VariantGothic
5569 || oldv == VariantFalcon ||
5570 gameInfo.variant == VariantFalcon
5573 InitDrawingSizes(-2 ,0);
5576 DrawPosition(TRUE, boards[currentMove]);
5580 SendBoard(cps, moveNum)
5581 ChessProgramState *cps;
5584 char message[MSG_SIZ];
5586 if (cps->useSetboard) {
5587 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5588 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
5589 SendToProgram(message, cps);
5595 /* Kludge to set black to move, avoiding the troublesome and now
5596 * deprecated "black" command.
5598 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
5599 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
5601 SendToProgram("edit\n", cps);
5602 SendToProgram("#\n", cps);
5603 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5604 bp = &boards[moveNum][i][BOARD_LEFT];
5605 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5606 if ((int) *bp < (int) BlackPawn) {
5607 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
5609 if(message[0] == '+' || message[0] == '~') {
5610 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5611 PieceToChar((ChessSquare)(DEMOTED *bp)),
5614 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5615 message[1] = BOARD_RGHT - 1 - j + '1';
5616 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5618 SendToProgram(message, cps);
5623 SendToProgram("c\n", cps);
5624 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5625 bp = &boards[moveNum][i][BOARD_LEFT];
5626 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5627 if (((int) *bp != (int) EmptySquare)
5628 && ((int) *bp >= (int) BlackPawn)) {
5629 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5631 if(message[0] == '+' || message[0] == '~') {
5632 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5633 PieceToChar((ChessSquare)(DEMOTED *bp)),
5636 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5637 message[1] = BOARD_RGHT - 1 - j + '1';
5638 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5640 SendToProgram(message, cps);
5645 SendToProgram(".\n", cps);
5647 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5650 static int autoQueen; // [HGM] oneclick
5653 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5655 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5656 /* [HGM] add Shogi promotions */
5657 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5662 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5663 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5665 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5666 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5669 piece = boards[currentMove][fromY][fromX];
5670 if(gameInfo.variant == VariantShogi) {
5671 promotionZoneSize = BOARD_HEIGHT/3;
5672 highestPromotingPiece = (int)WhiteFerz;
5673 } else if(gameInfo.variant == VariantMakruk) {
5674 promotionZoneSize = 3;
5677 // next weed out all moves that do not touch the promotion zone at all
5678 if((int)piece >= BlackPawn) {
5679 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5681 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5683 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5684 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5687 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5689 // weed out mandatory Shogi promotions
5690 if(gameInfo.variant == VariantShogi) {
5691 if(piece >= BlackPawn) {
5692 if(toY == 0 && piece == BlackPawn ||
5693 toY == 0 && piece == BlackQueen ||
5694 toY <= 1 && piece == BlackKnight) {
5699 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5700 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5701 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5708 // weed out obviously illegal Pawn moves
5709 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5710 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5711 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5712 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5713 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5714 // note we are not allowed to test for valid (non-)capture, due to premove
5717 // we either have a choice what to promote to, or (in Shogi) whether to promote
5718 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5719 *promoChoice = PieceToChar(BlackFerz); // no choice
5722 // no sense asking what we must promote to if it is going to explode...
5723 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
5724 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
5727 if(autoQueen) { // predetermined
5728 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantLosers)
5729 *promoChoice = PieceToChar(BlackKing); // in Suicide Q is the last thing we want
5730 else *promoChoice = PieceToChar(BlackQueen);
5734 // suppress promotion popup on illegal moves that are not premoves
5735 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5736 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5737 if(appData.testLegality && !premove) {
5738 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5739 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
5740 if(moveType != WhitePromotion && moveType != BlackPromotion)
5748 InPalace(row, column)
5750 { /* [HGM] for Xiangqi */
5751 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5752 column < (BOARD_WIDTH + 4)/2 &&
5753 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5758 PieceForSquare (x, y)
5762 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5765 return boards[currentMove][y][x];
5769 OKToStartUserMove(x, y)
5772 ChessSquare from_piece;
5775 if (matchMode) return FALSE;
5776 if (gameMode == EditPosition) return TRUE;
5778 if (x >= 0 && y >= 0)
5779 from_piece = boards[currentMove][y][x];
5781 from_piece = EmptySquare;
5783 if (from_piece == EmptySquare) return FALSE;
5785 white_piece = (int)from_piece >= (int)WhitePawn &&
5786 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5789 case PlayFromGameFile:
5791 case TwoMachinesPlay:
5799 case MachinePlaysWhite:
5800 case IcsPlayingBlack:
5801 if (appData.zippyPlay) return FALSE;
5803 DisplayMoveError(_("You are playing Black"));
5808 case MachinePlaysBlack:
5809 case IcsPlayingWhite:
5810 if (appData.zippyPlay) return FALSE;
5812 DisplayMoveError(_("You are playing White"));
5818 if (!white_piece && WhiteOnMove(currentMove)) {
5819 DisplayMoveError(_("It is White's turn"));
5822 if (white_piece && !WhiteOnMove(currentMove)) {
5823 DisplayMoveError(_("It is Black's turn"));
5826 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5827 /* Editing correspondence game history */
5828 /* Could disallow this or prompt for confirmation */
5833 case BeginningOfGame:
5834 if (appData.icsActive) return FALSE;
5835 if (!appData.noChessProgram) {
5837 DisplayMoveError(_("You are playing White"));
5844 if (!white_piece && WhiteOnMove(currentMove)) {
5845 DisplayMoveError(_("It is White's turn"));
5848 if (white_piece && !WhiteOnMove(currentMove)) {
5849 DisplayMoveError(_("It is Black's turn"));
5858 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
5859 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
5860 && gameMode != AnalyzeFile && gameMode != Training) {
5861 DisplayMoveError(_("Displayed position is not current"));
5868 OnlyMove(int *x, int *y, Boolean captures) {
5869 DisambiguateClosure cl;
5870 if (appData.zippyPlay) return FALSE;
5872 case MachinePlaysBlack:
5873 case IcsPlayingWhite:
5874 case BeginningOfGame:
5875 if(!WhiteOnMove(currentMove)) return FALSE;
5877 case MachinePlaysWhite:
5878 case IcsPlayingBlack:
5879 if(WhiteOnMove(currentMove)) return FALSE;
5886 cl.pieceIn = EmptySquare;
5891 cl.promoCharIn = NULLCHAR;
5892 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5893 if( cl.kind == NormalMove ||
5894 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
5895 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
5896 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
5903 if(cl.kind != ImpossibleMove) return FALSE;
5904 cl.pieceIn = EmptySquare;
5909 cl.promoCharIn = NULLCHAR;
5910 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5911 if( cl.kind == NormalMove ||
5912 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
5913 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
5914 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
5919 autoQueen = TRUE; // act as if autoQueen on when we click to-square
5925 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
5926 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
5927 int lastLoadGameUseList = FALSE;
5928 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
5929 ChessMove lastLoadGameStart = EndOfFile;
5932 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
5933 int fromX, fromY, toX, toY;
5937 ChessSquare pdown, pup;
5939 /* Check if the user is playing in turn. This is complicated because we
5940 let the user "pick up" a piece before it is his turn. So the piece he
5941 tried to pick up may have been captured by the time he puts it down!
5942 Therefore we use the color the user is supposed to be playing in this
5943 test, not the color of the piece that is currently on the starting
5944 square---except in EditGame mode, where the user is playing both
5945 sides; fortunately there the capture race can't happen. (It can
5946 now happen in IcsExamining mode, but that's just too bad. The user
5947 will get a somewhat confusing message in that case.)
5951 case PlayFromGameFile:
5953 case TwoMachinesPlay:
5957 /* We switched into a game mode where moves are not accepted,
5958 perhaps while the mouse button was down. */
5961 case MachinePlaysWhite:
5962 /* User is moving for Black */
5963 if (WhiteOnMove(currentMove)) {
5964 DisplayMoveError(_("It is White's turn"));
5969 case MachinePlaysBlack:
5970 /* User is moving for White */
5971 if (!WhiteOnMove(currentMove)) {
5972 DisplayMoveError(_("It is Black's turn"));
5979 case BeginningOfGame:
5982 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
5983 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
5984 /* User is moving for Black */
5985 if (WhiteOnMove(currentMove)) {
5986 DisplayMoveError(_("It is White's turn"));
5990 /* User is moving for White */
5991 if (!WhiteOnMove(currentMove)) {
5992 DisplayMoveError(_("It is Black's turn"));
5998 case IcsPlayingBlack:
5999 /* User is moving for Black */
6000 if (WhiteOnMove(currentMove)) {
6001 if (!appData.premove) {
6002 DisplayMoveError(_("It is White's turn"));
6003 } else if (toX >= 0 && toY >= 0) {
6006 premoveFromX = fromX;
6007 premoveFromY = fromY;
6008 premovePromoChar = promoChar;
6010 if (appData.debugMode)
6011 fprintf(debugFP, "Got premove: fromX %d,"
6012 "fromY %d, toX %d, toY %d\n",
6013 fromX, fromY, toX, toY);
6019 case IcsPlayingWhite:
6020 /* User is moving for White */
6021 if (!WhiteOnMove(currentMove)) {
6022 if (!appData.premove) {
6023 DisplayMoveError(_("It is Black's turn"));
6024 } else if (toX >= 0 && toY >= 0) {
6027 premoveFromX = fromX;
6028 premoveFromY = fromY;
6029 premovePromoChar = promoChar;
6031 if (appData.debugMode)
6032 fprintf(debugFP, "Got premove: fromX %d,"
6033 "fromY %d, toX %d, toY %d\n",
6034 fromX, fromY, toX, toY);
6044 /* EditPosition, empty square, or different color piece;
6045 click-click move is possible */
6046 if (toX == -2 || toY == -2) {
6047 boards[0][fromY][fromX] = EmptySquare;
6048 DrawPosition(FALSE, boards[currentMove]);
6050 } else if (toX >= 0 && toY >= 0) {
6051 boards[0][toY][toX] = boards[0][fromY][fromX];
6052 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6053 if(boards[0][fromY][0] != EmptySquare) {
6054 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6055 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6058 if(fromX == BOARD_RGHT+1) {
6059 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6060 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6061 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6064 boards[0][fromY][fromX] = EmptySquare;
6065 DrawPosition(FALSE, boards[currentMove]);
6071 if(toX < 0 || toY < 0) return;
6072 pdown = boards[currentMove][fromY][fromX];
6073 pup = boards[currentMove][toY][toX];
6075 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6076 if( fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) {
6077 if( pup != EmptySquare ) return;
6078 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6079 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6080 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6081 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6082 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6083 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6084 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6088 /* [HGM] always test for legality, to get promotion info */
6089 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6090 fromY, fromX, toY, toX, promoChar);
6091 /* [HGM] but possibly ignore an IllegalMove result */
6092 if (appData.testLegality) {
6093 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6094 DisplayMoveError(_("Illegal move"));
6099 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6102 /* Common tail of UserMoveEvent and DropMenuEvent */
6104 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6106 int fromX, fromY, toX, toY;
6107 /*char*/int promoChar;
6111 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6112 // [HGM] superchess: suppress promotions to non-available piece
6113 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6114 if(WhiteOnMove(currentMove)) {
6115 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6117 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6121 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6122 move type in caller when we know the move is a legal promotion */
6123 if(moveType == NormalMove && promoChar)
6124 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6126 /* [HGM] <popupFix> The following if has been moved here from
6127 UserMoveEvent(). Because it seemed to belong here (why not allow
6128 piece drops in training games?), and because it can only be
6129 performed after it is known to what we promote. */
6130 if (gameMode == Training) {
6131 /* compare the move played on the board to the next move in the
6132 * game. If they match, display the move and the opponent's response.
6133 * If they don't match, display an error message.
6137 CopyBoard(testBoard, boards[currentMove]);
6138 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6140 if (CompareBoards(testBoard, boards[currentMove+1])) {
6141 ForwardInner(currentMove+1);
6143 /* Autoplay the opponent's response.
6144 * if appData.animate was TRUE when Training mode was entered,
6145 * the response will be animated.
6147 saveAnimate = appData.animate;
6148 appData.animate = animateTraining;
6149 ForwardInner(currentMove+1);
6150 appData.animate = saveAnimate;
6152 /* check for the end of the game */
6153 if (currentMove >= forwardMostMove) {
6154 gameMode = PlayFromGameFile;
6156 SetTrainingModeOff();
6157 DisplayInformation(_("End of game"));
6160 DisplayError(_("Incorrect move"), 0);
6165 /* Ok, now we know that the move is good, so we can kill
6166 the previous line in Analysis Mode */
6167 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6168 && currentMove < forwardMostMove) {
6169 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6170 else forwardMostMove = currentMove;
6173 /* If we need the chess program but it's dead, restart it */
6174 ResurrectChessProgram();
6176 /* A user move restarts a paused game*/
6180 thinkOutput[0] = NULLCHAR;
6182 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6184 if(Adjudicate(NULL)) return 1; // [HGM] adjudicate: take care of automtic game end
6186 if (gameMode == BeginningOfGame) {
6187 if (appData.noChessProgram) {
6188 gameMode = EditGame;
6192 gameMode = MachinePlaysBlack;
6195 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6197 if (first.sendName) {
6198 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6199 SendToProgram(buf, &first);
6206 /* Relay move to ICS or chess engine */
6207 if (appData.icsActive) {
6208 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6209 gameMode == IcsExamining) {
6210 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6211 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6213 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6215 // also send plain move, in case ICS does not understand atomic claims
6216 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6220 if (first.sendTime && (gameMode == BeginningOfGame ||
6221 gameMode == MachinePlaysWhite ||
6222 gameMode == MachinePlaysBlack)) {
6223 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6225 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6226 // [HGM] book: if program might be playing, let it use book
6227 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6228 first.maybeThinking = TRUE;
6229 } else SendMoveToProgram(forwardMostMove-1, &first);
6230 if (currentMove == cmailOldMove + 1) {
6231 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6235 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6239 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6245 if (WhiteOnMove(currentMove)) {
6246 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6248 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6252 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6257 case MachinePlaysBlack:
6258 case MachinePlaysWhite:
6259 /* disable certain menu options while machine is thinking */
6260 SetMachineThinkingEnables();
6267 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6269 if(bookHit) { // [HGM] book: simulate book reply
6270 static char bookMove[MSG_SIZ]; // a bit generous?
6272 programStats.nodes = programStats.depth = programStats.time =
6273 programStats.score = programStats.got_only_move = 0;
6274 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6276 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6277 strcat(bookMove, bookHit);
6278 HandleMachineMove(bookMove, &first);
6284 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6291 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6292 Markers *m = (Markers *) closure;
6293 if(rf == fromY && ff == fromX)
6294 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6295 || kind == WhiteCapturesEnPassant
6296 || kind == BlackCapturesEnPassant);
6297 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6301 MarkTargetSquares(int clear)
6304 if(!appData.markers || !appData.highlightDragging ||
6305 !appData.testLegality || gameMode == EditPosition) return;
6307 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6310 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6311 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6312 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6314 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6317 DrawPosition(TRUE, NULL);
6321 Explode(Board board, int fromX, int fromY, int toX, int toY)
6323 if(gameInfo.variant == VariantAtomic &&
6324 (board[toY][toX] != EmptySquare || // capture?
6325 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6326 board[fromY][fromX] == BlackPawn )
6328 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6334 void LeftClick(ClickType clickType, int xPix, int yPix)
6337 Boolean saveAnimate;
6338 static int second = 0, promotionChoice = 0, dragging = 0;
6339 char promoChoice = NULLCHAR;
6341 if(appData.seekGraph && appData.icsActive && loggedOn &&
6342 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6343 SeekGraphClick(clickType, xPix, yPix, 0);
6347 if (clickType == Press) ErrorPopDown();
6348 MarkTargetSquares(1);
6350 x = EventToSquare(xPix, BOARD_WIDTH);
6351 y = EventToSquare(yPix, BOARD_HEIGHT);
6352 if (!flipView && y >= 0) {
6353 y = BOARD_HEIGHT - 1 - y;
6355 if (flipView && x >= 0) {
6356 x = BOARD_WIDTH - 1 - x;
6359 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6360 if(clickType == Release) return; // ignore upclick of click-click destination
6361 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6362 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6363 if(gameInfo.holdingsWidth &&
6364 (WhiteOnMove(currentMove)
6365 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6366 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6367 // click in right holdings, for determining promotion piece
6368 ChessSquare p = boards[currentMove][y][x];
6369 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6370 if(p != EmptySquare) {
6371 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6376 DrawPosition(FALSE, boards[currentMove]);
6380 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6381 if(clickType == Press
6382 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6383 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6384 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6387 autoQueen = appData.alwaysPromoteToQueen;
6390 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE)) {
6391 if (clickType == Press) {
6393 if (OKToStartUserMove(x, y)) {
6397 MarkTargetSquares(0);
6398 DragPieceBegin(xPix, yPix); dragging = 1;
6399 if (appData.highlightDragging) {
6400 SetHighlights(x, y, -1, -1);
6403 } else if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6404 DragPieceEnd(xPix, yPix); dragging = 0;
6405 DrawPosition(FALSE, NULL);
6412 if (clickType == Press && gameMode != EditPosition) {
6417 // ignore off-board to clicks
6418 if(y < 0 || x < 0) return;
6420 /* Check if clicking again on the same color piece */
6421 fromP = boards[currentMove][fromY][fromX];
6422 toP = boards[currentMove][y][x];
6423 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom;
6424 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6425 WhitePawn <= toP && toP <= WhiteKing &&
6426 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6427 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6428 (BlackPawn <= fromP && fromP <= BlackKing &&
6429 BlackPawn <= toP && toP <= BlackKing &&
6430 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6431 !(fromP == BlackKing && toP == BlackRook && frc))) {
6432 /* Clicked again on same color piece -- changed his mind */
6433 second = (x == fromX && y == fromY);
6434 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6435 if (appData.highlightDragging) {
6436 SetHighlights(x, y, -1, -1);
6440 if (OKToStartUserMove(x, y)) {
6442 fromY = y; dragging = 1;
6443 MarkTargetSquares(0);
6444 DragPieceBegin(xPix, yPix);
6449 // ignore clicks on holdings
6450 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6453 if (clickType == Release && x == fromX && y == fromY) {
6454 DragPieceEnd(xPix, yPix); dragging = 0;
6455 if (appData.animateDragging) {
6456 /* Undo animation damage if any */
6457 DrawPosition(FALSE, NULL);
6460 /* Second up/down in same square; just abort move */
6465 ClearPremoveHighlights();
6467 /* First upclick in same square; start click-click mode */
6468 SetHighlights(x, y, -1, -1);
6473 /* we now have a different from- and (possibly off-board) to-square */
6474 /* Completed move */
6477 saveAnimate = appData.animate;
6478 if (clickType == Press) {
6479 /* Finish clickclick move */
6480 if (appData.animate || appData.highlightLastMove) {
6481 SetHighlights(fromX, fromY, toX, toY);
6486 /* Finish drag move */
6487 if (appData.highlightLastMove) {
6488 SetHighlights(fromX, fromY, toX, toY);
6492 DragPieceEnd(xPix, yPix); dragging = 0;
6493 /* Don't animate move and drag both */
6494 appData.animate = FALSE;
6497 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6498 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6499 ChessSquare piece = boards[currentMove][fromY][fromX];
6500 if(gameMode == EditPosition && piece != EmptySquare &&
6501 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6504 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6505 n = PieceToNumber(piece - (int)BlackPawn);
6506 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6507 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6508 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6510 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6511 n = PieceToNumber(piece);
6512 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6513 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6514 boards[currentMove][n][BOARD_WIDTH-2]++;
6516 boards[currentMove][fromY][fromX] = EmptySquare;
6520 DrawPosition(TRUE, boards[currentMove]);
6524 // off-board moves should not be highlighted
6525 if(x < 0 || x < 0) ClearHighlights();
6527 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6528 SetHighlights(fromX, fromY, toX, toY);
6529 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6530 // [HGM] super: promotion to captured piece selected from holdings
6531 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6532 promotionChoice = TRUE;
6533 // kludge follows to temporarily execute move on display, without promoting yet
6534 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6535 boards[currentMove][toY][toX] = p;
6536 DrawPosition(FALSE, boards[currentMove]);
6537 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6538 boards[currentMove][toY][toX] = q;
6539 DisplayMessage("Click in holdings to choose piece", "");
6544 int oldMove = currentMove;
6545 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6546 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6547 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6548 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
6549 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
6550 DrawPosition(TRUE, boards[currentMove]);
6553 appData.animate = saveAnimate;
6554 if (appData.animate || appData.animateDragging) {
6555 /* Undo animation damage if needed */
6556 DrawPosition(FALSE, NULL);
6560 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6561 { // front-end-free part taken out of PieceMenuPopup
6562 int whichMenu; int xSqr, ySqr;
6564 if(seekGraphUp) { // [HGM] seekgraph
6565 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6566 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6570 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6571 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6572 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6573 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6574 if(action == Press) {
6575 originalFlip = flipView;
6576 flipView = !flipView; // temporarily flip board to see game from partners perspective
6577 DrawPosition(TRUE, partnerBoard);
6578 DisplayMessage(partnerStatus, "");
6580 } else if(action == Release) {
6581 flipView = originalFlip;
6582 DrawPosition(TRUE, boards[currentMove]);
6588 xSqr = EventToSquare(x, BOARD_WIDTH);
6589 ySqr = EventToSquare(y, BOARD_HEIGHT);
6590 if (action == Release) UnLoadPV(); // [HGM] pv
6591 if (action != Press) return -2; // return code to be ignored
6594 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6596 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6597 if (xSqr < 0 || ySqr < 0) return -1;
\r
6598 whichMenu = 0; // edit-position menu
6601 if(!appData.icsEngineAnalyze) return -1;
6602 case IcsPlayingWhite:
6603 case IcsPlayingBlack:
6604 if(!appData.zippyPlay) goto noZip;
6607 case MachinePlaysWhite:
6608 case MachinePlaysBlack:
6609 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6610 if (!appData.dropMenu) {
6612 return 2; // flag front-end to grab mouse events
6614 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6615 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6618 if (xSqr < 0 || ySqr < 0) return -1;
6619 if (!appData.dropMenu || appData.testLegality &&
6620 gameInfo.variant != VariantBughouse &&
6621 gameInfo.variant != VariantCrazyhouse) return -1;
6622 whichMenu = 1; // drop menu
6628 if (((*fromX = xSqr) < 0) ||
6629 ((*fromY = ySqr) < 0)) {
6630 *fromX = *fromY = -1;
6634 *fromX = BOARD_WIDTH - 1 - *fromX;
6636 *fromY = BOARD_HEIGHT - 1 - *fromY;
6641 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6643 // char * hint = lastHint;
6644 FrontEndProgramStats stats;
6646 stats.which = cps == &first ? 0 : 1;
6647 stats.depth = cpstats->depth;
6648 stats.nodes = cpstats->nodes;
6649 stats.score = cpstats->score;
6650 stats.time = cpstats->time;
6651 stats.pv = cpstats->movelist;
6652 stats.hint = lastHint;
6653 stats.an_move_index = 0;
6654 stats.an_move_count = 0;
6656 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6657 stats.hint = cpstats->move_name;
6658 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6659 stats.an_move_count = cpstats->nr_moves;
6662 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
6664 SetProgramStats( &stats );
6668 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6669 { // count all piece types
6671 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6672 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6673 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6676 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6677 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
6678 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6679 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6680 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6681 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6686 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
6688 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
6689 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
6691 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
6692 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
6693 if(myPawns == 2 && nMine == 3) // KPP
6694 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
6695 if(myPawns == 1 && nMine == 2) // KP
6696 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6697 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
6698 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
6699 if(myPawns) return FALSE;
6700 if(pCnt[WhiteRook+side])
6701 return pCnt[BlackRook-side] ||
6702 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
6703 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
6704 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
6705 if(pCnt[WhiteCannon+side]) {
6706 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
6707 return majorDefense || pCnt[BlackAlfil-side] >= 2;
6709 if(pCnt[WhiteKnight+side])
6710 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6715 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6717 VariantClass v = gameInfo.variant;
6719 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6720 if(v == VariantShatranj) return TRUE; // always winnable through baring
6721 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6722 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6724 if(v == VariantXiangqi) {
6725 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6727 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6728 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6729 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6730 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6731 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6732 if(stale) // we have at least one last-rank P plus perhaps C
6733 return majors // KPKX
6734 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6736 return pCnt[WhiteFerz+side] // KCAK
6737 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6738 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6739 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6741 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6742 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
6744 if(nMine == 1) return FALSE; // bare King
6745 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
6746 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
6747 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
6748 // by now we have King + 1 piece (or multiple Bishops on the same color)
6749 if(pCnt[WhiteKnight+side])
6750 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
6751 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
6752 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
6754 return (pCnt[BlackKnight-side]); // KBKN, KFKN
6755 if(pCnt[WhiteAlfil+side])
6756 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
6757 if(pCnt[WhiteWazir+side])
6758 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
6765 Adjudicate(ChessProgramState *cps)
6766 { // [HGM] some adjudications useful with buggy engines
6767 // [HGM] adjudicate: made into separate routine, which now can be called after every move
6768 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
6769 // Actually ending the game is now based on the additional internal condition canAdjudicate.
6770 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
6771 int k, count = 0; static int bare = 1;
6772 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
6773 Boolean canAdjudicate = !appData.icsActive;
6775 // most tests only when we understand the game, i.e. legality-checking on
6776 if( appData.testLegality )
6777 { /* [HGM] Some more adjudications for obstinate engines */
6778 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
6779 static int moveCount = 6;
6781 char *reason = NULL;
6783 /* Count what is on board. */
6784 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
6786 /* Some material-based adjudications that have to be made before stalemate test */
6787 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
6788 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
6789 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
6790 if(canAdjudicate && appData.checkMates) {
6792 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6793 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6794 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
6795 "Xboard adjudication: King destroyed", GE_XBOARD );
6800 /* Bare King in Shatranj (loses) or Losers (wins) */
6801 if( nrW == 1 || nrB == 1) {
6802 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
6803 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
6804 if(canAdjudicate && appData.checkMates) {
6806 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
6807 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6808 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
6809 "Xboard adjudication: Bare king", GE_XBOARD );
6813 if( gameInfo.variant == VariantShatranj && --bare < 0)
6815 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
6816 if(canAdjudicate && appData.checkMates) {
6817 /* but only adjudicate if adjudication enabled */
6819 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6820 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6821 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
6822 "Xboard adjudication: Bare king", GE_XBOARD );
6829 // don't wait for engine to announce game end if we can judge ourselves
6830 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
6832 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
6833 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
6834 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
6835 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
6838 reason = "Xboard adjudication: 3rd check";
6839 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
6849 reason = "Xboard adjudication: Stalemate";
6850 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
6851 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
6852 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
6853 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
6854 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
6855 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
6856 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
6857 EP_CHECKMATE : EP_WINS);
6858 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
6859 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
6863 reason = "Xboard adjudication: Checkmate";
6864 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
6868 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
6870 result = GameIsDrawn; break;
6872 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
6874 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
6878 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
6880 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6881 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6882 GameEnds( result, reason, GE_XBOARD );
6886 /* Next absolutely insufficient mating material. */
6887 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
6888 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
6889 { /* includes KBK, KNK, KK of KBKB with like Bishops */
6891 /* always flag draws, for judging claims */
6892 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
6894 if(canAdjudicate && appData.materialDraws) {
6895 /* but only adjudicate them if adjudication enabled */
6896 if(engineOpponent) {
6897 SendToProgram("force\n", engineOpponent); // suppress reply
6898 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
6900 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6901 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
6906 /* Then some trivial draws (only adjudicate, cannot be claimed) */
6907 if(gameInfo.variant == VariantXiangqi ?
6908 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
6910 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
6911 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
6912 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
6913 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
6915 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
6916 { /* if the first 3 moves do not show a tactical win, declare draw */
6917 if(engineOpponent) {
6918 SendToProgram("force\n", engineOpponent); // suppress reply
6919 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6921 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6922 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
6925 } else moveCount = 6;
6927 if (appData.debugMode) { int i;
6928 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
6929 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
6930 appData.drawRepeats);
6931 for( i=forwardMostMove; i>=backwardMostMove; i-- )
6932 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
6936 // Repetition draws and 50-move rule can be applied independently of legality testing
6938 /* Check for rep-draws */
6940 for(k = forwardMostMove-2;
6941 k>=backwardMostMove && k>=forwardMostMove-100 &&
6942 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
6943 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
6946 if(CompareBoards(boards[k], boards[forwardMostMove])) {
6947 /* compare castling rights */
6948 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
6949 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
6950 rights++; /* King lost rights, while rook still had them */
6951 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
6952 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
6953 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
6954 rights++; /* but at least one rook lost them */
6956 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
6957 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
6959 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
6960 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
6961 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
6964 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
6965 && appData.drawRepeats > 1) {
6966 /* adjudicate after user-specified nr of repeats */
6967 int result = GameIsDrawn;
6968 char *details = "XBoard adjudication: repetition draw";
6969 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
6970 // [HGM] xiangqi: check for forbidden perpetuals
6971 int m, ourPerpetual = 1, hisPerpetual = 1;
6972 for(m=forwardMostMove; m>k; m-=2) {
6973 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
6974 ourPerpetual = 0; // the current mover did not always check
6975 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
6976 hisPerpetual = 0; // the opponent did not always check
6978 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
6979 ourPerpetual, hisPerpetual);
6980 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
6981 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
6982 details = "Xboard adjudication: perpetual checking";
6984 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
6985 break; // (or we would have caught him before). Abort repetition-checking loop.
6987 // Now check for perpetual chases
6988 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
6989 hisPerpetual = PerpetualChase(k, forwardMostMove);
6990 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
6991 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
6992 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
6993 details = "Xboard adjudication: perpetual chasing";
6995 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
6996 break; // Abort repetition-checking loop.
6998 // if neither of us is checking or chasing all the time, or both are, it is draw
7000 if(engineOpponent) {
7001 SendToProgram("force\n", engineOpponent); // suppress reply
7002 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7004 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7005 GameEnds( result, details, GE_XBOARD );
7008 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7009 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7013 /* Now we test for 50-move draws. Determine ply count */
7014 count = forwardMostMove;
7015 /* look for last irreversble move */
7016 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7018 /* if we hit starting position, add initial plies */
7019 if( count == backwardMostMove )
7020 count -= initialRulePlies;
7021 count = forwardMostMove - count;
7022 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7023 // adjust reversible move counter for checks in Xiangqi
7024 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7025 if(i < backwardMostMove) i = backwardMostMove;
7026 while(i <= forwardMostMove) {
7027 lastCheck = inCheck; // check evasion does not count
7028 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7029 if(inCheck || lastCheck) count--; // check does not count
7034 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7035 /* this is used to judge if draw claims are legal */
7036 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7037 if(engineOpponent) {
7038 SendToProgram("force\n", engineOpponent); // suppress reply
7039 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7041 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7042 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7046 /* if draw offer is pending, treat it as a draw claim
7047 * when draw condition present, to allow engines a way to
7048 * claim draws before making their move to avoid a race
7049 * condition occurring after their move
7051 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7053 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7054 p = "Draw claim: 50-move rule";
7055 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7056 p = "Draw claim: 3-fold repetition";
7057 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7058 p = "Draw claim: insufficient mating material";
7059 if( p != NULL && canAdjudicate) {
7060 if(engineOpponent) {
7061 SendToProgram("force\n", engineOpponent); // suppress reply
7062 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7064 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7065 GameEnds( GameIsDrawn, p, GE_XBOARD );
7070 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7071 if(engineOpponent) {
7072 SendToProgram("force\n", engineOpponent); // suppress reply
7073 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7075 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7076 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7082 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7083 { // [HGM] book: this routine intercepts moves to simulate book replies
7084 char *bookHit = NULL;
7086 //first determine if the incoming move brings opponent into his book
7087 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7088 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7089 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7090 if(bookHit != NULL && !cps->bookSuspend) {
7091 // make sure opponent is not going to reply after receiving move to book position
7092 SendToProgram("force\n", cps);
7093 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7095 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7096 // now arrange restart after book miss
7098 // after a book hit we never send 'go', and the code after the call to this routine
7099 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7101 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
7102 SendToProgram(buf, cps);
7103 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7104 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7105 SendToProgram("go\n", cps);
7106 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7107 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7108 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7109 SendToProgram("go\n", cps);
7110 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7112 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7116 ChessProgramState *savedState;
7117 void DeferredBookMove(void)
7119 if(savedState->lastPing != savedState->lastPong)
7120 ScheduleDelayedEvent(DeferredBookMove, 10);
7122 HandleMachineMove(savedMessage, savedState);
7126 HandleMachineMove(message, cps)
7128 ChessProgramState *cps;
7130 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7131 char realname[MSG_SIZ];
7132 int fromX, fromY, toX, toY;
7141 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7143 * Kludge to ignore BEL characters
7145 while (*message == '\007') message++;
7148 * [HGM] engine debug message: ignore lines starting with '#' character
7150 if(cps->debug && *message == '#') return;
7153 * Look for book output
7155 if (cps == &first && bookRequested) {
7156 if (message[0] == '\t' || message[0] == ' ') {
7157 /* Part of the book output is here; append it */
7158 strcat(bookOutput, message);
7159 strcat(bookOutput, " \n");
7161 } else if (bookOutput[0] != NULLCHAR) {
7162 /* All of book output has arrived; display it */
7163 char *p = bookOutput;
7164 while (*p != NULLCHAR) {
7165 if (*p == '\t') *p = ' ';
7168 DisplayInformation(bookOutput);
7169 bookRequested = FALSE;
7170 /* Fall through to parse the current output */
7175 * Look for machine move.
7177 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7178 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7180 /* This method is only useful on engines that support ping */
7181 if (cps->lastPing != cps->lastPong) {
7182 if (gameMode == BeginningOfGame) {
7183 /* Extra move from before last new; ignore */
7184 if (appData.debugMode) {
7185 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7188 if (appData.debugMode) {
7189 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7190 cps->which, gameMode);
7193 SendToProgram("undo\n", cps);
7199 case BeginningOfGame:
7200 /* Extra move from before last reset; ignore */
7201 if (appData.debugMode) {
7202 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7209 /* Extra move after we tried to stop. The mode test is
7210 not a reliable way of detecting this problem, but it's
7211 the best we can do on engines that don't support ping.
7213 if (appData.debugMode) {
7214 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7215 cps->which, gameMode);
7217 SendToProgram("undo\n", cps);
7220 case MachinePlaysWhite:
7221 case IcsPlayingWhite:
7222 machineWhite = TRUE;
7225 case MachinePlaysBlack:
7226 case IcsPlayingBlack:
7227 machineWhite = FALSE;
7230 case TwoMachinesPlay:
7231 machineWhite = (cps->twoMachinesColor[0] == 'w');
7234 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7235 if (appData.debugMode) {
7237 "Ignoring move out of turn by %s, gameMode %d"
7238 ", forwardMost %d\n",
7239 cps->which, gameMode, forwardMostMove);
7244 if (appData.debugMode) { int f = forwardMostMove;
7245 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7246 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7247 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7249 if(cps->alphaRank) AlphaRank(machineMove, 4);
7250 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7251 &fromX, &fromY, &toX, &toY, &promoChar)) {
7252 /* Machine move could not be parsed; ignore it. */
7253 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7254 machineMove, cps->which);
7255 DisplayError(buf1, 0);
7256 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7257 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7258 if (gameMode == TwoMachinesPlay) {
7259 GameEnds(machineWhite ? BlackWins : WhiteWins,
7265 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7266 /* So we have to redo legality test with true e.p. status here, */
7267 /* to make sure an illegal e.p. capture does not slip through, */
7268 /* to cause a forfeit on a justified illegal-move complaint */
7269 /* of the opponent. */
7270 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7272 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7273 fromY, fromX, toY, toX, promoChar);
7274 if (appData.debugMode) {
7276 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7277 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7278 fprintf(debugFP, "castling rights\n");
7280 if(moveType == IllegalMove) {
7281 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7282 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7283 GameEnds(machineWhite ? BlackWins : WhiteWins,
7286 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7287 /* [HGM] Kludge to handle engines that send FRC-style castling
7288 when they shouldn't (like TSCP-Gothic) */
7290 case WhiteASideCastleFR:
7291 case BlackASideCastleFR:
7293 currentMoveString[2]++;
7295 case WhiteHSideCastleFR:
7296 case BlackHSideCastleFR:
7298 currentMoveString[2]--;
7300 default: ; // nothing to do, but suppresses warning of pedantic compilers
7303 hintRequested = FALSE;
7304 lastHint[0] = NULLCHAR;
7305 bookRequested = FALSE;
7306 /* Program may be pondering now */
7307 cps->maybeThinking = TRUE;
7308 if (cps->sendTime == 2) cps->sendTime = 1;
7309 if (cps->offeredDraw) cps->offeredDraw--;
7311 /* currentMoveString is set as a side-effect of ParseOneMove */
7312 safeStrCpy(machineMove, currentMoveString, sizeof(machineMove)/sizeof(machineMove[0]));
7313 strcat(machineMove, "\n");
7314 safeStrCpy(moveList[forwardMostMove], machineMove, sizeof(moveList[forwardMostMove])/sizeof(moveList[forwardMostMove][0]));
7316 /* [AS] Save move info*/
7317 pvInfoList[ forwardMostMove ].score = programStats.score;
7318 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7319 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7321 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7323 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7324 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7327 while( count < adjudicateLossPlies ) {
7328 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7331 score = -score; /* Flip score for winning side */
7334 if( score > adjudicateLossThreshold ) {
7341 if( count >= adjudicateLossPlies ) {
7342 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7344 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7345 "Xboard adjudication",
7352 if(Adjudicate(cps)) return; // [HGM] adjudicate: for all automatic game ends
7355 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7357 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7358 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7360 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7362 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7364 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7365 char buf[3*MSG_SIZ];
7367 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7368 programStats.score / 100.,
7370 programStats.time / 100.,
7371 (unsigned int)programStats.nodes,
7372 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7373 programStats.movelist);
7375 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7380 /* [AS] Clear stats for next move */
7381 ClearProgramStats();
7382 thinkOutput[0] = NULLCHAR;
7383 hiddenThinkOutputState = 0;
7386 if (gameMode == TwoMachinesPlay) {
7387 /* [HGM] relaying draw offers moved to after reception of move */
7388 /* and interpreting offer as claim if it brings draw condition */
7389 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7390 SendToProgram("draw\n", cps->other);
7392 if (cps->other->sendTime) {
7393 SendTimeRemaining(cps->other,
7394 cps->other->twoMachinesColor[0] == 'w');
7396 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7397 if (firstMove && !bookHit) {
7399 if (cps->other->useColors) {
7400 SendToProgram(cps->other->twoMachinesColor, cps->other);
7402 SendToProgram("go\n", cps->other);
7404 cps->other->maybeThinking = TRUE;
7407 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7409 if (!pausing && appData.ringBellAfterMoves) {
7414 * Reenable menu items that were disabled while
7415 * machine was thinking
7417 if (gameMode != TwoMachinesPlay)
7418 SetUserThinkingEnables();
7420 // [HGM] book: after book hit opponent has received move and is now in force mode
7421 // force the book reply into it, and then fake that it outputted this move by jumping
7422 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7424 static char bookMove[MSG_SIZ]; // a bit generous?
7426 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7427 strcat(bookMove, bookHit);
7430 programStats.nodes = programStats.depth = programStats.time =
7431 programStats.score = programStats.got_only_move = 0;
7432 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7434 if(cps->lastPing != cps->lastPong) {
7435 savedMessage = message; // args for deferred call
7437 ScheduleDelayedEvent(DeferredBookMove, 10);
7446 /* Set special modes for chess engines. Later something general
7447 * could be added here; for now there is just one kludge feature,
7448 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7449 * when "xboard" is given as an interactive command.
7451 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7452 cps->useSigint = FALSE;
7453 cps->useSigterm = FALSE;
7455 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7456 ParseFeatures(message+8, cps);
7457 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7460 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7461 * want this, I was asked to put it in, and obliged.
7463 if (!strncmp(message, "setboard ", 9)) {
7464 Board initial_position;
7466 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7468 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7469 DisplayError(_("Bad FEN received from engine"), 0);
7473 CopyBoard(boards[0], initial_position);
7474 initialRulePlies = FENrulePlies;
7475 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7476 else gameMode = MachinePlaysBlack;
7477 DrawPosition(FALSE, boards[currentMove]);
7483 * Look for communication commands
7485 if (!strncmp(message, "telluser ", 9)) {
7486 EscapeExpand(message+9, message+9); // [HGM] esc: allow escape sequences in popup box
7487 DisplayNote(message + 9);
7490 if (!strncmp(message, "tellusererror ", 14)) {
7492 EscapeExpand(message+14, message+14); // [HGM] esc: allow escape sequences in popup box
7493 DisplayError(message + 14, 0);
7496 if (!strncmp(message, "tellopponent ", 13)) {
7497 if (appData.icsActive) {
7499 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7503 DisplayNote(message + 13);
7507 if (!strncmp(message, "tellothers ", 11)) {
7508 if (appData.icsActive) {
7510 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7516 if (!strncmp(message, "tellall ", 8)) {
7517 if (appData.icsActive) {
7519 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7523 DisplayNote(message + 8);
7527 if (strncmp(message, "warning", 7) == 0) {
7528 /* Undocumented feature, use tellusererror in new code */
7529 DisplayError(message, 0);
7532 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7533 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
7534 strcat(realname, " query");
7535 AskQuestion(realname, buf2, buf1, cps->pr);
7538 /* Commands from the engine directly to ICS. We don't allow these to be
7539 * sent until we are logged on. Crafty kibitzes have been known to
7540 * interfere with the login process.
7543 if (!strncmp(message, "tellics ", 8)) {
7544 SendToICS(message + 8);
7548 if (!strncmp(message, "tellicsnoalias ", 15)) {
7549 SendToICS(ics_prefix);
7550 SendToICS(message + 15);
7554 /* The following are for backward compatibility only */
7555 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7556 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7557 SendToICS(ics_prefix);
7563 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7567 * If the move is illegal, cancel it and redraw the board.
7568 * Also deal with other error cases. Matching is rather loose
7569 * here to accommodate engines written before the spec.
7571 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7572 strncmp(message, "Error", 5) == 0) {
7573 if (StrStr(message, "name") ||
7574 StrStr(message, "rating") || StrStr(message, "?") ||
7575 StrStr(message, "result") || StrStr(message, "board") ||
7576 StrStr(message, "bk") || StrStr(message, "computer") ||
7577 StrStr(message, "variant") || StrStr(message, "hint") ||
7578 StrStr(message, "random") || StrStr(message, "depth") ||
7579 StrStr(message, "accepted")) {
7582 if (StrStr(message, "protover")) {
7583 /* Program is responding to input, so it's apparently done
7584 initializing, and this error message indicates it is
7585 protocol version 1. So we don't need to wait any longer
7586 for it to initialize and send feature commands. */
7587 FeatureDone(cps, 1);
7588 cps->protocolVersion = 1;
7591 cps->maybeThinking = FALSE;
7593 if (StrStr(message, "draw")) {
7594 /* Program doesn't have "draw" command */
7595 cps->sendDrawOffers = 0;
7598 if (cps->sendTime != 1 &&
7599 (StrStr(message, "time") || StrStr(message, "otim"))) {
7600 /* Program apparently doesn't have "time" or "otim" command */
7604 if (StrStr(message, "analyze")) {
7605 cps->analysisSupport = FALSE;
7606 cps->analyzing = FALSE;
7608 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
7609 DisplayError(buf2, 0);
7612 if (StrStr(message, "(no matching move)st")) {
7613 /* Special kludge for GNU Chess 4 only */
7614 cps->stKludge = TRUE;
7615 SendTimeControl(cps, movesPerSession, timeControl,
7616 timeIncrement, appData.searchDepth,
7620 if (StrStr(message, "(no matching move)sd")) {
7621 /* Special kludge for GNU Chess 4 only */
7622 cps->sdKludge = TRUE;
7623 SendTimeControl(cps, movesPerSession, timeControl,
7624 timeIncrement, appData.searchDepth,
7628 if (!StrStr(message, "llegal")) {
7631 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7632 gameMode == IcsIdle) return;
7633 if (forwardMostMove <= backwardMostMove) return;
7634 if (pausing) PauseEvent();
7635 if(appData.forceIllegal) {
7636 // [HGM] illegal: machine refused move; force position after move into it
7637 SendToProgram("force\n", cps);
7638 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7639 // we have a real problem now, as SendBoard will use the a2a3 kludge
7640 // when black is to move, while there might be nothing on a2 or black
7641 // might already have the move. So send the board as if white has the move.
7642 // But first we must change the stm of the engine, as it refused the last move
7643 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7644 if(WhiteOnMove(forwardMostMove)) {
7645 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7646 SendBoard(cps, forwardMostMove); // kludgeless board
7648 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7649 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7650 SendBoard(cps, forwardMostMove+1); // kludgeless board
7652 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7653 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7654 gameMode == TwoMachinesPlay)
7655 SendToProgram("go\n", cps);
7658 if (gameMode == PlayFromGameFile) {
7659 /* Stop reading this game file */
7660 gameMode = EditGame;
7663 currentMove = forwardMostMove-1;
7664 DisplayMove(currentMove-1); /* before DisplayMoveError */
7665 SwitchClocks(forwardMostMove-1); // [HGM] race
7666 DisplayBothClocks();
7667 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
7668 parseList[currentMove], cps->which);
7669 DisplayMoveError(buf1);
7670 DrawPosition(FALSE, boards[currentMove]);
7672 /* [HGM] illegal-move claim should forfeit game when Xboard */
7673 /* only passes fully legal moves */
7674 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7675 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7676 "False illegal-move claim", GE_XBOARD );
7680 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7681 /* Program has a broken "time" command that
7682 outputs a string not ending in newline.
7688 * If chess program startup fails, exit with an error message.
7689 * Attempts to recover here are futile.
7691 if ((StrStr(message, "unknown host") != NULL)
7692 || (StrStr(message, "No remote directory") != NULL)
7693 || (StrStr(message, "not found") != NULL)
7694 || (StrStr(message, "No such file") != NULL)
7695 || (StrStr(message, "can't alloc") != NULL)
7696 || (StrStr(message, "Permission denied") != NULL)) {
7698 cps->maybeThinking = FALSE;
7699 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7700 cps->which, cps->program, cps->host, message);
7701 RemoveInputSource(cps->isr);
7702 DisplayFatalError(buf1, 0, 1);
7707 * Look for hint output
7709 if (sscanf(message, "Hint: %s", buf1) == 1) {
7710 if (cps == &first && hintRequested) {
7711 hintRequested = FALSE;
7712 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7713 &fromX, &fromY, &toX, &toY, &promoChar)) {
7714 (void) CoordsToAlgebraic(boards[forwardMostMove],
7715 PosFlags(forwardMostMove),
7716 fromY, fromX, toY, toX, promoChar, buf1);
7717 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7718 DisplayInformation(buf2);
7720 /* Hint move could not be parsed!? */
7721 snprintf(buf2, sizeof(buf2),
7722 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7724 DisplayError(buf2, 0);
7727 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
7733 * Ignore other messages if game is not in progress
7735 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7736 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7739 * look for win, lose, draw, or draw offer
7741 if (strncmp(message, "1-0", 3) == 0) {
7742 char *p, *q, *r = "";
7743 p = strchr(message, '{');
7751 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
7753 } else if (strncmp(message, "0-1", 3) == 0) {
7754 char *p, *q, *r = "";
7755 p = strchr(message, '{');
7763 /* Kludge for Arasan 4.1 bug */
7764 if (strcmp(r, "Black resigns") == 0) {
7765 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
7768 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
7770 } else if (strncmp(message, "1/2", 3) == 0) {
7771 char *p, *q, *r = "";
7772 p = strchr(message, '{');
7781 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
7784 } else if (strncmp(message, "White resign", 12) == 0) {
7785 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7787 } else if (strncmp(message, "Black resign", 12) == 0) {
7788 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7790 } else if (strncmp(message, "White matches", 13) == 0 ||
7791 strncmp(message, "Black matches", 13) == 0 ) {
7792 /* [HGM] ignore GNUShogi noises */
7794 } else if (strncmp(message, "White", 5) == 0 &&
7795 message[5] != '(' &&
7796 StrStr(message, "Black") == NULL) {
7797 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7799 } else if (strncmp(message, "Black", 5) == 0 &&
7800 message[5] != '(') {
7801 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7803 } else if (strcmp(message, "resign") == 0 ||
7804 strcmp(message, "computer resigns") == 0) {
7806 case MachinePlaysBlack:
7807 case IcsPlayingBlack:
7808 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
7810 case MachinePlaysWhite:
7811 case IcsPlayingWhite:
7812 GameEnds(BlackWins, "White resigns", GE_ENGINE);
7814 case TwoMachinesPlay:
7815 if (cps->twoMachinesColor[0] == 'w')
7816 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7818 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7825 } else if (strncmp(message, "opponent mates", 14) == 0) {
7827 case MachinePlaysBlack:
7828 case IcsPlayingBlack:
7829 GameEnds(WhiteWins, "White mates", GE_ENGINE);
7831 case MachinePlaysWhite:
7832 case IcsPlayingWhite:
7833 GameEnds(BlackWins, "Black mates", GE_ENGINE);
7835 case TwoMachinesPlay:
7836 if (cps->twoMachinesColor[0] == 'w')
7837 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7839 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7846 } else if (strncmp(message, "computer mates", 14) == 0) {
7848 case MachinePlaysBlack:
7849 case IcsPlayingBlack:
7850 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
7852 case MachinePlaysWhite:
7853 case IcsPlayingWhite:
7854 GameEnds(WhiteWins, "White mates", GE_ENGINE);
7856 case TwoMachinesPlay:
7857 if (cps->twoMachinesColor[0] == 'w')
7858 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7860 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7867 } else if (strncmp(message, "checkmate", 9) == 0) {
7868 if (WhiteOnMove(forwardMostMove)) {
7869 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7871 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7874 } else if (strstr(message, "Draw") != NULL ||
7875 strstr(message, "game is a draw") != NULL) {
7876 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
7878 } else if (strstr(message, "offer") != NULL &&
7879 strstr(message, "draw") != NULL) {
7881 if (appData.zippyPlay && first.initDone) {
7882 /* Relay offer to ICS */
7883 SendToICS(ics_prefix);
7884 SendToICS("draw\n");
7887 cps->offeredDraw = 2; /* valid until this engine moves twice */
7888 if (gameMode == TwoMachinesPlay) {
7889 if (cps->other->offeredDraw) {
7890 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
7891 /* [HGM] in two-machine mode we delay relaying draw offer */
7892 /* until after we also have move, to see if it is really claim */
7894 } else if (gameMode == MachinePlaysWhite ||
7895 gameMode == MachinePlaysBlack) {
7896 if (userOfferedDraw) {
7897 DisplayInformation(_("Machine accepts your draw offer"));
7898 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
7900 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
7907 * Look for thinking output
7909 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
7910 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
7912 int plylev, mvleft, mvtot, curscore, time;
7913 char mvname[MOVE_LEN];
7917 int prefixHint = FALSE;
7918 mvname[0] = NULLCHAR;
7921 case MachinePlaysBlack:
7922 case IcsPlayingBlack:
7923 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
7925 case MachinePlaysWhite:
7926 case IcsPlayingWhite:
7927 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
7932 case IcsObserving: /* [DM] icsEngineAnalyze */
7933 if (!appData.icsEngineAnalyze) ignore = TRUE;
7935 case TwoMachinesPlay:
7936 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
7946 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
7948 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
7949 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
7951 if (plyext != ' ' && plyext != '\t') {
7955 /* [AS] Negate score if machine is playing black and reporting absolute scores */
7956 if( cps->scoreIsAbsolute &&
7957 ( gameMode == MachinePlaysBlack ||
7958 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
7959 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
7960 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
7961 !WhiteOnMove(currentMove)
7964 curscore = -curscore;
7968 tempStats.depth = plylev;
7969 tempStats.nodes = nodes;
7970 tempStats.time = time;
7971 tempStats.score = curscore;
7972 tempStats.got_only_move = 0;
7974 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
7977 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
7978 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
7979 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
7980 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
7981 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
7982 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
7983 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
7984 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
7987 /* Buffer overflow protection */
7988 if (buf1[0] != NULLCHAR) {
7989 if (strlen(buf1) >= sizeof(tempStats.movelist)
7990 && appData.debugMode) {
7992 "PV is too long; using the first %u bytes.\n",
7993 (unsigned) sizeof(tempStats.movelist) - 1);
7996 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
7998 sprintf(tempStats.movelist, " no PV\n");
8001 if (tempStats.seen_stat) {
8002 tempStats.ok_to_send = 1;
8005 if (strchr(tempStats.movelist, '(') != NULL) {
8006 tempStats.line_is_book = 1;
8007 tempStats.nr_moves = 0;
8008 tempStats.moves_left = 0;
8010 tempStats.line_is_book = 0;
8013 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8014 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8016 SendProgramStatsToFrontend( cps, &tempStats );
8019 [AS] Protect the thinkOutput buffer from overflow... this
8020 is only useful if buf1 hasn't overflowed first!
8022 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8024 (gameMode == TwoMachinesPlay ?
8025 ToUpper(cps->twoMachinesColor[0]) : ' '),
8026 ((double) curscore) / 100.0,
8027 prefixHint ? lastHint : "",
8028 prefixHint ? " " : "" );
8030 if( buf1[0] != NULLCHAR ) {
8031 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8033 if( strlen(buf1) > max_len ) {
8034 if( appData.debugMode) {
8035 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8037 buf1[max_len+1] = '\0';
8040 strcat( thinkOutput, buf1 );
8043 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8044 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8045 DisplayMove(currentMove - 1);
8049 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8050 /* crafty (9.25+) says "(only move) <move>"
8051 * if there is only 1 legal move
8053 sscanf(p, "(only move) %s", buf1);
8054 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8055 sprintf(programStats.movelist, "%s (only move)", buf1);
8056 programStats.depth = 1;
8057 programStats.nr_moves = 1;
8058 programStats.moves_left = 1;
8059 programStats.nodes = 1;
8060 programStats.time = 1;
8061 programStats.got_only_move = 1;
8063 /* Not really, but we also use this member to
8064 mean "line isn't going to change" (Crafty
8065 isn't searching, so stats won't change) */
8066 programStats.line_is_book = 1;
8068 SendProgramStatsToFrontend( cps, &programStats );
8070 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8071 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8072 DisplayMove(currentMove - 1);
8075 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8076 &time, &nodes, &plylev, &mvleft,
8077 &mvtot, mvname) >= 5) {
8078 /* The stat01: line is from Crafty (9.29+) in response
8079 to the "." command */
8080 programStats.seen_stat = 1;
8081 cps->maybeThinking = TRUE;
8083 if (programStats.got_only_move || !appData.periodicUpdates)
8086 programStats.depth = plylev;
8087 programStats.time = time;
8088 programStats.nodes = nodes;
8089 programStats.moves_left = mvleft;
8090 programStats.nr_moves = mvtot;
8091 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8092 programStats.ok_to_send = 1;
8093 programStats.movelist[0] = '\0';
8095 SendProgramStatsToFrontend( cps, &programStats );
8099 } else if (strncmp(message,"++",2) == 0) {
8100 /* Crafty 9.29+ outputs this */
8101 programStats.got_fail = 2;
8104 } else if (strncmp(message,"--",2) == 0) {
8105 /* Crafty 9.29+ outputs this */
8106 programStats.got_fail = 1;
8109 } else if (thinkOutput[0] != NULLCHAR &&
8110 strncmp(message, " ", 4) == 0) {
8111 unsigned message_len;
8114 while (*p && *p == ' ') p++;
8116 message_len = strlen( p );
8118 /* [AS] Avoid buffer overflow */
8119 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8120 strcat(thinkOutput, " ");
8121 strcat(thinkOutput, p);
8124 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8125 strcat(programStats.movelist, " ");
8126 strcat(programStats.movelist, p);
8129 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8130 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8131 DisplayMove(currentMove - 1);
8139 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8140 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8142 ChessProgramStats cpstats;
8144 if (plyext != ' ' && plyext != '\t') {
8148 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8149 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8150 curscore = -curscore;
8153 cpstats.depth = plylev;
8154 cpstats.nodes = nodes;
8155 cpstats.time = time;
8156 cpstats.score = curscore;
8157 cpstats.got_only_move = 0;
8158 cpstats.movelist[0] = '\0';
8160 if (buf1[0] != NULLCHAR) {
8161 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8164 cpstats.ok_to_send = 0;
8165 cpstats.line_is_book = 0;
8166 cpstats.nr_moves = 0;
8167 cpstats.moves_left = 0;
8169 SendProgramStatsToFrontend( cps, &cpstats );
8176 /* Parse a game score from the character string "game", and
8177 record it as the history of the current game. The game
8178 score is NOT assumed to start from the standard position.
8179 The display is not updated in any way.
8182 ParseGameHistory(game)
8186 int fromX, fromY, toX, toY, boardIndex;
8191 if (appData.debugMode)
8192 fprintf(debugFP, "Parsing game history: %s\n", game);
8194 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8195 gameInfo.site = StrSave(appData.icsHost);
8196 gameInfo.date = PGNDate();
8197 gameInfo.round = StrSave("-");
8199 /* Parse out names of players */
8200 while (*game == ' ') game++;
8202 while (*game != ' ') *p++ = *game++;
8204 gameInfo.white = StrSave(buf);
8205 while (*game == ' ') game++;
8207 while (*game != ' ' && *game != '\n') *p++ = *game++;
8209 gameInfo.black = StrSave(buf);
8212 boardIndex = blackPlaysFirst ? 1 : 0;
8215 yyboardindex = boardIndex;
8216 moveType = (ChessMove) yylex();
8218 case IllegalMove: /* maybe suicide chess, etc. */
8219 if (appData.debugMode) {
8220 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8221 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8222 setbuf(debugFP, NULL);
8224 case WhitePromotion:
8225 case BlackPromotion:
8226 case WhiteNonPromotion:
8227 case BlackNonPromotion:
8229 case WhiteCapturesEnPassant:
8230 case BlackCapturesEnPassant:
8231 case WhiteKingSideCastle:
8232 case WhiteQueenSideCastle:
8233 case BlackKingSideCastle:
8234 case BlackQueenSideCastle:
8235 case WhiteKingSideCastleWild:
8236 case WhiteQueenSideCastleWild:
8237 case BlackKingSideCastleWild:
8238 case BlackQueenSideCastleWild:
8240 case WhiteHSideCastleFR:
8241 case WhiteASideCastleFR:
8242 case BlackHSideCastleFR:
8243 case BlackASideCastleFR:
8245 fromX = currentMoveString[0] - AAA;
8246 fromY = currentMoveString[1] - ONE;
8247 toX = currentMoveString[2] - AAA;
8248 toY = currentMoveString[3] - ONE;
8249 promoChar = currentMoveString[4];
8253 fromX = moveType == WhiteDrop ?
8254 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8255 (int) CharToPiece(ToLower(currentMoveString[0]));
8257 toX = currentMoveString[2] - AAA;
8258 toY = currentMoveString[3] - ONE;
8259 promoChar = NULLCHAR;
8263 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8264 if (appData.debugMode) {
8265 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8266 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8267 setbuf(debugFP, NULL);
8269 DisplayError(buf, 0);
8271 case ImpossibleMove:
8273 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8274 if (appData.debugMode) {
8275 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8276 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8277 setbuf(debugFP, NULL);
8279 DisplayError(buf, 0);
8282 if (boardIndex < backwardMostMove) {
8283 /* Oops, gap. How did that happen? */
8284 DisplayError(_("Gap in move list"), 0);
8287 backwardMostMove = blackPlaysFirst ? 1 : 0;
8288 if (boardIndex > forwardMostMove) {
8289 forwardMostMove = boardIndex;
8293 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8294 strcat(parseList[boardIndex-1], " ");
8295 strcat(parseList[boardIndex-1], yy_text);
8307 case GameUnfinished:
8308 if (gameMode == IcsExamining) {
8309 if (boardIndex < backwardMostMove) {
8310 /* Oops, gap. How did that happen? */
8313 backwardMostMove = blackPlaysFirst ? 1 : 0;
8316 gameInfo.result = moveType;
8317 p = strchr(yy_text, '{');
8318 if (p == NULL) p = strchr(yy_text, '(');
8321 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8323 q = strchr(p, *p == '{' ? '}' : ')');
8324 if (q != NULL) *q = NULLCHAR;
8327 gameInfo.resultDetails = StrSave(p);
8330 if (boardIndex >= forwardMostMove &&
8331 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8332 backwardMostMove = blackPlaysFirst ? 1 : 0;
8335 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8336 fromY, fromX, toY, toX, promoChar,
8337 parseList[boardIndex]);
8338 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8339 /* currentMoveString is set as a side-effect of yylex */
8340 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
8341 strcat(moveList[boardIndex], "\n");
8343 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8344 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8350 if(gameInfo.variant != VariantShogi)
8351 strcat(parseList[boardIndex - 1], "+");
8355 strcat(parseList[boardIndex - 1], "#");
8362 /* Apply a move to the given board */
8364 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8365 int fromX, fromY, toX, toY;
8369 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8370 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8372 /* [HGM] compute & store e.p. status and castling rights for new position */
8373 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8375 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8376 oldEP = (signed char)board[EP_STATUS];
8377 board[EP_STATUS] = EP_NONE;
8379 if( board[toY][toX] != EmptySquare )
8380 board[EP_STATUS] = EP_CAPTURE;
8382 if (fromY == DROP_RANK) {
8384 piece = board[toY][toX] = (ChessSquare) fromX;
8388 if( board[fromY][fromX] == WhitePawn ) {
8389 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8390 board[EP_STATUS] = EP_PAWN_MOVE;
8392 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8393 gameInfo.variant != VariantBerolina || toX < fromX)
8394 board[EP_STATUS] = toX | berolina;
8395 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8396 gameInfo.variant != VariantBerolina || toX > fromX)
8397 board[EP_STATUS] = toX;
8400 if( board[fromY][fromX] == BlackPawn ) {
8401 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8402 board[EP_STATUS] = EP_PAWN_MOVE;
8403 if( toY-fromY== -2) {
8404 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8405 gameInfo.variant != VariantBerolina || toX < fromX)
8406 board[EP_STATUS] = toX | berolina;
8407 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8408 gameInfo.variant != VariantBerolina || toX > fromX)
8409 board[EP_STATUS] = toX;
8413 for(i=0; i<nrCastlingRights; i++) {
8414 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8415 board[CASTLING][i] == toX && castlingRank[i] == toY
8416 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8419 if (fromX == toX && fromY == toY) return;
8421 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8422 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8423 if(gameInfo.variant == VariantKnightmate)
8424 king += (int) WhiteUnicorn - (int) WhiteKing;
8426 /* Code added by Tord: */
8427 /* FRC castling assumed when king captures friendly rook. */
8428 if (board[fromY][fromX] == WhiteKing &&
8429 board[toY][toX] == WhiteRook) {
8430 board[fromY][fromX] = EmptySquare;
8431 board[toY][toX] = EmptySquare;
8433 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8435 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8437 } else if (board[fromY][fromX] == BlackKing &&
8438 board[toY][toX] == BlackRook) {
8439 board[fromY][fromX] = EmptySquare;
8440 board[toY][toX] = EmptySquare;
8442 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8444 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8446 /* End of code added by Tord */
8448 } else if (board[fromY][fromX] == king
8449 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8450 && toY == fromY && toX > fromX+1) {
8451 board[fromY][fromX] = EmptySquare;
8452 board[toY][toX] = king;
8453 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8454 board[fromY][BOARD_RGHT-1] = EmptySquare;
8455 } else if (board[fromY][fromX] == king
8456 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8457 && toY == fromY && toX < fromX-1) {
8458 board[fromY][fromX] = EmptySquare;
8459 board[toY][toX] = king;
8460 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8461 board[fromY][BOARD_LEFT] = EmptySquare;
8462 } else if (board[fromY][fromX] == WhitePawn
8463 && toY >= BOARD_HEIGHT-promoRank
8464 && gameInfo.variant != VariantXiangqi
8466 /* white pawn promotion */
8467 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8468 if (board[toY][toX] == EmptySquare) {
8469 board[toY][toX] = WhiteQueen;
8471 if(gameInfo.variant==VariantBughouse ||
8472 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8473 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8474 board[fromY][fromX] = EmptySquare;
8475 } else if ((fromY == BOARD_HEIGHT-4)
8477 && gameInfo.variant != VariantXiangqi
8478 && gameInfo.variant != VariantBerolina
8479 && (board[fromY][fromX] == WhitePawn)
8480 && (board[toY][toX] == EmptySquare)) {
8481 board[fromY][fromX] = EmptySquare;
8482 board[toY][toX] = WhitePawn;
8483 captured = board[toY - 1][toX];
8484 board[toY - 1][toX] = EmptySquare;
8485 } else if ((fromY == BOARD_HEIGHT-4)
8487 && gameInfo.variant == VariantBerolina
8488 && (board[fromY][fromX] == WhitePawn)
8489 && (board[toY][toX] == EmptySquare)) {
8490 board[fromY][fromX] = EmptySquare;
8491 board[toY][toX] = WhitePawn;
8492 if(oldEP & EP_BEROLIN_A) {
8493 captured = board[fromY][fromX-1];
8494 board[fromY][fromX-1] = EmptySquare;
8495 }else{ captured = board[fromY][fromX+1];
8496 board[fromY][fromX+1] = EmptySquare;
8498 } else if (board[fromY][fromX] == king
8499 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8500 && toY == fromY && toX > fromX+1) {
8501 board[fromY][fromX] = EmptySquare;
8502 board[toY][toX] = king;
8503 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8504 board[fromY][BOARD_RGHT-1] = EmptySquare;
8505 } else if (board[fromY][fromX] == king
8506 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8507 && toY == fromY && toX < fromX-1) {
8508 board[fromY][fromX] = EmptySquare;
8509 board[toY][toX] = king;
8510 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8511 board[fromY][BOARD_LEFT] = EmptySquare;
8512 } else if (fromY == 7 && fromX == 3
8513 && board[fromY][fromX] == BlackKing
8514 && toY == 7 && toX == 5) {
8515 board[fromY][fromX] = EmptySquare;
8516 board[toY][toX] = BlackKing;
8517 board[fromY][7] = EmptySquare;
8518 board[toY][4] = BlackRook;
8519 } else if (fromY == 7 && fromX == 3
8520 && board[fromY][fromX] == BlackKing
8521 && toY == 7 && toX == 1) {
8522 board[fromY][fromX] = EmptySquare;
8523 board[toY][toX] = BlackKing;
8524 board[fromY][0] = EmptySquare;
8525 board[toY][2] = BlackRook;
8526 } else if (board[fromY][fromX] == BlackPawn
8528 && gameInfo.variant != VariantXiangqi
8530 /* black pawn promotion */
8531 board[toY][toX] = CharToPiece(ToLower(promoChar));
8532 if (board[toY][toX] == EmptySquare) {
8533 board[toY][toX] = BlackQueen;
8535 if(gameInfo.variant==VariantBughouse ||
8536 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8537 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8538 board[fromY][fromX] = EmptySquare;
8539 } else if ((fromY == 3)
8541 && gameInfo.variant != VariantXiangqi
8542 && gameInfo.variant != VariantBerolina
8543 && (board[fromY][fromX] == BlackPawn)
8544 && (board[toY][toX] == EmptySquare)) {
8545 board[fromY][fromX] = EmptySquare;
8546 board[toY][toX] = BlackPawn;
8547 captured = board[toY + 1][toX];
8548 board[toY + 1][toX] = EmptySquare;
8549 } else if ((fromY == 3)
8551 && gameInfo.variant == VariantBerolina
8552 && (board[fromY][fromX] == BlackPawn)
8553 && (board[toY][toX] == EmptySquare)) {
8554 board[fromY][fromX] = EmptySquare;
8555 board[toY][toX] = BlackPawn;
8556 if(oldEP & EP_BEROLIN_A) {
8557 captured = board[fromY][fromX-1];
8558 board[fromY][fromX-1] = EmptySquare;
8559 }else{ captured = board[fromY][fromX+1];
8560 board[fromY][fromX+1] = EmptySquare;
8563 board[toY][toX] = board[fromY][fromX];
8564 board[fromY][fromX] = EmptySquare;
8568 if (gameInfo.holdingsWidth != 0) {
8570 /* !!A lot more code needs to be written to support holdings */
8571 /* [HGM] OK, so I have written it. Holdings are stored in the */
8572 /* penultimate board files, so they are automaticlly stored */
8573 /* in the game history. */
8574 if (fromY == DROP_RANK) {
8575 /* Delete from holdings, by decreasing count */
8576 /* and erasing image if necessary */
8578 if(p < (int) BlackPawn) { /* white drop */
8579 p -= (int)WhitePawn;
8580 p = PieceToNumber((ChessSquare)p);
8581 if(p >= gameInfo.holdingsSize) p = 0;
8582 if(--board[p][BOARD_WIDTH-2] <= 0)
8583 board[p][BOARD_WIDTH-1] = EmptySquare;
8584 if((int)board[p][BOARD_WIDTH-2] < 0)
8585 board[p][BOARD_WIDTH-2] = 0;
8586 } else { /* black drop */
8587 p -= (int)BlackPawn;
8588 p = PieceToNumber((ChessSquare)p);
8589 if(p >= gameInfo.holdingsSize) p = 0;
8590 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8591 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8592 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8593 board[BOARD_HEIGHT-1-p][1] = 0;
8596 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8597 && gameInfo.variant != VariantBughouse ) {
8598 /* [HGM] holdings: Add to holdings, if holdings exist */
8599 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8600 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8601 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8604 if (p >= (int) BlackPawn) {
8605 p -= (int)BlackPawn;
8606 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8607 /* in Shogi restore piece to its original first */
8608 captured = (ChessSquare) (DEMOTED captured);
8611 p = PieceToNumber((ChessSquare)p);
8612 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8613 board[p][BOARD_WIDTH-2]++;
8614 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8616 p -= (int)WhitePawn;
8617 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8618 captured = (ChessSquare) (DEMOTED captured);
8621 p = PieceToNumber((ChessSquare)p);
8622 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8623 board[BOARD_HEIGHT-1-p][1]++;
8624 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8627 } else if (gameInfo.variant == VariantAtomic) {
8628 if (captured != EmptySquare) {
8630 for (y = toY-1; y <= toY+1; y++) {
8631 for (x = toX-1; x <= toX+1; x++) {
8632 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8633 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8634 board[y][x] = EmptySquare;
8638 board[toY][toX] = EmptySquare;
8641 if(promoChar == '+') {
8642 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
8643 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8644 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
8645 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
8647 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8648 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8649 // [HGM] superchess: take promotion piece out of holdings
8650 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8651 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8652 if(!--board[k][BOARD_WIDTH-2])
8653 board[k][BOARD_WIDTH-1] = EmptySquare;
8655 if(!--board[BOARD_HEIGHT-1-k][1])
8656 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8662 /* Updates forwardMostMove */
8664 MakeMove(fromX, fromY, toX, toY, promoChar)
8665 int fromX, fromY, toX, toY;
8668 // forwardMostMove++; // [HGM] bare: moved downstream
8670 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8671 int timeLeft; static int lastLoadFlag=0; int king, piece;
8672 piece = boards[forwardMostMove][fromY][fromX];
8673 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8674 if(gameInfo.variant == VariantKnightmate)
8675 king += (int) WhiteUnicorn - (int) WhiteKing;
8676 if(forwardMostMove == 0) {
8678 fprintf(serverMoves, "%s;", second.tidy);
8679 fprintf(serverMoves, "%s;", first.tidy);
8680 if(!blackPlaysFirst)
8681 fprintf(serverMoves, "%s;", second.tidy);
8682 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8683 lastLoadFlag = loadFlag;
8685 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8686 // print castling suffix
8687 if( toY == fromY && piece == king ) {
8689 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8691 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8694 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8695 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8696 boards[forwardMostMove][toY][toX] == EmptySquare
8697 && fromX != toX && fromY != toY)
8698 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8700 if(promoChar != NULLCHAR)
8701 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8703 fprintf(serverMoves, "/%d/%d",
8704 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8705 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8706 else timeLeft = blackTimeRemaining/1000;
8707 fprintf(serverMoves, "/%d", timeLeft);
8709 fflush(serverMoves);
8712 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8713 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8717 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8718 if (commentList[forwardMostMove+1] != NULL) {
8719 free(commentList[forwardMostMove+1]);
8720 commentList[forwardMostMove+1] = NULL;
8722 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8723 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8724 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8725 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8726 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8727 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8728 gameInfo.result = GameUnfinished;
8729 if (gameInfo.resultDetails != NULL) {
8730 free(gameInfo.resultDetails);
8731 gameInfo.resultDetails = NULL;
8733 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
8734 moveList[forwardMostMove - 1]);
8735 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
8736 PosFlags(forwardMostMove - 1),
8737 fromY, fromX, toY, toX, promoChar,
8738 parseList[forwardMostMove - 1]);
8739 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8745 if(gameInfo.variant != VariantShogi)
8746 strcat(parseList[forwardMostMove - 1], "+");
8750 strcat(parseList[forwardMostMove - 1], "#");
8753 if (appData.debugMode) {
8754 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
8759 /* Updates currentMove if not pausing */
8761 ShowMove(fromX, fromY, toX, toY)
8763 int instant = (gameMode == PlayFromGameFile) ?
8764 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
8765 if(appData.noGUI) return;
8766 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8768 if (forwardMostMove == currentMove + 1) {
8769 AnimateMove(boards[forwardMostMove - 1],
8770 fromX, fromY, toX, toY);
8772 if (appData.highlightLastMove) {
8773 SetHighlights(fromX, fromY, toX, toY);
8776 currentMove = forwardMostMove;
8779 if (instant) return;
8781 DisplayMove(currentMove - 1);
8782 DrawPosition(FALSE, boards[currentMove]);
8783 DisplayBothClocks();
8784 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8787 void SendEgtPath(ChessProgramState *cps)
8788 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
8789 char buf[MSG_SIZ], name[MSG_SIZ], *p;
8791 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
8794 char c, *q = name+1, *r, *s;
8796 name[0] = ','; // extract next format name from feature and copy with prefixed ','
8797 while(*p && *p != ',') *q++ = *p++;
8799 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
8800 strcmp(name, ",nalimov:") == 0 ) {
8801 // take nalimov path from the menu-changeable option first, if it is defined
8802 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
8803 SendToProgram(buf,cps); // send egtbpath command for nalimov
8805 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
8806 (s = StrStr(appData.egtFormats, name)) != NULL) {
8807 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
8808 s = r = StrStr(s, ":") + 1; // beginning of path info
8809 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
8810 c = *r; *r = 0; // temporarily null-terminate path info
8811 *--q = 0; // strip of trailig ':' from name
8812 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
8814 SendToProgram(buf,cps); // send egtbpath command for this format
8816 if(*p == ',') p++; // read away comma to position for next format name
8821 InitChessProgram(cps, setup)
8822 ChessProgramState *cps;
8823 int setup; /* [HGM] needed to setup FRC opening position */
8825 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
8826 if (appData.noChessProgram) return;
8827 hintRequested = FALSE;
8828 bookRequested = FALSE;
8830 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
8831 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
8832 if(cps->memSize) { /* [HGM] memory */
8833 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
8834 SendToProgram(buf, cps);
8836 SendEgtPath(cps); /* [HGM] EGT */
8837 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
8838 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
8839 SendToProgram(buf, cps);
8842 SendToProgram(cps->initString, cps);
8843 if (gameInfo.variant != VariantNormal &&
8844 gameInfo.variant != VariantLoadable
8845 /* [HGM] also send variant if board size non-standard */
8846 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
8848 char *v = VariantName(gameInfo.variant);
8849 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
8850 /* [HGM] in protocol 1 we have to assume all variants valid */
8851 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
8852 DisplayFatalError(buf, 0, 1);
8856 /* [HGM] make prefix for non-standard board size. Awkward testing... */
8857 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8858 if( gameInfo.variant == VariantXiangqi )
8859 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
8860 if( gameInfo.variant == VariantShogi )
8861 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
8862 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
8863 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
8864 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
8865 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon )
8866 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8867 if( gameInfo.variant == VariantCourier )
8868 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8869 if( gameInfo.variant == VariantSuper )
8870 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
8871 if( gameInfo.variant == VariantGreat )
8872 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
8875 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
8876 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
8877 /* [HGM] varsize: try first if this defiant size variant is specifically known */
8878 if(StrStr(cps->variants, b) == NULL) {
8879 // specific sized variant not known, check if general sizing allowed
8880 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
8881 if(StrStr(cps->variants, "boardsize") == NULL) {
8882 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
8883 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
8884 DisplayFatalError(buf, 0, 1);
8887 /* [HGM] here we really should compare with the maximum supported board size */
8890 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
8891 snprintf(buf, MSG_SIZ, "variant %s\n", b);
8892 SendToProgram(buf, cps);
8894 currentlyInitializedVariant = gameInfo.variant;
8896 /* [HGM] send opening position in FRC to first engine */
8898 SendToProgram("force\n", cps);
8900 /* engine is now in force mode! Set flag to wake it up after first move. */
8901 setboardSpoiledMachineBlack = 1;
8905 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
8906 SendToProgram(buf, cps);
8908 cps->maybeThinking = FALSE;
8909 cps->offeredDraw = 0;
8910 if (!appData.icsActive) {
8911 SendTimeControl(cps, movesPerSession, timeControl,
8912 timeIncrement, appData.searchDepth,
8915 if (appData.showThinking
8916 // [HGM] thinking: four options require thinking output to be sent
8917 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8919 SendToProgram("post\n", cps);
8921 SendToProgram("hard\n", cps);
8922 if (!appData.ponderNextMove) {
8923 /* Warning: "easy" is a toggle in GNU Chess, so don't send
8924 it without being sure what state we are in first. "hard"
8925 is not a toggle, so that one is OK.
8927 SendToProgram("easy\n", cps);
8930 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
8931 SendToProgram(buf, cps);
8933 cps->initDone = TRUE;
8938 StartChessProgram(cps)
8939 ChessProgramState *cps;
8944 if (appData.noChessProgram) return;
8945 cps->initDone = FALSE;
8947 if (strcmp(cps->host, "localhost") == 0) {
8948 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
8949 } else if (*appData.remoteShell == NULLCHAR) {
8950 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
8952 if (*appData.remoteUser == NULLCHAR) {
8953 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
8956 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
8957 cps->host, appData.remoteUser, cps->program);
8959 err = StartChildProcess(buf, "", &cps->pr);
8963 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
8964 DisplayFatalError(buf, err, 1);
8970 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
8971 if (cps->protocolVersion > 1) {
8972 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
8973 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
8974 cps->comboCnt = 0; // and values of combo boxes
8975 SendToProgram(buf, cps);
8977 SendToProgram("xboard\n", cps);
8983 TwoMachinesEventIfReady P((void))
8985 if (first.lastPing != first.lastPong) {
8986 DisplayMessage("", _("Waiting for first chess program"));
8987 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
8990 if (second.lastPing != second.lastPong) {
8991 DisplayMessage("", _("Waiting for second chess program"));
8992 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9000 NextMatchGame P((void))
9002 int index; /* [HGM] autoinc: step load index during match */
9004 if (*appData.loadGameFile != NULLCHAR) {
9005 index = appData.loadGameIndex;
9006 if(index < 0) { // [HGM] autoinc
9007 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9008 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9010 LoadGameFromFile(appData.loadGameFile,
9012 appData.loadGameFile, FALSE);
9013 } else if (*appData.loadPositionFile != NULLCHAR) {
9014 index = appData.loadPositionIndex;
9015 if(index < 0) { // [HGM] autoinc
9016 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9017 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9019 LoadPositionFromFile(appData.loadPositionFile,
9021 appData.loadPositionFile);
9023 TwoMachinesEventIfReady();
9026 void UserAdjudicationEvent( int result )
9028 ChessMove gameResult = GameIsDrawn;
9031 gameResult = WhiteWins;
9033 else if( result < 0 ) {
9034 gameResult = BlackWins;
9037 if( gameMode == TwoMachinesPlay ) {
9038 GameEnds( gameResult, "User adjudication", GE_XBOARD );
9043 // [HGM] save: calculate checksum of game to make games easily identifiable
9044 int StringCheckSum(char *s)
9047 if(s==NULL) return 0;
9048 while(*s) i = i*259 + *s++;
9055 for(i=backwardMostMove; i<forwardMostMove; i++) {
9056 sum += pvInfoList[i].depth;
9057 sum += StringCheckSum(parseList[i]);
9058 sum += StringCheckSum(commentList[i]);
9061 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
9062 return sum + StringCheckSum(commentList[i]);
9063 } // end of save patch
9066 GameEnds(result, resultDetails, whosays)
9068 char *resultDetails;
9071 GameMode nextGameMode;
9073 char buf[MSG_SIZ], popupRequested = 0;
9075 if(endingGame) return; /* [HGM] crash: forbid recursion */
9077 if(twoBoards) { // [HGM] dual: switch back to one board
9078 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
9079 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
9081 if (appData.debugMode) {
9082 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
9083 result, resultDetails ? resultDetails : "(null)", whosays);
9086 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9088 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9089 /* If we are playing on ICS, the server decides when the
9090 game is over, but the engine can offer to draw, claim
9094 if (appData.zippyPlay && first.initDone) {
9095 if (result == GameIsDrawn) {
9096 /* In case draw still needs to be claimed */
9097 SendToICS(ics_prefix);
9098 SendToICS("draw\n");
9099 } else if (StrCaseStr(resultDetails, "resign")) {
9100 SendToICS(ics_prefix);
9101 SendToICS("resign\n");
9105 endingGame = 0; /* [HGM] crash */
9109 /* If we're loading the game from a file, stop */
9110 if (whosays == GE_FILE) {
9111 (void) StopLoadGameTimer();
9115 /* Cancel draw offers */
9116 first.offeredDraw = second.offeredDraw = 0;
9118 /* If this is an ICS game, only ICS can really say it's done;
9119 if not, anyone can. */
9120 isIcsGame = (gameMode == IcsPlayingWhite ||
9121 gameMode == IcsPlayingBlack ||
9122 gameMode == IcsObserving ||
9123 gameMode == IcsExamining);
9125 if (!isIcsGame || whosays == GE_ICS) {
9126 /* OK -- not an ICS game, or ICS said it was done */
9128 if (!isIcsGame && !appData.noChessProgram)
9129 SetUserThinkingEnables();
9131 /* [HGM] if a machine claims the game end we verify this claim */
9132 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9133 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9135 ChessMove trueResult = (ChessMove) -1;
9137 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9138 first.twoMachinesColor[0] :
9139 second.twoMachinesColor[0] ;
9141 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9142 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9143 /* [HGM] verify: engine mate claims accepted if they were flagged */
9144 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9146 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9147 /* [HGM] verify: engine mate claims accepted if they were flagged */
9148 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9150 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9151 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9154 // now verify win claims, but not in drop games, as we don't understand those yet
9155 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9156 || gameInfo.variant == VariantGreat) &&
9157 (result == WhiteWins && claimer == 'w' ||
9158 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9159 if (appData.debugMode) {
9160 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9161 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9163 if(result != trueResult) {
9164 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
9165 result = claimer == 'w' ? BlackWins : WhiteWins;
9166 resultDetails = buf;
9169 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9170 && (forwardMostMove <= backwardMostMove ||
9171 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9172 (claimer=='b')==(forwardMostMove&1))
9174 /* [HGM] verify: draws that were not flagged are false claims */
9175 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
9176 result = claimer == 'w' ? BlackWins : WhiteWins;
9177 resultDetails = buf;
9179 /* (Claiming a loss is accepted no questions asked!) */
9181 /* [HGM] bare: don't allow bare King to win */
9182 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9183 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9184 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9185 && result != GameIsDrawn)
9186 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9187 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9188 int p = (signed char)boards[forwardMostMove][i][j] - color;
9189 if(p >= 0 && p <= (int)WhiteKing) k++;
9191 if (appData.debugMode) {
9192 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9193 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9196 result = GameIsDrawn;
9197 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
9198 resultDetails = buf;
9204 if(serverMoves != NULL && !loadFlag) { char c = '=';
9205 if(result==WhiteWins) c = '+';
9206 if(result==BlackWins) c = '-';
9207 if(resultDetails != NULL)
9208 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9210 if (resultDetails != NULL) {
9211 gameInfo.result = result;
9212 gameInfo.resultDetails = StrSave(resultDetails);
9214 /* display last move only if game was not loaded from file */
9215 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9216 DisplayMove(currentMove - 1);
9218 if (forwardMostMove != 0) {
9219 if (gameMode != PlayFromGameFile && gameMode != EditGame
9220 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9222 if (*appData.saveGameFile != NULLCHAR) {
9223 SaveGameToFile(appData.saveGameFile, TRUE);
9224 } else if (appData.autoSaveGames) {
9227 if (*appData.savePositionFile != NULLCHAR) {
9228 SavePositionToFile(appData.savePositionFile);
9233 /* Tell program how game ended in case it is learning */
9234 /* [HGM] Moved this to after saving the PGN, just in case */
9235 /* engine died and we got here through time loss. In that */
9236 /* case we will get a fatal error writing the pipe, which */
9237 /* would otherwise lose us the PGN. */
9238 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9239 /* output during GameEnds should never be fatal anymore */
9240 if (gameMode == MachinePlaysWhite ||
9241 gameMode == MachinePlaysBlack ||
9242 gameMode == TwoMachinesPlay ||
9243 gameMode == IcsPlayingWhite ||
9244 gameMode == IcsPlayingBlack ||
9245 gameMode == BeginningOfGame) {
9247 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
9249 if (first.pr != NoProc) {
9250 SendToProgram(buf, &first);
9252 if (second.pr != NoProc &&
9253 gameMode == TwoMachinesPlay) {
9254 SendToProgram(buf, &second);
9259 if (appData.icsActive) {
9260 if (appData.quietPlay &&
9261 (gameMode == IcsPlayingWhite ||
9262 gameMode == IcsPlayingBlack)) {
9263 SendToICS(ics_prefix);
9264 SendToICS("set shout 1\n");
9266 nextGameMode = IcsIdle;
9267 ics_user_moved = FALSE;
9268 /* clean up premove. It's ugly when the game has ended and the
9269 * premove highlights are still on the board.
9273 ClearPremoveHighlights();
9274 DrawPosition(FALSE, boards[currentMove]);
9276 if (whosays == GE_ICS) {
9279 if (gameMode == IcsPlayingWhite)
9281 else if(gameMode == IcsPlayingBlack)
9285 if (gameMode == IcsPlayingBlack)
9287 else if(gameMode == IcsPlayingWhite)
9294 PlayIcsUnfinishedSound();
9297 } else if (gameMode == EditGame ||
9298 gameMode == PlayFromGameFile ||
9299 gameMode == AnalyzeMode ||
9300 gameMode == AnalyzeFile) {
9301 nextGameMode = gameMode;
9303 nextGameMode = EndOfGame;
9308 nextGameMode = gameMode;
9311 if (appData.noChessProgram) {
9312 gameMode = nextGameMode;
9314 endingGame = 0; /* [HGM] crash */
9319 /* Put first chess program into idle state */
9320 if (first.pr != NoProc &&
9321 (gameMode == MachinePlaysWhite ||
9322 gameMode == MachinePlaysBlack ||
9323 gameMode == TwoMachinesPlay ||
9324 gameMode == IcsPlayingWhite ||
9325 gameMode == IcsPlayingBlack ||
9326 gameMode == BeginningOfGame)) {
9327 SendToProgram("force\n", &first);
9328 if (first.usePing) {
9330 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
9331 SendToProgram(buf, &first);
9334 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9335 /* Kill off first chess program */
9336 if (first.isr != NULL)
9337 RemoveInputSource(first.isr);
9340 if (first.pr != NoProc) {
9342 DoSleep( appData.delayBeforeQuit );
9343 SendToProgram("quit\n", &first);
9344 DoSleep( appData.delayAfterQuit );
9345 DestroyChildProcess(first.pr, first.useSigterm);
9350 /* Put second chess program into idle state */
9351 if (second.pr != NoProc &&
9352 gameMode == TwoMachinesPlay) {
9353 SendToProgram("force\n", &second);
9354 if (second.usePing) {
9356 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
9357 SendToProgram(buf, &second);
9360 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9361 /* Kill off second chess program */
9362 if (second.isr != NULL)
9363 RemoveInputSource(second.isr);
9366 if (second.pr != NoProc) {
9367 DoSleep( appData.delayBeforeQuit );
9368 SendToProgram("quit\n", &second);
9369 DoSleep( appData.delayAfterQuit );
9370 DestroyChildProcess(second.pr, second.useSigterm);
9375 if (matchMode && gameMode == TwoMachinesPlay) {
9378 if (first.twoMachinesColor[0] == 'w') {
9385 if (first.twoMachinesColor[0] == 'b') {
9394 if (matchGame < appData.matchGames) {
9396 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9397 tmp = first.twoMachinesColor;
9398 first.twoMachinesColor = second.twoMachinesColor;
9399 second.twoMachinesColor = tmp;
9401 gameMode = nextGameMode;
9403 if(appData.matchPause>10000 || appData.matchPause<10)
9404 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9405 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9406 endingGame = 0; /* [HGM] crash */
9409 gameMode = nextGameMode;
9410 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
9411 first.tidy, second.tidy,
9412 first.matchWins, second.matchWins,
9413 appData.matchGames - (first.matchWins + second.matchWins));
9414 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9417 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9418 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9420 gameMode = nextGameMode;
9422 endingGame = 0; /* [HGM] crash */
9423 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9424 if(matchMode == TRUE) DisplayFatalError(buf, 0, 0); else {
9425 matchMode = FALSE; appData.matchGames = matchGame = 0;
9431 /* Assumes program was just initialized (initString sent).
9432 Leaves program in force mode. */
9434 FeedMovesToProgram(cps, upto)
9435 ChessProgramState *cps;
9440 if (appData.debugMode)
9441 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9442 startedFromSetupPosition ? "position and " : "",
9443 backwardMostMove, upto, cps->which);
9444 if(currentlyInitializedVariant != gameInfo.variant) {
9446 // [HGM] variantswitch: make engine aware of new variant
9447 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9448 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9449 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
9450 SendToProgram(buf, cps);
9451 currentlyInitializedVariant = gameInfo.variant;
9453 SendToProgram("force\n", cps);
9454 if (startedFromSetupPosition) {
9455 SendBoard(cps, backwardMostMove);
9456 if (appData.debugMode) {
9457 fprintf(debugFP, "feedMoves\n");
9460 for (i = backwardMostMove; i < upto; i++) {
9461 SendMoveToProgram(i, cps);
9467 ResurrectChessProgram()
9469 /* The chess program may have exited.
9470 If so, restart it and feed it all the moves made so far. */
9472 if (appData.noChessProgram || first.pr != NoProc) return;
9474 StartChessProgram(&first);
9475 InitChessProgram(&first, FALSE);
9476 FeedMovesToProgram(&first, currentMove);
9478 if (!first.sendTime) {
9479 /* can't tell gnuchess what its clock should read,
9480 so we bow to its notion. */
9482 timeRemaining[0][currentMove] = whiteTimeRemaining;
9483 timeRemaining[1][currentMove] = blackTimeRemaining;
9486 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9487 appData.icsEngineAnalyze) && first.analysisSupport) {
9488 SendToProgram("analyze\n", &first);
9489 first.analyzing = TRUE;
9502 if (appData.debugMode) {
9503 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9504 redraw, init, gameMode);
9506 CleanupTail(); // [HGM] vari: delete any stored variations
9507 pausing = pauseExamInvalid = FALSE;
9508 startedFromSetupPosition = blackPlaysFirst = FALSE;
9510 whiteFlag = blackFlag = FALSE;
9511 userOfferedDraw = FALSE;
9512 hintRequested = bookRequested = FALSE;
9513 first.maybeThinking = FALSE;
9514 second.maybeThinking = FALSE;
9515 first.bookSuspend = FALSE; // [HGM] book
9516 second.bookSuspend = FALSE;
9517 thinkOutput[0] = NULLCHAR;
9518 lastHint[0] = NULLCHAR;
9519 ClearGameInfo(&gameInfo);
9520 gameInfo.variant = StringToVariant(appData.variant);
9521 ics_user_moved = ics_clock_paused = FALSE;
9522 ics_getting_history = H_FALSE;
9524 white_holding[0] = black_holding[0] = NULLCHAR;
9525 ClearProgramStats();
9526 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9530 flipView = appData.flipView;
9531 ClearPremoveHighlights();
9533 alarmSounded = FALSE;
9535 GameEnds(EndOfFile, NULL, GE_PLAYER);
9536 if(appData.serverMovesName != NULL) {
9537 /* [HGM] prepare to make moves file for broadcasting */
9538 clock_t t = clock();
9539 if(serverMoves != NULL) fclose(serverMoves);
9540 serverMoves = fopen(appData.serverMovesName, "r");
9541 if(serverMoves != NULL) {
9542 fclose(serverMoves);
9543 /* delay 15 sec before overwriting, so all clients can see end */
9544 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9546 serverMoves = fopen(appData.serverMovesName, "w");
9550 gameMode = BeginningOfGame;
9552 if(appData.icsActive) gameInfo.variant = VariantNormal;
9553 currentMove = forwardMostMove = backwardMostMove = 0;
9554 InitPosition(redraw);
9555 for (i = 0; i < MAX_MOVES; i++) {
9556 if (commentList[i] != NULL) {
9557 free(commentList[i]);
9558 commentList[i] = NULL;
9562 timeRemaining[0][0] = whiteTimeRemaining;
9563 timeRemaining[1][0] = blackTimeRemaining;
9564 if (first.pr == NULL) {
9565 StartChessProgram(&first);
9568 InitChessProgram(&first, startedFromSetupPosition);
9571 DisplayMessage("", "");
9572 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9573 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9580 if (!AutoPlayOneMove())
9582 if (matchMode || appData.timeDelay == 0)
9584 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
9586 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9595 int fromX, fromY, toX, toY;
9597 if (appData.debugMode) {
9598 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9601 if (gameMode != PlayFromGameFile)
9604 if (currentMove >= forwardMostMove) {
9605 gameMode = EditGame;
9608 /* [AS] Clear current move marker at the end of a game */
9609 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9614 toX = moveList[currentMove][2] - AAA;
9615 toY = moveList[currentMove][3] - ONE;
9617 if (moveList[currentMove][1] == '@') {
9618 if (appData.highlightLastMove) {
9619 SetHighlights(-1, -1, toX, toY);
9622 fromX = moveList[currentMove][0] - AAA;
9623 fromY = moveList[currentMove][1] - ONE;
9625 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9627 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9629 if (appData.highlightLastMove) {
9630 SetHighlights(fromX, fromY, toX, toY);
9633 DisplayMove(currentMove);
9634 SendMoveToProgram(currentMove++, &first);
9635 DisplayBothClocks();
9636 DrawPosition(FALSE, boards[currentMove]);
9637 // [HGM] PV info: always display, routine tests if empty
9638 DisplayComment(currentMove - 1, commentList[currentMove]);
9644 LoadGameOneMove(readAhead)
9645 ChessMove readAhead;
9647 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9648 char promoChar = NULLCHAR;
9653 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9654 gameMode != AnalyzeMode && gameMode != Training) {
9659 yyboardindex = forwardMostMove;
9660 if (readAhead != EndOfFile) {
9661 moveType = readAhead;
9663 if (gameFileFP == NULL)
9665 moveType = (ChessMove) yylex();
9671 if (appData.debugMode)
9672 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9675 /* append the comment but don't display it */
9676 AppendComment(currentMove, p, FALSE);
9679 case WhiteCapturesEnPassant:
9680 case BlackCapturesEnPassant:
9681 case WhitePromotion:
9682 case BlackPromotion:
9683 case WhiteNonPromotion:
9684 case BlackNonPromotion:
9686 case WhiteKingSideCastle:
9687 case WhiteQueenSideCastle:
9688 case BlackKingSideCastle:
9689 case BlackQueenSideCastle:
9690 case WhiteKingSideCastleWild:
9691 case WhiteQueenSideCastleWild:
9692 case BlackKingSideCastleWild:
9693 case BlackQueenSideCastleWild:
9695 case WhiteHSideCastleFR:
9696 case WhiteASideCastleFR:
9697 case BlackHSideCastleFR:
9698 case BlackASideCastleFR:
9700 if (appData.debugMode)
9701 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9702 fromX = currentMoveString[0] - AAA;
9703 fromY = currentMoveString[1] - ONE;
9704 toX = currentMoveString[2] - AAA;
9705 toY = currentMoveString[3] - ONE;
9706 promoChar = currentMoveString[4];
9711 if (appData.debugMode)
9712 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9713 fromX = moveType == WhiteDrop ?
9714 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9715 (int) CharToPiece(ToLower(currentMoveString[0]));
9717 toX = currentMoveString[2] - AAA;
9718 toY = currentMoveString[3] - ONE;
9724 case GameUnfinished:
9725 if (appData.debugMode)
9726 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9727 p = strchr(yy_text, '{');
9728 if (p == NULL) p = strchr(yy_text, '(');
9731 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9733 q = strchr(p, *p == '{' ? '}' : ')');
9734 if (q != NULL) *q = NULLCHAR;
9737 GameEnds(moveType, p, GE_FILE);
9739 if (cmailMsgLoaded) {
9741 flipView = WhiteOnMove(currentMove);
9742 if (moveType == GameUnfinished) flipView = !flipView;
9743 if (appData.debugMode)
9744 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
9749 if (appData.debugMode)
9750 fprintf(debugFP, "Parser hit end of file\n");
9751 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9757 if (WhiteOnMove(currentMove)) {
9758 GameEnds(BlackWins, "Black mates", GE_FILE);
9760 GameEnds(WhiteWins, "White mates", GE_FILE);
9764 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9771 if (lastLoadGameStart == GNUChessGame) {
9772 /* GNUChessGames have numbers, but they aren't move numbers */
9773 if (appData.debugMode)
9774 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9775 yy_text, (int) moveType);
9776 return LoadGameOneMove(EndOfFile); /* tail recursion */
9778 /* else fall thru */
9783 /* Reached start of next game in file */
9784 if (appData.debugMode)
9785 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
9786 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9792 if (WhiteOnMove(currentMove)) {
9793 GameEnds(BlackWins, "Black mates", GE_FILE);
9795 GameEnds(WhiteWins, "White mates", GE_FILE);
9799 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9805 case PositionDiagram: /* should not happen; ignore */
9806 case ElapsedTime: /* ignore */
9807 case NAG: /* ignore */
9808 if (appData.debugMode)
9809 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9810 yy_text, (int) moveType);
9811 return LoadGameOneMove(EndOfFile); /* tail recursion */
9814 if (appData.testLegality) {
9815 if (appData.debugMode)
9816 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
9817 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
9818 (forwardMostMove / 2) + 1,
9819 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9820 DisplayError(move, 0);
9823 if (appData.debugMode)
9824 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
9825 yy_text, currentMoveString);
9826 fromX = currentMoveString[0] - AAA;
9827 fromY = currentMoveString[1] - ONE;
9828 toX = currentMoveString[2] - AAA;
9829 toY = currentMoveString[3] - ONE;
9830 promoChar = currentMoveString[4];
9835 if (appData.debugMode)
9836 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
9837 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
9838 (forwardMostMove / 2) + 1,
9839 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9840 DisplayError(move, 0);
9845 case ImpossibleMove:
9846 if (appData.debugMode)
9847 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
9848 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
9849 (forwardMostMove / 2) + 1,
9850 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9851 DisplayError(move, 0);
9857 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
9858 DrawPosition(FALSE, boards[currentMove]);
9859 DisplayBothClocks();
9860 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
9861 DisplayComment(currentMove - 1, commentList[currentMove]);
9863 (void) StopLoadGameTimer();
9865 cmailOldMove = forwardMostMove;
9868 /* currentMoveString is set as a side-effect of yylex */
9869 strcat(currentMoveString, "\n");
9870 safeStrCpy(moveList[forwardMostMove], currentMoveString, sizeof(moveList[forwardMostMove])/sizeof(moveList[forwardMostMove][0]));
9872 thinkOutput[0] = NULLCHAR;
9873 MakeMove(fromX, fromY, toX, toY, promoChar);
9874 currentMove = forwardMostMove;
9879 /* Load the nth game from the given file */
9881 LoadGameFromFile(filename, n, title, useList)
9885 /*Boolean*/ int useList;
9890 if (strcmp(filename, "-") == 0) {
9894 f = fopen(filename, "rb");
9896 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
9897 DisplayError(buf, errno);
9901 if (fseek(f, 0, 0) == -1) {
9902 /* f is not seekable; probably a pipe */
9905 if (useList && n == 0) {
9906 int error = GameListBuild(f);
9908 DisplayError(_("Cannot build game list"), error);
9909 } else if (!ListEmpty(&gameList) &&
9910 ((ListGame *) gameList.tailPred)->number > 1) {
9911 GameListPopUp(f, title);
9918 return LoadGame(f, n, title, FALSE);
9923 MakeRegisteredMove()
9925 int fromX, fromY, toX, toY;
9927 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
9928 switch (cmailMoveType[lastLoadGameNumber - 1]) {
9931 if (appData.debugMode)
9932 fprintf(debugFP, "Restoring %s for game %d\n",
9933 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
9935 thinkOutput[0] = NULLCHAR;
9936 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
9937 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
9938 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
9939 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
9940 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
9941 promoChar = cmailMove[lastLoadGameNumber - 1][4];
9942 MakeMove(fromX, fromY, toX, toY, promoChar);
9943 ShowMove(fromX, fromY, toX, toY);
9945 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9952 if (WhiteOnMove(currentMove)) {
9953 GameEnds(BlackWins, "Black mates", GE_PLAYER);
9955 GameEnds(WhiteWins, "White mates", GE_PLAYER);
9960 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
9967 if (WhiteOnMove(currentMove)) {
9968 GameEnds(BlackWins, "White resigns", GE_PLAYER);
9970 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
9975 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
9986 /* Wrapper around LoadGame for use when a Cmail message is loaded */
9988 CmailLoadGame(f, gameNumber, title, useList)
9996 if (gameNumber > nCmailGames) {
9997 DisplayError(_("No more games in this message"), 0);
10000 if (f == lastLoadGameFP) {
10001 int offset = gameNumber - lastLoadGameNumber;
10003 cmailMsg[0] = NULLCHAR;
10004 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10005 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
10006 nCmailMovesRegistered--;
10008 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
10009 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
10010 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
10013 if (! RegisterMove()) return FALSE;
10017 retVal = LoadGame(f, gameNumber, title, useList);
10019 /* Make move registered during previous look at this game, if any */
10020 MakeRegisteredMove();
10022 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
10023 commentList[currentMove]
10024 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
10025 DisplayComment(currentMove - 1, commentList[currentMove]);
10031 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
10036 int gameNumber = lastLoadGameNumber + offset;
10037 if (lastLoadGameFP == NULL) {
10038 DisplayError(_("No game has been loaded yet"), 0);
10041 if (gameNumber <= 0) {
10042 DisplayError(_("Can't back up any further"), 0);
10045 if (cmailMsgLoaded) {
10046 return CmailLoadGame(lastLoadGameFP, gameNumber,
10047 lastLoadGameTitle, lastLoadGameUseList);
10049 return LoadGame(lastLoadGameFP, gameNumber,
10050 lastLoadGameTitle, lastLoadGameUseList);
10056 /* Load the nth game from open file f */
10058 LoadGame(f, gameNumber, title, useList)
10066 int gn = gameNumber;
10067 ListGame *lg = NULL;
10068 int numPGNTags = 0;
10070 GameMode oldGameMode;
10071 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
10073 if (appData.debugMode)
10074 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
10076 if (gameMode == Training )
10077 SetTrainingModeOff();
10079 oldGameMode = gameMode;
10080 if (gameMode != BeginningOfGame) {
10081 Reset(FALSE, TRUE);
10085 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10086 fclose(lastLoadGameFP);
10090 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10093 fseek(f, lg->offset, 0);
10094 GameListHighlight(gameNumber);
10098 DisplayError(_("Game number out of range"), 0);
10103 if (fseek(f, 0, 0) == -1) {
10104 if (f == lastLoadGameFP ?
10105 gameNumber == lastLoadGameNumber + 1 :
10109 DisplayError(_("Can't seek on game file"), 0);
10114 lastLoadGameFP = f;
10115 lastLoadGameNumber = gameNumber;
10116 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
10117 lastLoadGameUseList = useList;
10121 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10122 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10123 lg->gameInfo.black);
10125 } else if (*title != NULLCHAR) {
10126 if (gameNumber > 1) {
10127 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
10130 DisplayTitle(title);
10134 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10135 gameMode = PlayFromGameFile;
10139 currentMove = forwardMostMove = backwardMostMove = 0;
10140 CopyBoard(boards[0], initialPosition);
10144 * Skip the first gn-1 games in the file.
10145 * Also skip over anything that precedes an identifiable
10146 * start of game marker, to avoid being confused by
10147 * garbage at the start of the file. Currently
10148 * recognized start of game markers are the move number "1",
10149 * the pattern "gnuchess .* game", the pattern
10150 * "^[#;%] [^ ]* game file", and a PGN tag block.
10151 * A game that starts with one of the latter two patterns
10152 * will also have a move number 1, possibly
10153 * following a position diagram.
10154 * 5-4-02: Let's try being more lenient and allowing a game to
10155 * start with an unnumbered move. Does that break anything?
10157 cm = lastLoadGameStart = EndOfFile;
10159 yyboardindex = forwardMostMove;
10160 cm = (ChessMove) yylex();
10163 if (cmailMsgLoaded) {
10164 nCmailGames = CMAIL_MAX_GAMES - gn;
10167 DisplayError(_("Game not found in file"), 0);
10174 lastLoadGameStart = cm;
10177 case MoveNumberOne:
10178 switch (lastLoadGameStart) {
10183 case MoveNumberOne:
10185 gn--; /* count this game */
10186 lastLoadGameStart = cm;
10195 switch (lastLoadGameStart) {
10198 case MoveNumberOne:
10200 gn--; /* count this game */
10201 lastLoadGameStart = cm;
10204 lastLoadGameStart = cm; /* game counted already */
10212 yyboardindex = forwardMostMove;
10213 cm = (ChessMove) yylex();
10214 } while (cm == PGNTag || cm == Comment);
10221 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10222 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10223 != CMAIL_OLD_RESULT) {
10225 cmailResult[ CMAIL_MAX_GAMES
10226 - gn - 1] = CMAIL_OLD_RESULT;
10232 /* Only a NormalMove can be at the start of a game
10233 * without a position diagram. */
10234 if (lastLoadGameStart == EndOfFile ) {
10236 lastLoadGameStart = MoveNumberOne;
10245 if (appData.debugMode)
10246 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10248 if (cm == XBoardGame) {
10249 /* Skip any header junk before position diagram and/or move 1 */
10251 yyboardindex = forwardMostMove;
10252 cm = (ChessMove) yylex();
10254 if (cm == EndOfFile ||
10255 cm == GNUChessGame || cm == XBoardGame) {
10256 /* Empty game; pretend end-of-file and handle later */
10261 if (cm == MoveNumberOne || cm == PositionDiagram ||
10262 cm == PGNTag || cm == Comment)
10265 } else if (cm == GNUChessGame) {
10266 if (gameInfo.event != NULL) {
10267 free(gameInfo.event);
10269 gameInfo.event = StrSave(yy_text);
10272 startedFromSetupPosition = FALSE;
10273 while (cm == PGNTag) {
10274 if (appData.debugMode)
10275 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10276 err = ParsePGNTag(yy_text, &gameInfo);
10277 if (!err) numPGNTags++;
10279 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10280 if(gameInfo.variant != oldVariant) {
10281 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10282 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10283 InitPosition(TRUE);
10284 oldVariant = gameInfo.variant;
10285 if (appData.debugMode)
10286 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10290 if (gameInfo.fen != NULL) {
10291 Board initial_position;
10292 startedFromSetupPosition = TRUE;
10293 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10295 DisplayError(_("Bad FEN position in file"), 0);
10298 CopyBoard(boards[0], initial_position);
10299 if (blackPlaysFirst) {
10300 currentMove = forwardMostMove = backwardMostMove = 1;
10301 CopyBoard(boards[1], initial_position);
10302 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10303 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10304 timeRemaining[0][1] = whiteTimeRemaining;
10305 timeRemaining[1][1] = blackTimeRemaining;
10306 if (commentList[0] != NULL) {
10307 commentList[1] = commentList[0];
10308 commentList[0] = NULL;
10311 currentMove = forwardMostMove = backwardMostMove = 0;
10313 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10315 initialRulePlies = FENrulePlies;
10316 for( i=0; i< nrCastlingRights; i++ )
10317 initialRights[i] = initial_position[CASTLING][i];
10319 yyboardindex = forwardMostMove;
10320 free(gameInfo.fen);
10321 gameInfo.fen = NULL;
10324 yyboardindex = forwardMostMove;
10325 cm = (ChessMove) yylex();
10327 /* Handle comments interspersed among the tags */
10328 while (cm == Comment) {
10330 if (appData.debugMode)
10331 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10333 AppendComment(currentMove, p, FALSE);
10334 yyboardindex = forwardMostMove;
10335 cm = (ChessMove) yylex();
10339 /* don't rely on existence of Event tag since if game was
10340 * pasted from clipboard the Event tag may not exist
10342 if (numPGNTags > 0){
10344 if (gameInfo.variant == VariantNormal) {
10345 VariantClass v = StringToVariant(gameInfo.event);
10346 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10347 if(v < VariantShogi) gameInfo.variant = v;
10350 if( appData.autoDisplayTags ) {
10351 tags = PGNTags(&gameInfo);
10352 TagsPopUp(tags, CmailMsg());
10357 /* Make something up, but don't display it now */
10362 if (cm == PositionDiagram) {
10365 Board initial_position;
10367 if (appData.debugMode)
10368 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10370 if (!startedFromSetupPosition) {
10372 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10373 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10383 initial_position[i][j++] = CharToPiece(*p);
10386 while (*p == ' ' || *p == '\t' ||
10387 *p == '\n' || *p == '\r') p++;
10389 if (strncmp(p, "black", strlen("black"))==0)
10390 blackPlaysFirst = TRUE;
10392 blackPlaysFirst = FALSE;
10393 startedFromSetupPosition = TRUE;
10395 CopyBoard(boards[0], initial_position);
10396 if (blackPlaysFirst) {
10397 currentMove = forwardMostMove = backwardMostMove = 1;
10398 CopyBoard(boards[1], initial_position);
10399 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10400 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10401 timeRemaining[0][1] = whiteTimeRemaining;
10402 timeRemaining[1][1] = blackTimeRemaining;
10403 if (commentList[0] != NULL) {
10404 commentList[1] = commentList[0];
10405 commentList[0] = NULL;
10408 currentMove = forwardMostMove = backwardMostMove = 0;
10411 yyboardindex = forwardMostMove;
10412 cm = (ChessMove) yylex();
10415 if (first.pr == NoProc) {
10416 StartChessProgram(&first);
10418 InitChessProgram(&first, FALSE);
10419 SendToProgram("force\n", &first);
10420 if (startedFromSetupPosition) {
10421 SendBoard(&first, forwardMostMove);
10422 if (appData.debugMode) {
10423 fprintf(debugFP, "Load Game\n");
10425 DisplayBothClocks();
10428 /* [HGM] server: flag to write setup moves in broadcast file as one */
10429 loadFlag = appData.suppressLoadMoves;
10431 while (cm == Comment) {
10433 if (appData.debugMode)
10434 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10436 AppendComment(currentMove, p, FALSE);
10437 yyboardindex = forwardMostMove;
10438 cm = (ChessMove) yylex();
10441 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
10442 cm == WhiteWins || cm == BlackWins ||
10443 cm == GameIsDrawn || cm == GameUnfinished) {
10444 DisplayMessage("", _("No moves in game"));
10445 if (cmailMsgLoaded) {
10446 if (appData.debugMode)
10447 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10451 DrawPosition(FALSE, boards[currentMove]);
10452 DisplayBothClocks();
10453 gameMode = EditGame;
10460 // [HGM] PV info: routine tests if comment empty
10461 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10462 DisplayComment(currentMove - 1, commentList[currentMove]);
10464 if (!matchMode && appData.timeDelay != 0)
10465 DrawPosition(FALSE, boards[currentMove]);
10467 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10468 programStats.ok_to_send = 1;
10471 /* if the first token after the PGN tags is a move
10472 * and not move number 1, retrieve it from the parser
10474 if (cm != MoveNumberOne)
10475 LoadGameOneMove(cm);
10477 /* load the remaining moves from the file */
10478 while (LoadGameOneMove(EndOfFile)) {
10479 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10480 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10483 /* rewind to the start of the game */
10484 currentMove = backwardMostMove;
10486 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10488 if (oldGameMode == AnalyzeFile ||
10489 oldGameMode == AnalyzeMode) {
10490 AnalyzeFileEvent();
10493 if (matchMode || appData.timeDelay == 0) {
10495 gameMode = EditGame;
10497 } else if (appData.timeDelay > 0) {
10498 AutoPlayGameLoop();
10501 if (appData.debugMode)
10502 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10504 loadFlag = 0; /* [HGM] true game starts */
10508 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10510 ReloadPosition(offset)
10513 int positionNumber = lastLoadPositionNumber + offset;
10514 if (lastLoadPositionFP == NULL) {
10515 DisplayError(_("No position has been loaded yet"), 0);
10518 if (positionNumber <= 0) {
10519 DisplayError(_("Can't back up any further"), 0);
10522 return LoadPosition(lastLoadPositionFP, positionNumber,
10523 lastLoadPositionTitle);
10526 /* Load the nth position from the given file */
10528 LoadPositionFromFile(filename, n, title)
10536 if (strcmp(filename, "-") == 0) {
10537 return LoadPosition(stdin, n, "stdin");
10539 f = fopen(filename, "rb");
10541 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10542 DisplayError(buf, errno);
10545 return LoadPosition(f, n, title);
10550 /* Load the nth position from the given open file, and close it */
10552 LoadPosition(f, positionNumber, title)
10554 int positionNumber;
10557 char *p, line[MSG_SIZ];
10558 Board initial_position;
10559 int i, j, fenMode, pn;
10561 if (gameMode == Training )
10562 SetTrainingModeOff();
10564 if (gameMode != BeginningOfGame) {
10565 Reset(FALSE, TRUE);
10567 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10568 fclose(lastLoadPositionFP);
10570 if (positionNumber == 0) positionNumber = 1;
10571 lastLoadPositionFP = f;
10572 lastLoadPositionNumber = positionNumber;
10573 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
10574 if (first.pr == NoProc) {
10575 StartChessProgram(&first);
10576 InitChessProgram(&first, FALSE);
10578 pn = positionNumber;
10579 if (positionNumber < 0) {
10580 /* Negative position number means to seek to that byte offset */
10581 if (fseek(f, -positionNumber, 0) == -1) {
10582 DisplayError(_("Can't seek on position file"), 0);
10587 if (fseek(f, 0, 0) == -1) {
10588 if (f == lastLoadPositionFP ?
10589 positionNumber == lastLoadPositionNumber + 1 :
10590 positionNumber == 1) {
10593 DisplayError(_("Can't seek on position file"), 0);
10598 /* See if this file is FEN or old-style xboard */
10599 if (fgets(line, MSG_SIZ, f) == NULL) {
10600 DisplayError(_("Position not found in file"), 0);
10603 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10604 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10607 if (fenMode || line[0] == '#') pn--;
10609 /* skip positions before number pn */
10610 if (fgets(line, MSG_SIZ, f) == NULL) {
10612 DisplayError(_("Position not found in file"), 0);
10615 if (fenMode || line[0] == '#') pn--;
10620 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10621 DisplayError(_("Bad FEN position in file"), 0);
10625 (void) fgets(line, MSG_SIZ, f);
10626 (void) fgets(line, MSG_SIZ, f);
10628 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10629 (void) fgets(line, MSG_SIZ, f);
10630 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10633 initial_position[i][j++] = CharToPiece(*p);
10637 blackPlaysFirst = FALSE;
10639 (void) fgets(line, MSG_SIZ, f);
10640 if (strncmp(line, "black", strlen("black"))==0)
10641 blackPlaysFirst = TRUE;
10644 startedFromSetupPosition = TRUE;
10646 SendToProgram("force\n", &first);
10647 CopyBoard(boards[0], initial_position);
10648 if (blackPlaysFirst) {
10649 currentMove = forwardMostMove = backwardMostMove = 1;
10650 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10651 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10652 CopyBoard(boards[1], initial_position);
10653 DisplayMessage("", _("Black to play"));
10655 currentMove = forwardMostMove = backwardMostMove = 0;
10656 DisplayMessage("", _("White to play"));
10658 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10659 SendBoard(&first, forwardMostMove);
10660 if (appData.debugMode) {
10662 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10663 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10664 fprintf(debugFP, "Load Position\n");
10667 if (positionNumber > 1) {
10668 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
10669 DisplayTitle(line);
10671 DisplayTitle(title);
10673 gameMode = EditGame;
10676 timeRemaining[0][1] = whiteTimeRemaining;
10677 timeRemaining[1][1] = blackTimeRemaining;
10678 DrawPosition(FALSE, boards[currentMove]);
10685 CopyPlayerNameIntoFileName(dest, src)
10688 while (*src != NULLCHAR && *src != ',') {
10693 *(*dest)++ = *src++;
10698 char *DefaultFileName(ext)
10701 static char def[MSG_SIZ];
10704 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10706 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10708 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10710 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
10717 /* Save the current game to the given file */
10719 SaveGameToFile(filename, append)
10726 if (strcmp(filename, "-") == 0) {
10727 return SaveGame(stdout, 0, NULL);
10729 f = fopen(filename, append ? "a" : "w");
10731 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10732 DisplayError(buf, errno);
10735 return SaveGame(f, 0, NULL);
10744 static char buf[MSG_SIZ];
10747 p = strchr(str, ' ');
10748 if (p == NULL) return str;
10749 strncpy(buf, str, p - str);
10750 buf[p - str] = NULLCHAR;
10754 #define PGN_MAX_LINE 75
10756 #define PGN_SIDE_WHITE 0
10757 #define PGN_SIDE_BLACK 1
10760 static int FindFirstMoveOutOfBook( int side )
10764 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
10765 int index = backwardMostMove;
10766 int has_book_hit = 0;
10768 if( (index % 2) != side ) {
10772 while( index < forwardMostMove ) {
10773 /* Check to see if engine is in book */
10774 int depth = pvInfoList[index].depth;
10775 int score = pvInfoList[index].score;
10781 else if( score == 0 && depth == 63 ) {
10782 in_book = 1; /* Zappa */
10784 else if( score == 2 && depth == 99 ) {
10785 in_book = 1; /* Abrok */
10788 has_book_hit += in_book;
10804 void GetOutOfBookInfo( char * buf )
10808 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
10810 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
10811 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
10815 if( oob[0] >= 0 || oob[1] >= 0 ) {
10816 for( i=0; i<2; i++ ) {
10820 if( i > 0 && oob[0] >= 0 ) {
10821 strcat( buf, " " );
10824 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
10825 sprintf( buf+strlen(buf), "%s%.2f",
10826 pvInfoList[idx].score >= 0 ? "+" : "",
10827 pvInfoList[idx].score / 100.0 );
10833 /* Save game in PGN style and close the file */
10838 int i, offset, linelen, newblock;
10842 int movelen, numlen, blank;
10843 char move_buffer[100]; /* [AS] Buffer for move+PV info */
10845 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
10847 tm = time((time_t *) NULL);
10849 PrintPGNTags(f, &gameInfo);
10851 if (backwardMostMove > 0 || startedFromSetupPosition) {
10852 char *fen = PositionToFEN(backwardMostMove, NULL);
10853 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
10854 fprintf(f, "\n{--------------\n");
10855 PrintPosition(f, backwardMostMove);
10856 fprintf(f, "--------------}\n");
10860 /* [AS] Out of book annotation */
10861 if( appData.saveOutOfBookInfo ) {
10864 GetOutOfBookInfo( buf );
10866 if( buf[0] != '\0' ) {
10867 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
10874 i = backwardMostMove;
10878 while (i < forwardMostMove) {
10879 /* Print comments preceding this move */
10880 if (commentList[i] != NULL) {
10881 if (linelen > 0) fprintf(f, "\n");
10882 fprintf(f, "%s", commentList[i]);
10887 /* Format move number */
10889 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
10892 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
10894 numtext[0] = NULLCHAR;
10896 numlen = strlen(numtext);
10899 /* Print move number */
10900 blank = linelen > 0 && numlen > 0;
10901 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
10910 fprintf(f, "%s", numtext);
10914 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
10915 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
10918 blank = linelen > 0 && movelen > 0;
10919 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
10928 fprintf(f, "%s", move_buffer);
10929 linelen += movelen;
10931 /* [AS] Add PV info if present */
10932 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
10933 /* [HGM] add time */
10934 char buf[MSG_SIZ]; int seconds;
10936 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
10942 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
10945 seconds = (seconds + 4)/10; // round to full seconds
10947 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
10949 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
10952 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
10953 pvInfoList[i].score >= 0 ? "+" : "",
10954 pvInfoList[i].score / 100.0,
10955 pvInfoList[i].depth,
10958 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
10960 /* Print score/depth */
10961 blank = linelen > 0 && movelen > 0;
10962 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
10971 fprintf(f, "%s", move_buffer);
10972 linelen += movelen;
10978 /* Start a new line */
10979 if (linelen > 0) fprintf(f, "\n");
10981 /* Print comments after last move */
10982 if (commentList[i] != NULL) {
10983 fprintf(f, "%s\n", commentList[i]);
10987 if (gameInfo.resultDetails != NULL &&
10988 gameInfo.resultDetails[0] != NULLCHAR) {
10989 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
10990 PGNResult(gameInfo.result));
10992 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
10996 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11000 /* Save game in old style and close the file */
11002 SaveGameOldStyle(f)
11008 tm = time((time_t *) NULL);
11010 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
11013 if (backwardMostMove > 0 || startedFromSetupPosition) {
11014 fprintf(f, "\n[--------------\n");
11015 PrintPosition(f, backwardMostMove);
11016 fprintf(f, "--------------]\n");
11021 i = backwardMostMove;
11022 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11024 while (i < forwardMostMove) {
11025 if (commentList[i] != NULL) {
11026 fprintf(f, "[%s]\n", commentList[i]);
11029 if ((i % 2) == 1) {
11030 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
11033 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
11035 if (commentList[i] != NULL) {
11039 if (i >= forwardMostMove) {
11043 fprintf(f, "%s\n", parseList[i]);
11048 if (commentList[i] != NULL) {
11049 fprintf(f, "[%s]\n", commentList[i]);
11052 /* This isn't really the old style, but it's close enough */
11053 if (gameInfo.resultDetails != NULL &&
11054 gameInfo.resultDetails[0] != NULLCHAR) {
11055 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
11056 gameInfo.resultDetails);
11058 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11065 /* Save the current game to open file f and close the file */
11067 SaveGame(f, dummy, dummy2)
11072 if (gameMode == EditPosition) EditPositionDone(TRUE);
11073 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11074 if (appData.oldSaveStyle)
11075 return SaveGameOldStyle(f);
11077 return SaveGamePGN(f);
11080 /* Save the current position to the given file */
11082 SavePositionToFile(filename)
11088 if (strcmp(filename, "-") == 0) {
11089 return SavePosition(stdout, 0, NULL);
11091 f = fopen(filename, "a");
11093 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11094 DisplayError(buf, errno);
11097 SavePosition(f, 0, NULL);
11103 /* Save the current position to the given open file and close the file */
11105 SavePosition(f, dummy, dummy2)
11113 if (gameMode == EditPosition) EditPositionDone(TRUE);
11114 if (appData.oldSaveStyle) {
11115 tm = time((time_t *) NULL);
11117 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11119 fprintf(f, "[--------------\n");
11120 PrintPosition(f, currentMove);
11121 fprintf(f, "--------------]\n");
11123 fen = PositionToFEN(currentMove, NULL);
11124 fprintf(f, "%s\n", fen);
11132 ReloadCmailMsgEvent(unregister)
11136 static char *inFilename = NULL;
11137 static char *outFilename;
11139 struct stat inbuf, outbuf;
11142 /* Any registered moves are unregistered if unregister is set, */
11143 /* i.e. invoked by the signal handler */
11145 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11146 cmailMoveRegistered[i] = FALSE;
11147 if (cmailCommentList[i] != NULL) {
11148 free(cmailCommentList[i]);
11149 cmailCommentList[i] = NULL;
11152 nCmailMovesRegistered = 0;
11155 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11156 cmailResult[i] = CMAIL_NOT_RESULT;
11160 if (inFilename == NULL) {
11161 /* Because the filenames are static they only get malloced once */
11162 /* and they never get freed */
11163 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11164 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11166 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11167 sprintf(outFilename, "%s.out", appData.cmailGameName);
11170 status = stat(outFilename, &outbuf);
11172 cmailMailedMove = FALSE;
11174 status = stat(inFilename, &inbuf);
11175 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11178 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11179 counts the games, notes how each one terminated, etc.
11181 It would be nice to remove this kludge and instead gather all
11182 the information while building the game list. (And to keep it
11183 in the game list nodes instead of having a bunch of fixed-size
11184 parallel arrays.) Note this will require getting each game's
11185 termination from the PGN tags, as the game list builder does
11186 not process the game moves. --mann
11188 cmailMsgLoaded = TRUE;
11189 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11191 /* Load first game in the file or popup game menu */
11192 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11194 #endif /* !WIN32 */
11202 char string[MSG_SIZ];
11204 if ( cmailMailedMove
11205 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11206 return TRUE; /* Allow free viewing */
11209 /* Unregister move to ensure that we don't leave RegisterMove */
11210 /* with the move registered when the conditions for registering no */
11212 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11213 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11214 nCmailMovesRegistered --;
11216 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11218 free(cmailCommentList[lastLoadGameNumber - 1]);
11219 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11223 if (cmailOldMove == -1) {
11224 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11228 if (currentMove > cmailOldMove + 1) {
11229 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11233 if (currentMove < cmailOldMove) {
11234 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11238 if (forwardMostMove > currentMove) {
11239 /* Silently truncate extra moves */
11243 if ( (currentMove == cmailOldMove + 1)
11244 || ( (currentMove == cmailOldMove)
11245 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11246 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11247 if (gameInfo.result != GameUnfinished) {
11248 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11251 if (commentList[currentMove] != NULL) {
11252 cmailCommentList[lastLoadGameNumber - 1]
11253 = StrSave(commentList[currentMove]);
11255 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
11257 if (appData.debugMode)
11258 fprintf(debugFP, "Saving %s for game %d\n",
11259 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11261 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11263 f = fopen(string, "w");
11264 if (appData.oldSaveStyle) {
11265 SaveGameOldStyle(f); /* also closes the file */
11267 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
11268 f = fopen(string, "w");
11269 SavePosition(f, 0, NULL); /* also closes the file */
11271 fprintf(f, "{--------------\n");
11272 PrintPosition(f, currentMove);
11273 fprintf(f, "--------------}\n\n");
11275 SaveGame(f, 0, NULL); /* also closes the file*/
11278 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11279 nCmailMovesRegistered ++;
11280 } else if (nCmailGames == 1) {
11281 DisplayError(_("You have not made a move yet"), 0);
11292 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11293 FILE *commandOutput;
11294 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11295 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11301 if (! cmailMsgLoaded) {
11302 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11306 if (nCmailGames == nCmailResults) {
11307 DisplayError(_("No unfinished games"), 0);
11311 #if CMAIL_PROHIBIT_REMAIL
11312 if (cmailMailedMove) {
11313 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);
11314 DisplayError(msg, 0);
11319 if (! (cmailMailedMove || RegisterMove())) return;
11321 if ( cmailMailedMove
11322 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11323 snprintf(string, MSG_SIZ, partCommandString,
11324 appData.debugMode ? " -v" : "", appData.cmailGameName);
11325 commandOutput = popen(string, "r");
11327 if (commandOutput == NULL) {
11328 DisplayError(_("Failed to invoke cmail"), 0);
11330 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11331 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11333 if (nBuffers > 1) {
11334 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11335 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11336 nBytes = MSG_SIZ - 1;
11338 (void) memcpy(msg, buffer, nBytes);
11340 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11342 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11343 cmailMailedMove = TRUE; /* Prevent >1 moves */
11346 for (i = 0; i < nCmailGames; i ++) {
11347 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11352 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11354 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
11356 appData.cmailGameName,
11358 LoadGameFromFile(buffer, 1, buffer, FALSE);
11359 cmailMsgLoaded = FALSE;
11363 DisplayInformation(msg);
11364 pclose(commandOutput);
11367 if ((*cmailMsg) != '\0') {
11368 DisplayInformation(cmailMsg);
11373 #endif /* !WIN32 */
11382 int prependComma = 0;
11384 char string[MSG_SIZ]; /* Space for game-list */
11387 if (!cmailMsgLoaded) return "";
11389 if (cmailMailedMove) {
11390 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
11392 /* Create a list of games left */
11393 snprintf(string, MSG_SIZ, "[");
11394 for (i = 0; i < nCmailGames; i ++) {
11395 if (! ( cmailMoveRegistered[i]
11396 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11397 if (prependComma) {
11398 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
11400 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
11404 strcat(string, number);
11407 strcat(string, "]");
11409 if (nCmailMovesRegistered + nCmailResults == 0) {
11410 switch (nCmailGames) {
11412 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
11416 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
11420 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
11425 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11427 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
11432 if (nCmailResults == nCmailGames) {
11433 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
11435 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
11440 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
11452 if (gameMode == Training)
11453 SetTrainingModeOff();
11456 cmailMsgLoaded = FALSE;
11457 if (appData.icsActive) {
11458 SendToICS(ics_prefix);
11459 SendToICS("refresh\n");
11469 /* Give up on clean exit */
11473 /* Keep trying for clean exit */
11477 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11479 if (telnetISR != NULL) {
11480 RemoveInputSource(telnetISR);
11482 if (icsPR != NoProc) {
11483 DestroyChildProcess(icsPR, TRUE);
11486 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11487 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11489 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11490 /* make sure this other one finishes before killing it! */
11491 if(endingGame) { int count = 0;
11492 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11493 while(endingGame && count++ < 10) DoSleep(1);
11494 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11497 /* Kill off chess programs */
11498 if (first.pr != NoProc) {
11501 DoSleep( appData.delayBeforeQuit );
11502 SendToProgram("quit\n", &first);
11503 DoSleep( appData.delayAfterQuit );
11504 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11506 if (second.pr != NoProc) {
11507 DoSleep( appData.delayBeforeQuit );
11508 SendToProgram("quit\n", &second);
11509 DoSleep( appData.delayAfterQuit );
11510 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11512 if (first.isr != NULL) {
11513 RemoveInputSource(first.isr);
11515 if (second.isr != NULL) {
11516 RemoveInputSource(second.isr);
11519 ShutDownFrontEnd();
11526 if (appData.debugMode)
11527 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11531 if (gameMode == MachinePlaysWhite ||
11532 gameMode == MachinePlaysBlack) {
11535 DisplayBothClocks();
11537 if (gameMode == PlayFromGameFile) {
11538 if (appData.timeDelay >= 0)
11539 AutoPlayGameLoop();
11540 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11541 Reset(FALSE, TRUE);
11542 SendToICS(ics_prefix);
11543 SendToICS("refresh\n");
11544 } else if (currentMove < forwardMostMove) {
11545 ForwardInner(forwardMostMove);
11547 pauseExamInvalid = FALSE;
11549 switch (gameMode) {
11553 pauseExamForwardMostMove = forwardMostMove;
11554 pauseExamInvalid = FALSE;
11557 case IcsPlayingWhite:
11558 case IcsPlayingBlack:
11562 case PlayFromGameFile:
11563 (void) StopLoadGameTimer();
11567 case BeginningOfGame:
11568 if (appData.icsActive) return;
11569 /* else fall through */
11570 case MachinePlaysWhite:
11571 case MachinePlaysBlack:
11572 case TwoMachinesPlay:
11573 if (forwardMostMove == 0)
11574 return; /* don't pause if no one has moved */
11575 if ((gameMode == MachinePlaysWhite &&
11576 !WhiteOnMove(forwardMostMove)) ||
11577 (gameMode == MachinePlaysBlack &&
11578 WhiteOnMove(forwardMostMove))) {
11591 char title[MSG_SIZ];
11593 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11594 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
11596 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11597 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11598 parseList[currentMove - 1]);
11601 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11608 char *tags = PGNTags(&gameInfo);
11609 EditTagsPopUp(tags);
11616 if (appData.noChessProgram || gameMode == AnalyzeMode)
11619 if (gameMode != AnalyzeFile) {
11620 if (!appData.icsEngineAnalyze) {
11622 if (gameMode != EditGame) return;
11624 ResurrectChessProgram();
11625 SendToProgram("analyze\n", &first);
11626 first.analyzing = TRUE;
11627 /*first.maybeThinking = TRUE;*/
11628 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11629 EngineOutputPopUp();
11631 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11636 StartAnalysisClock();
11637 GetTimeMark(&lastNodeCountTime);
11644 if (appData.noChessProgram || gameMode == AnalyzeFile)
11647 if (gameMode != AnalyzeMode) {
11649 if (gameMode != EditGame) return;
11650 ResurrectChessProgram();
11651 SendToProgram("analyze\n", &first);
11652 first.analyzing = TRUE;
11653 /*first.maybeThinking = TRUE;*/
11654 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11655 EngineOutputPopUp();
11657 gameMode = AnalyzeFile;
11662 StartAnalysisClock();
11663 GetTimeMark(&lastNodeCountTime);
11668 MachineWhiteEvent()
11671 char *bookHit = NULL;
11673 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11677 if (gameMode == PlayFromGameFile ||
11678 gameMode == TwoMachinesPlay ||
11679 gameMode == Training ||
11680 gameMode == AnalyzeMode ||
11681 gameMode == EndOfGame)
11684 if (gameMode == EditPosition)
11685 EditPositionDone(TRUE);
11687 if (!WhiteOnMove(currentMove)) {
11688 DisplayError(_("It is not White's turn"), 0);
11692 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11695 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11696 gameMode == AnalyzeFile)
11699 ResurrectChessProgram(); /* in case it isn't running */
11700 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11701 gameMode = MachinePlaysWhite;
11704 gameMode = MachinePlaysWhite;
11708 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11710 if (first.sendName) {
11711 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
11712 SendToProgram(buf, &first);
11714 if (first.sendTime) {
11715 if (first.useColors) {
11716 SendToProgram("black\n", &first); /*gnu kludge*/
11718 SendTimeRemaining(&first, TRUE);
11720 if (first.useColors) {
11721 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
11723 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11724 SetMachineThinkingEnables();
11725 first.maybeThinking = TRUE;
11729 if (appData.autoFlipView && !flipView) {
11730 flipView = !flipView;
11731 DrawPosition(FALSE, NULL);
11732 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11735 if(bookHit) { // [HGM] book: simulate book reply
11736 static char bookMove[MSG_SIZ]; // a bit generous?
11738 programStats.nodes = programStats.depth = programStats.time =
11739 programStats.score = programStats.got_only_move = 0;
11740 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11742 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
11743 strcat(bookMove, bookHit);
11744 HandleMachineMove(bookMove, &first);
11749 MachineBlackEvent()
11752 char *bookHit = NULL;
11754 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
11758 if (gameMode == PlayFromGameFile ||
11759 gameMode == TwoMachinesPlay ||
11760 gameMode == Training ||
11761 gameMode == AnalyzeMode ||
11762 gameMode == EndOfGame)
11765 if (gameMode == EditPosition)
11766 EditPositionDone(TRUE);
11768 if (WhiteOnMove(currentMove)) {
11769 DisplayError(_("It is not Black's turn"), 0);
11773 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11776 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11777 gameMode == AnalyzeFile)
11780 ResurrectChessProgram(); /* in case it isn't running */
11781 gameMode = MachinePlaysBlack;
11785 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11787 if (first.sendName) {
11788 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
11789 SendToProgram(buf, &first);
11791 if (first.sendTime) {
11792 if (first.useColors) {
11793 SendToProgram("white\n", &first); /*gnu kludge*/
11795 SendTimeRemaining(&first, FALSE);
11797 if (first.useColors) {
11798 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
11800 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11801 SetMachineThinkingEnables();
11802 first.maybeThinking = TRUE;
11805 if (appData.autoFlipView && flipView) {
11806 flipView = !flipView;
11807 DrawPosition(FALSE, NULL);
11808 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11810 if(bookHit) { // [HGM] book: simulate book reply
11811 static char bookMove[MSG_SIZ]; // a bit generous?
11813 programStats.nodes = programStats.depth = programStats.time =
11814 programStats.score = programStats.got_only_move = 0;
11815 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11817 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
11818 strcat(bookMove, bookHit);
11819 HandleMachineMove(bookMove, &first);
11825 DisplayTwoMachinesTitle()
11828 if (appData.matchGames > 0) {
11829 if (first.twoMachinesColor[0] == 'w') {
11830 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
11831 gameInfo.white, gameInfo.black,
11832 first.matchWins, second.matchWins,
11833 matchGame - 1 - (first.matchWins + second.matchWins));
11835 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
11836 gameInfo.white, gameInfo.black,
11837 second.matchWins, first.matchWins,
11838 matchGame - 1 - (first.matchWins + second.matchWins));
11841 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11847 TwoMachinesEvent P((void))
11851 ChessProgramState *onmove;
11852 char *bookHit = NULL;
11854 if (appData.noChessProgram) return;
11856 switch (gameMode) {
11857 case TwoMachinesPlay:
11859 case MachinePlaysWhite:
11860 case MachinePlaysBlack:
11861 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
11862 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
11866 case BeginningOfGame:
11867 case PlayFromGameFile:
11870 if (gameMode != EditGame) return;
11873 EditPositionDone(TRUE);
11884 // forwardMostMove = currentMove;
11885 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
11886 ResurrectChessProgram(); /* in case first program isn't running */
11888 if (second.pr == NULL) {
11889 StartChessProgram(&second);
11890 if (second.protocolVersion == 1) {
11891 TwoMachinesEventIfReady();
11893 /* kludge: allow timeout for initial "feature" command */
11895 DisplayMessage("", _("Starting second chess program"));
11896 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
11900 DisplayMessage("", "");
11901 InitChessProgram(&second, FALSE);
11902 SendToProgram("force\n", &second);
11903 if (startedFromSetupPosition) {
11904 SendBoard(&second, backwardMostMove);
11905 if (appData.debugMode) {
11906 fprintf(debugFP, "Two Machines\n");
11909 for (i = backwardMostMove; i < forwardMostMove; i++) {
11910 SendMoveToProgram(i, &second);
11913 gameMode = TwoMachinesPlay;
11917 DisplayTwoMachinesTitle();
11919 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
11925 SendToProgram(first.computerString, &first);
11926 if (first.sendName) {
11927 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
11928 SendToProgram(buf, &first);
11930 SendToProgram(second.computerString, &second);
11931 if (second.sendName) {
11932 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
11933 SendToProgram(buf, &second);
11937 if (!first.sendTime || !second.sendTime) {
11938 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
11939 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
11941 if (onmove->sendTime) {
11942 if (onmove->useColors) {
11943 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
11945 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
11947 if (onmove->useColors) {
11948 SendToProgram(onmove->twoMachinesColor, onmove);
11950 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
11951 // SendToProgram("go\n", onmove);
11952 onmove->maybeThinking = TRUE;
11953 SetMachineThinkingEnables();
11957 if(bookHit) { // [HGM] book: simulate book reply
11958 static char bookMove[MSG_SIZ]; // a bit generous?
11960 programStats.nodes = programStats.depth = programStats.time =
11961 programStats.score = programStats.got_only_move = 0;
11962 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11964 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
11965 strcat(bookMove, bookHit);
11966 savedMessage = bookMove; // args for deferred call
11967 savedState = onmove;
11968 ScheduleDelayedEvent(DeferredBookMove, 1);
11975 if (gameMode == Training) {
11976 SetTrainingModeOff();
11977 gameMode = PlayFromGameFile;
11978 DisplayMessage("", _("Training mode off"));
11980 gameMode = Training;
11981 animateTraining = appData.animate;
11983 /* make sure we are not already at the end of the game */
11984 if (currentMove < forwardMostMove) {
11985 SetTrainingModeOn();
11986 DisplayMessage("", _("Training mode on"));
11988 gameMode = PlayFromGameFile;
11989 DisplayError(_("Already at end of game"), 0);
11998 if (!appData.icsActive) return;
11999 switch (gameMode) {
12000 case IcsPlayingWhite:
12001 case IcsPlayingBlack:
12004 case BeginningOfGame:
12012 EditPositionDone(TRUE);
12025 gameMode = IcsIdle;
12036 switch (gameMode) {
12038 SetTrainingModeOff();
12040 case MachinePlaysWhite:
12041 case MachinePlaysBlack:
12042 case BeginningOfGame:
12043 SendToProgram("force\n", &first);
12044 SetUserThinkingEnables();
12046 case PlayFromGameFile:
12047 (void) StopLoadGameTimer();
12048 if (gameFileFP != NULL) {
12053 EditPositionDone(TRUE);
12058 SendToProgram("force\n", &first);
12060 case TwoMachinesPlay:
12061 GameEnds(EndOfFile, NULL, GE_PLAYER);
12062 ResurrectChessProgram();
12063 SetUserThinkingEnables();
12066 ResurrectChessProgram();
12068 case IcsPlayingBlack:
12069 case IcsPlayingWhite:
12070 DisplayError(_("Warning: You are still playing a game"), 0);
12073 DisplayError(_("Warning: You are still observing a game"), 0);
12076 DisplayError(_("Warning: You are still examining a game"), 0);
12087 first.offeredDraw = second.offeredDraw = 0;
12089 if (gameMode == PlayFromGameFile) {
12090 whiteTimeRemaining = timeRemaining[0][currentMove];
12091 blackTimeRemaining = timeRemaining[1][currentMove];
12095 if (gameMode == MachinePlaysWhite ||
12096 gameMode == MachinePlaysBlack ||
12097 gameMode == TwoMachinesPlay ||
12098 gameMode == EndOfGame) {
12099 i = forwardMostMove;
12100 while (i > currentMove) {
12101 SendToProgram("undo\n", &first);
12104 whiteTimeRemaining = timeRemaining[0][currentMove];
12105 blackTimeRemaining = timeRemaining[1][currentMove];
12106 DisplayBothClocks();
12107 if (whiteFlag || blackFlag) {
12108 whiteFlag = blackFlag = 0;
12113 gameMode = EditGame;
12120 EditPositionEvent()
12122 if (gameMode == EditPosition) {
12128 if (gameMode != EditGame) return;
12130 gameMode = EditPosition;
12133 if (currentMove > 0)
12134 CopyBoard(boards[0], boards[currentMove]);
12136 blackPlaysFirst = !WhiteOnMove(currentMove);
12138 currentMove = forwardMostMove = backwardMostMove = 0;
12139 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12146 /* [DM] icsEngineAnalyze - possible call from other functions */
12147 if (appData.icsEngineAnalyze) {
12148 appData.icsEngineAnalyze = FALSE;
12150 DisplayMessage("",_("Close ICS engine analyze..."));
12152 if (first.analysisSupport && first.analyzing) {
12153 SendToProgram("exit\n", &first);
12154 first.analyzing = FALSE;
12156 thinkOutput[0] = NULLCHAR;
12160 EditPositionDone(Boolean fakeRights)
12162 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12164 startedFromSetupPosition = TRUE;
12165 InitChessProgram(&first, FALSE);
12166 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12167 boards[0][EP_STATUS] = EP_NONE;
12168 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12169 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12170 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12171 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12172 } else boards[0][CASTLING][2] = NoRights;
12173 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12174 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12175 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12176 } else boards[0][CASTLING][5] = NoRights;
12178 SendToProgram("force\n", &first);
12179 if (blackPlaysFirst) {
12180 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12181 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12182 currentMove = forwardMostMove = backwardMostMove = 1;
12183 CopyBoard(boards[1], boards[0]);
12185 currentMove = forwardMostMove = backwardMostMove = 0;
12187 SendBoard(&first, forwardMostMove);
12188 if (appData.debugMode) {
12189 fprintf(debugFP, "EditPosDone\n");
12192 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12193 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12194 gameMode = EditGame;
12196 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12197 ClearHighlights(); /* [AS] */
12200 /* Pause for `ms' milliseconds */
12201 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12211 } while (SubtractTimeMarks(&m2, &m1) < ms);
12214 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12216 SendMultiLineToICS(buf)
12219 char temp[MSG_SIZ+1], *p;
12226 strncpy(temp, buf, len);
12231 if (*p == '\n' || *p == '\r')
12236 strcat(temp, "\n");
12238 SendToPlayer(temp, strlen(temp));
12242 SetWhiteToPlayEvent()
12244 if (gameMode == EditPosition) {
12245 blackPlaysFirst = FALSE;
12246 DisplayBothClocks(); /* works because currentMove is 0 */
12247 } else if (gameMode == IcsExamining) {
12248 SendToICS(ics_prefix);
12249 SendToICS("tomove white\n");
12254 SetBlackToPlayEvent()
12256 if (gameMode == EditPosition) {
12257 blackPlaysFirst = TRUE;
12258 currentMove = 1; /* kludge */
12259 DisplayBothClocks();
12261 } else if (gameMode == IcsExamining) {
12262 SendToICS(ics_prefix);
12263 SendToICS("tomove black\n");
12268 EditPositionMenuEvent(selection, x, y)
12269 ChessSquare selection;
12273 ChessSquare piece = boards[0][y][x];
12275 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12277 switch (selection) {
12279 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12280 SendToICS(ics_prefix);
12281 SendToICS("bsetup clear\n");
12282 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12283 SendToICS(ics_prefix);
12284 SendToICS("clearboard\n");
12286 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12287 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12288 for (y = 0; y < BOARD_HEIGHT; y++) {
12289 if (gameMode == IcsExamining) {
12290 if (boards[currentMove][y][x] != EmptySquare) {
12291 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
12296 boards[0][y][x] = p;
12301 if (gameMode == EditPosition) {
12302 DrawPosition(FALSE, boards[0]);
12307 SetWhiteToPlayEvent();
12311 SetBlackToPlayEvent();
12315 if (gameMode == IcsExamining) {
12316 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12317 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12320 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12321 if(x == BOARD_LEFT-2) {
12322 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12323 boards[0][y][1] = 0;
12325 if(x == BOARD_RGHT+1) {
12326 if(y >= gameInfo.holdingsSize) break;
12327 boards[0][y][BOARD_WIDTH-2] = 0;
12330 boards[0][y][x] = EmptySquare;
12331 DrawPosition(FALSE, boards[0]);
12336 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12337 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12338 selection = (ChessSquare) (PROMOTED piece);
12339 } else if(piece == EmptySquare) selection = WhiteSilver;
12340 else selection = (ChessSquare)((int)piece - 1);
12344 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12345 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12346 selection = (ChessSquare) (DEMOTED piece);
12347 } else if(piece == EmptySquare) selection = BlackSilver;
12348 else selection = (ChessSquare)((int)piece + 1);
12353 if(gameInfo.variant == VariantShatranj ||
12354 gameInfo.variant == VariantXiangqi ||
12355 gameInfo.variant == VariantCourier ||
12356 gameInfo.variant == VariantMakruk )
12357 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12362 if(gameInfo.variant == VariantXiangqi)
12363 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12364 if(gameInfo.variant == VariantKnightmate)
12365 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12368 if (gameMode == IcsExamining) {
12369 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12370 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
12371 PieceToChar(selection), AAA + x, ONE + y);
12374 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12376 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12377 n = PieceToNumber(selection - BlackPawn);
12378 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12379 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12380 boards[0][BOARD_HEIGHT-1-n][1]++;
12382 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12383 n = PieceToNumber(selection);
12384 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12385 boards[0][n][BOARD_WIDTH-1] = selection;
12386 boards[0][n][BOARD_WIDTH-2]++;
12389 boards[0][y][x] = selection;
12390 DrawPosition(TRUE, boards[0]);
12398 DropMenuEvent(selection, x, y)
12399 ChessSquare selection;
12402 ChessMove moveType;
12404 switch (gameMode) {
12405 case IcsPlayingWhite:
12406 case MachinePlaysBlack:
12407 if (!WhiteOnMove(currentMove)) {
12408 DisplayMoveError(_("It is Black's turn"));
12411 moveType = WhiteDrop;
12413 case IcsPlayingBlack:
12414 case MachinePlaysWhite:
12415 if (WhiteOnMove(currentMove)) {
12416 DisplayMoveError(_("It is White's turn"));
12419 moveType = BlackDrop;
12422 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12428 if (moveType == BlackDrop && selection < BlackPawn) {
12429 selection = (ChessSquare) ((int) selection
12430 + (int) BlackPawn - (int) WhitePawn);
12432 if (boards[currentMove][y][x] != EmptySquare) {
12433 DisplayMoveError(_("That square is occupied"));
12437 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12443 /* Accept a pending offer of any kind from opponent */
12445 if (appData.icsActive) {
12446 SendToICS(ics_prefix);
12447 SendToICS("accept\n");
12448 } else if (cmailMsgLoaded) {
12449 if (currentMove == cmailOldMove &&
12450 commentList[cmailOldMove] != NULL &&
12451 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12452 "Black offers a draw" : "White offers a draw")) {
12454 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12455 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12457 DisplayError(_("There is no pending offer on this move"), 0);
12458 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12461 /* Not used for offers from chess program */
12468 /* Decline a pending offer of any kind from opponent */
12470 if (appData.icsActive) {
12471 SendToICS(ics_prefix);
12472 SendToICS("decline\n");
12473 } else if (cmailMsgLoaded) {
12474 if (currentMove == cmailOldMove &&
12475 commentList[cmailOldMove] != NULL &&
12476 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12477 "Black offers a draw" : "White offers a draw")) {
12479 AppendComment(cmailOldMove, "Draw declined", TRUE);
12480 DisplayComment(cmailOldMove - 1, "Draw declined");
12483 DisplayError(_("There is no pending offer on this move"), 0);
12486 /* Not used for offers from chess program */
12493 /* Issue ICS rematch command */
12494 if (appData.icsActive) {
12495 SendToICS(ics_prefix);
12496 SendToICS("rematch\n");
12503 /* Call your opponent's flag (claim a win on time) */
12504 if (appData.icsActive) {
12505 SendToICS(ics_prefix);
12506 SendToICS("flag\n");
12508 switch (gameMode) {
12511 case MachinePlaysWhite:
12514 GameEnds(GameIsDrawn, "Both players ran out of time",
12517 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12519 DisplayError(_("Your opponent is not out of time"), 0);
12522 case MachinePlaysBlack:
12525 GameEnds(GameIsDrawn, "Both players ran out of time",
12528 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12530 DisplayError(_("Your opponent is not out of time"), 0);
12540 /* Offer draw or accept pending draw offer from opponent */
12542 if (appData.icsActive) {
12543 /* Note: tournament rules require draw offers to be
12544 made after you make your move but before you punch
12545 your clock. Currently ICS doesn't let you do that;
12546 instead, you immediately punch your clock after making
12547 a move, but you can offer a draw at any time. */
12549 SendToICS(ics_prefix);
12550 SendToICS("draw\n");
12551 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12552 } else if (cmailMsgLoaded) {
12553 if (currentMove == cmailOldMove &&
12554 commentList[cmailOldMove] != NULL &&
12555 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12556 "Black offers a draw" : "White offers a draw")) {
12557 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12558 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12559 } else if (currentMove == cmailOldMove + 1) {
12560 char *offer = WhiteOnMove(cmailOldMove) ?
12561 "White offers a draw" : "Black offers a draw";
12562 AppendComment(currentMove, offer, TRUE);
12563 DisplayComment(currentMove - 1, offer);
12564 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12566 DisplayError(_("You must make your move before offering a draw"), 0);
12567 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12569 } else if (first.offeredDraw) {
12570 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12572 if (first.sendDrawOffers) {
12573 SendToProgram("draw\n", &first);
12574 userOfferedDraw = TRUE;
12582 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12584 if (appData.icsActive) {
12585 SendToICS(ics_prefix);
12586 SendToICS("adjourn\n");
12588 /* Currently GNU Chess doesn't offer or accept Adjourns */
12596 /* Offer Abort or accept pending Abort offer from opponent */
12598 if (appData.icsActive) {
12599 SendToICS(ics_prefix);
12600 SendToICS("abort\n");
12602 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12609 /* Resign. You can do this even if it's not your turn. */
12611 if (appData.icsActive) {
12612 SendToICS(ics_prefix);
12613 SendToICS("resign\n");
12615 switch (gameMode) {
12616 case MachinePlaysWhite:
12617 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12619 case MachinePlaysBlack:
12620 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12623 if (cmailMsgLoaded) {
12625 if (WhiteOnMove(cmailOldMove)) {
12626 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12628 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12630 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12641 StopObservingEvent()
12643 /* Stop observing current games */
12644 SendToICS(ics_prefix);
12645 SendToICS("unobserve\n");
12649 StopExaminingEvent()
12651 /* Stop observing current game */
12652 SendToICS(ics_prefix);
12653 SendToICS("unexamine\n");
12657 ForwardInner(target)
12662 if (appData.debugMode)
12663 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
12664 target, currentMove, forwardMostMove);
12666 if (gameMode == EditPosition)
12669 if (gameMode == PlayFromGameFile && !pausing)
12672 if (gameMode == IcsExamining && pausing)
12673 limit = pauseExamForwardMostMove;
12675 limit = forwardMostMove;
12677 if (target > limit) target = limit;
12679 if (target > 0 && moveList[target - 1][0]) {
12680 int fromX, fromY, toX, toY;
12681 toX = moveList[target - 1][2] - AAA;
12682 toY = moveList[target - 1][3] - ONE;
12683 if (moveList[target - 1][1] == '@') {
12684 if (appData.highlightLastMove) {
12685 SetHighlights(-1, -1, toX, toY);
12688 fromX = moveList[target - 1][0] - AAA;
12689 fromY = moveList[target - 1][1] - ONE;
12690 if (target == currentMove + 1) {
12691 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12693 if (appData.highlightLastMove) {
12694 SetHighlights(fromX, fromY, toX, toY);
12698 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12699 gameMode == Training || gameMode == PlayFromGameFile ||
12700 gameMode == AnalyzeFile) {
12701 while (currentMove < target) {
12702 SendMoveToProgram(currentMove++, &first);
12705 currentMove = target;
12708 if (gameMode == EditGame || gameMode == EndOfGame) {
12709 whiteTimeRemaining = timeRemaining[0][currentMove];
12710 blackTimeRemaining = timeRemaining[1][currentMove];
12712 DisplayBothClocks();
12713 DisplayMove(currentMove - 1);
12714 DrawPosition(FALSE, boards[currentMove]);
12715 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12716 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
12717 DisplayComment(currentMove - 1, commentList[currentMove]);
12725 if (gameMode == IcsExamining && !pausing) {
12726 SendToICS(ics_prefix);
12727 SendToICS("forward\n");
12729 ForwardInner(currentMove + 1);
12736 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12737 /* to optimze, we temporarily turn off analysis mode while we feed
12738 * the remaining moves to the engine. Otherwise we get analysis output
12741 if (first.analysisSupport) {
12742 SendToProgram("exit\nforce\n", &first);
12743 first.analyzing = FALSE;
12747 if (gameMode == IcsExamining && !pausing) {
12748 SendToICS(ics_prefix);
12749 SendToICS("forward 999999\n");
12751 ForwardInner(forwardMostMove);
12754 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12755 /* we have fed all the moves, so reactivate analysis mode */
12756 SendToProgram("analyze\n", &first);
12757 first.analyzing = TRUE;
12758 /*first.maybeThinking = TRUE;*/
12759 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12764 BackwardInner(target)
12767 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
12769 if (appData.debugMode)
12770 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
12771 target, currentMove, forwardMostMove);
12773 if (gameMode == EditPosition) return;
12774 if (currentMove <= backwardMostMove) {
12776 DrawPosition(full_redraw, boards[currentMove]);
12779 if (gameMode == PlayFromGameFile && !pausing)
12782 if (moveList[target][0]) {
12783 int fromX, fromY, toX, toY;
12784 toX = moveList[target][2] - AAA;
12785 toY = moveList[target][3] - ONE;
12786 if (moveList[target][1] == '@') {
12787 if (appData.highlightLastMove) {
12788 SetHighlights(-1, -1, toX, toY);
12791 fromX = moveList[target][0] - AAA;
12792 fromY = moveList[target][1] - ONE;
12793 if (target == currentMove - 1) {
12794 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
12796 if (appData.highlightLastMove) {
12797 SetHighlights(fromX, fromY, toX, toY);
12801 if (gameMode == EditGame || gameMode==AnalyzeMode ||
12802 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
12803 while (currentMove > target) {
12804 SendToProgram("undo\n", &first);
12808 currentMove = target;
12811 if (gameMode == EditGame || gameMode == EndOfGame) {
12812 whiteTimeRemaining = timeRemaining[0][currentMove];
12813 blackTimeRemaining = timeRemaining[1][currentMove];
12815 DisplayBothClocks();
12816 DisplayMove(currentMove - 1);
12817 DrawPosition(full_redraw, boards[currentMove]);
12818 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12819 // [HGM] PV info: routine tests if comment empty
12820 DisplayComment(currentMove - 1, commentList[currentMove]);
12826 if (gameMode == IcsExamining && !pausing) {
12827 SendToICS(ics_prefix);
12828 SendToICS("backward\n");
12830 BackwardInner(currentMove - 1);
12837 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12838 /* to optimize, we temporarily turn off analysis mode while we undo
12839 * all the moves. Otherwise we get analysis output after each undo.
12841 if (first.analysisSupport) {
12842 SendToProgram("exit\nforce\n", &first);
12843 first.analyzing = FALSE;
12847 if (gameMode == IcsExamining && !pausing) {
12848 SendToICS(ics_prefix);
12849 SendToICS("backward 999999\n");
12851 BackwardInner(backwardMostMove);
12854 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12855 /* we have fed all the moves, so reactivate analysis mode */
12856 SendToProgram("analyze\n", &first);
12857 first.analyzing = TRUE;
12858 /*first.maybeThinking = TRUE;*/
12859 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12866 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
12867 if (to >= forwardMostMove) to = forwardMostMove;
12868 if (to <= backwardMostMove) to = backwardMostMove;
12869 if (to < currentMove) {
12877 RevertEvent(Boolean annotate)
12879 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
12882 if (gameMode != IcsExamining) {
12883 DisplayError(_("You are not examining a game"), 0);
12887 DisplayError(_("You can't revert while pausing"), 0);
12890 SendToICS(ics_prefix);
12891 SendToICS("revert\n");
12897 switch (gameMode) {
12898 case MachinePlaysWhite:
12899 case MachinePlaysBlack:
12900 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12901 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12904 if (forwardMostMove < 2) return;
12905 currentMove = forwardMostMove = forwardMostMove - 2;
12906 whiteTimeRemaining = timeRemaining[0][currentMove];
12907 blackTimeRemaining = timeRemaining[1][currentMove];
12908 DisplayBothClocks();
12909 DisplayMove(currentMove - 1);
12910 ClearHighlights();/*!! could figure this out*/
12911 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
12912 SendToProgram("remove\n", &first);
12913 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
12916 case BeginningOfGame:
12920 case IcsPlayingWhite:
12921 case IcsPlayingBlack:
12922 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
12923 SendToICS(ics_prefix);
12924 SendToICS("takeback 2\n");
12926 SendToICS(ics_prefix);
12927 SendToICS("takeback 1\n");
12936 ChessProgramState *cps;
12938 switch (gameMode) {
12939 case MachinePlaysWhite:
12940 if (!WhiteOnMove(forwardMostMove)) {
12941 DisplayError(_("It is your turn"), 0);
12946 case MachinePlaysBlack:
12947 if (WhiteOnMove(forwardMostMove)) {
12948 DisplayError(_("It is your turn"), 0);
12953 case TwoMachinesPlay:
12954 if (WhiteOnMove(forwardMostMove) ==
12955 (first.twoMachinesColor[0] == 'w')) {
12961 case BeginningOfGame:
12965 SendToProgram("?\n", cps);
12969 TruncateGameEvent()
12972 if (gameMode != EditGame) return;
12979 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
12980 if (forwardMostMove > currentMove) {
12981 if (gameInfo.resultDetails != NULL) {
12982 free(gameInfo.resultDetails);
12983 gameInfo.resultDetails = NULL;
12984 gameInfo.result = GameUnfinished;
12986 forwardMostMove = currentMove;
12987 HistorySet(parseList, backwardMostMove, forwardMostMove,
12995 if (appData.noChessProgram) return;
12996 switch (gameMode) {
12997 case MachinePlaysWhite:
12998 if (WhiteOnMove(forwardMostMove)) {
12999 DisplayError(_("Wait until your turn"), 0);
13003 case BeginningOfGame:
13004 case MachinePlaysBlack:
13005 if (!WhiteOnMove(forwardMostMove)) {
13006 DisplayError(_("Wait until your turn"), 0);
13011 DisplayError(_("No hint available"), 0);
13014 SendToProgram("hint\n", &first);
13015 hintRequested = TRUE;
13021 if (appData.noChessProgram) return;
13022 switch (gameMode) {
13023 case MachinePlaysWhite:
13024 if (WhiteOnMove(forwardMostMove)) {
13025 DisplayError(_("Wait until your turn"), 0);
13029 case BeginningOfGame:
13030 case MachinePlaysBlack:
13031 if (!WhiteOnMove(forwardMostMove)) {
13032 DisplayError(_("Wait until your turn"), 0);
13037 EditPositionDone(TRUE);
13039 case TwoMachinesPlay:
13044 SendToProgram("bk\n", &first);
13045 bookOutput[0] = NULLCHAR;
13046 bookRequested = TRUE;
13052 char *tags = PGNTags(&gameInfo);
13053 TagsPopUp(tags, CmailMsg());
13057 /* end button procedures */
13060 PrintPosition(fp, move)
13066 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13067 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13068 char c = PieceToChar(boards[move][i][j]);
13069 fputc(c == 'x' ? '.' : c, fp);
13070 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
13073 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
13074 fprintf(fp, "white to play\n");
13076 fprintf(fp, "black to play\n");
13083 if (gameInfo.white != NULL) {
13084 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13090 /* Find last component of program's own name, using some heuristics */
13092 TidyProgramName(prog, host, buf)
13093 char *prog, *host, buf[MSG_SIZ];
13096 int local = (strcmp(host, "localhost") == 0);
13097 while (!local && (p = strchr(prog, ';')) != NULL) {
13099 while (*p == ' ') p++;
13102 if (*prog == '"' || *prog == '\'') {
13103 q = strchr(prog + 1, *prog);
13105 q = strchr(prog, ' ');
13107 if (q == NULL) q = prog + strlen(prog);
13109 while (p >= prog && *p != '/' && *p != '\\') p--;
13111 if(p == prog && *p == '"') p++;
13112 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13113 memcpy(buf, p, q - p);
13114 buf[q - p] = NULLCHAR;
13122 TimeControlTagValue()
13125 if (!appData.clockMode) {
13126 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
13127 } else if (movesPerSession > 0) {
13128 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
13129 } else if (timeIncrement == 0) {
13130 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
13132 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13134 return StrSave(buf);
13140 /* This routine is used only for certain modes */
13141 VariantClass v = gameInfo.variant;
13142 ChessMove r = GameUnfinished;
13145 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13146 r = gameInfo.result;
13147 p = gameInfo.resultDetails;
13148 gameInfo.resultDetails = NULL;
13150 ClearGameInfo(&gameInfo);
13151 gameInfo.variant = v;
13153 switch (gameMode) {
13154 case MachinePlaysWhite:
13155 gameInfo.event = StrSave( appData.pgnEventHeader );
13156 gameInfo.site = StrSave(HostName());
13157 gameInfo.date = PGNDate();
13158 gameInfo.round = StrSave("-");
13159 gameInfo.white = StrSave(first.tidy);
13160 gameInfo.black = StrSave(UserName());
13161 gameInfo.timeControl = TimeControlTagValue();
13164 case MachinePlaysBlack:
13165 gameInfo.event = StrSave( appData.pgnEventHeader );
13166 gameInfo.site = StrSave(HostName());
13167 gameInfo.date = PGNDate();
13168 gameInfo.round = StrSave("-");
13169 gameInfo.white = StrSave(UserName());
13170 gameInfo.black = StrSave(first.tidy);
13171 gameInfo.timeControl = TimeControlTagValue();
13174 case TwoMachinesPlay:
13175 gameInfo.event = StrSave( appData.pgnEventHeader );
13176 gameInfo.site = StrSave(HostName());
13177 gameInfo.date = PGNDate();
13178 if (matchGame > 0) {
13180 snprintf(buf, MSG_SIZ, "%d", matchGame);
13181 gameInfo.round = StrSave(buf);
13183 gameInfo.round = StrSave("-");
13185 if (first.twoMachinesColor[0] == 'w') {
13186 gameInfo.white = StrSave(first.tidy);
13187 gameInfo.black = StrSave(second.tidy);
13189 gameInfo.white = StrSave(second.tidy);
13190 gameInfo.black = StrSave(first.tidy);
13192 gameInfo.timeControl = TimeControlTagValue();
13196 gameInfo.event = StrSave("Edited game");
13197 gameInfo.site = StrSave(HostName());
13198 gameInfo.date = PGNDate();
13199 gameInfo.round = StrSave("-");
13200 gameInfo.white = StrSave("-");
13201 gameInfo.black = StrSave("-");
13202 gameInfo.result = r;
13203 gameInfo.resultDetails = p;
13207 gameInfo.event = StrSave("Edited position");
13208 gameInfo.site = StrSave(HostName());
13209 gameInfo.date = PGNDate();
13210 gameInfo.round = StrSave("-");
13211 gameInfo.white = StrSave("-");
13212 gameInfo.black = StrSave("-");
13215 case IcsPlayingWhite:
13216 case IcsPlayingBlack:
13221 case PlayFromGameFile:
13222 gameInfo.event = StrSave("Game from non-PGN file");
13223 gameInfo.site = StrSave(HostName());
13224 gameInfo.date = PGNDate();
13225 gameInfo.round = StrSave("-");
13226 gameInfo.white = StrSave("?");
13227 gameInfo.black = StrSave("?");
13236 ReplaceComment(index, text)
13242 while (*text == '\n') text++;
13243 len = strlen(text);
13244 while (len > 0 && text[len - 1] == '\n') len--;
13246 if (commentList[index] != NULL)
13247 free(commentList[index]);
13250 commentList[index] = NULL;
13253 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13254 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13255 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13256 commentList[index] = (char *) malloc(len + 2);
13257 strncpy(commentList[index], text, len);
13258 commentList[index][len] = '\n';
13259 commentList[index][len + 1] = NULLCHAR;
13261 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13263 commentList[index] = (char *) malloc(len + 7);
13264 safeStrCpy(commentList[index], "{\n", 3);
13265 safeStrCpy(commentList[index]+2, text, len+1);
13266 commentList[index][len+2] = NULLCHAR;
13267 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13268 strcat(commentList[index], "\n}\n");
13282 if (ch == '\r') continue;
13284 } while (ch != '\0');
13288 AppendComment(index, text, addBraces)
13291 Boolean addBraces; // [HGM] braces: tells if we should add {}
13296 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13297 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13300 while (*text == '\n') text++;
13301 len = strlen(text);
13302 while (len > 0 && text[len - 1] == '\n') len--;
13304 if (len == 0) return;
13306 if (commentList[index] != NULL) {
13307 old = commentList[index];
13308 oldlen = strlen(old);
13309 while(commentList[index][oldlen-1] == '\n')
13310 commentList[index][--oldlen] = NULLCHAR;
13311 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13312 safeStrCpy(commentList[index], old, oldlen);
13314 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13315 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces)) {
13316 if(addBraces) addBraces = FALSE; else { text++; len--; }
13317 while (*text == '\n') { text++; len--; }
13318 commentList[index][--oldlen] = NULLCHAR;
13320 if(addBraces) strcat(commentList[index], "\n{\n");
13321 else strcat(commentList[index], "\n");
13322 strcat(commentList[index], text);
13323 if(addBraces) strcat(commentList[index], "\n}\n");
13324 else strcat(commentList[index], "\n");
13326 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13328 safeStrCpy(commentList[index], "{\n", 3);
13329 else commentList[index][0] = NULLCHAR;
13330 strcat(commentList[index], text);
13331 strcat(commentList[index], "\n");
13332 if(addBraces) strcat(commentList[index], "}\n");
13336 static char * FindStr( char * text, char * sub_text )
13338 char * result = strstr( text, sub_text );
13340 if( result != NULL ) {
13341 result += strlen( sub_text );
13347 /* [AS] Try to extract PV info from PGN comment */
13348 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13349 char *GetInfoFromComment( int index, char * text )
13353 if( text != NULL && index > 0 ) {
13356 int time = -1, sec = 0, deci;
13357 char * s_eval = FindStr( text, "[%eval " );
13358 char * s_emt = FindStr( text, "[%emt " );
13360 if( s_eval != NULL || s_emt != NULL ) {
13364 if( s_eval != NULL ) {
13365 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13369 if( delim != ']' ) {
13374 if( s_emt != NULL ) {
13379 /* We expect something like: [+|-]nnn.nn/dd */
13382 if(*text != '{') return text; // [HGM] braces: must be normal comment
13384 sep = strchr( text, '/' );
13385 if( sep == NULL || sep < (text+4) ) {
13389 time = -1; sec = -1; deci = -1;
13390 if( sscanf( text+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13391 sscanf( text+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13392 sscanf( text+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13393 sscanf( text+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13397 if( score_lo < 0 || score_lo >= 100 ) {
13401 if(sec >= 0) time = 600*time + 10*sec; else
13402 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13404 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13406 /* [HGM] PV time: now locate end of PV info */
13407 while( *++sep >= '0' && *sep <= '9'); // strip depth
13409 while( *++sep >= '0' && *sep <= '9'); // strip time
13411 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13413 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13414 while(*sep == ' ') sep++;
13425 pvInfoList[index-1].depth = depth;
13426 pvInfoList[index-1].score = score;
13427 pvInfoList[index-1].time = 10*time; // centi-sec
13428 if(*sep == '}') *sep = 0; else *--sep = '{';
13434 SendToProgram(message, cps)
13436 ChessProgramState *cps;
13438 int count, outCount, error;
13441 if (cps->pr == NULL) return;
13444 if (appData.debugMode) {
13447 fprintf(debugFP, "%ld >%-6s: %s",
13448 SubtractTimeMarks(&now, &programStartTime),
13449 cps->which, message);
13452 count = strlen(message);
13453 outCount = OutputToProcess(cps->pr, message, count, &error);
13454 if (outCount < count && !exiting
13455 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13456 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), cps->which);
13457 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13458 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13459 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13460 snprintf(buf, MSG_SIZ, "%s program exits in draw position (%s)", cps->which, cps->program);
13462 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13464 gameInfo.resultDetails = StrSave(buf);
13466 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13471 ReceiveFromProgram(isr, closure, message, count, error)
13472 InputSourceRef isr;
13480 ChessProgramState *cps = (ChessProgramState *)closure;
13482 if (isr != cps->isr) return; /* Killed intentionally */
13485 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
13486 cps->which, cps->program);
13487 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13488 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13489 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13490 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), cps->which, cps->program);
13492 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13494 gameInfo.resultDetails = StrSave(buf);
13496 RemoveInputSource(cps->isr);
13497 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13499 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
13500 cps->which, cps->program);
13501 RemoveInputSource(cps->isr);
13503 /* [AS] Program is misbehaving badly... kill it */
13504 if( count == -2 ) {
13505 DestroyChildProcess( cps->pr, 9 );
13509 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13514 if ((end_str = strchr(message, '\r')) != NULL)
13515 *end_str = NULLCHAR;
13516 if ((end_str = strchr(message, '\n')) != NULL)
13517 *end_str = NULLCHAR;
13519 if (appData.debugMode) {
13520 TimeMark now; int print = 1;
13521 char *quote = ""; char c; int i;
13523 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13524 char start = message[0];
13525 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13526 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13527 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13528 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13529 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13530 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13531 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13532 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13533 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13534 print = (appData.engineComments >= 2);
13536 message[0] = start; // restore original message
13540 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13541 SubtractTimeMarks(&now, &programStartTime), cps->which,
13547 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13548 if (appData.icsEngineAnalyze) {
13549 if (strstr(message, "whisper") != NULL ||
13550 strstr(message, "kibitz") != NULL ||
13551 strstr(message, "tellics") != NULL) return;
13554 HandleMachineMove(message, cps);
13559 SendTimeControl(cps, mps, tc, inc, sd, st)
13560 ChessProgramState *cps;
13561 int mps, inc, sd, st;
13567 if( timeControl_2 > 0 ) {
13568 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13569 tc = timeControl_2;
13572 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13573 inc /= cps->timeOdds;
13574 st /= cps->timeOdds;
13576 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13579 /* Set exact time per move, normally using st command */
13580 if (cps->stKludge) {
13581 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13583 if (seconds == 0) {
13584 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
13586 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
13589 snprintf(buf, MSG_SIZ, "st %d\n", st);
13592 /* Set conventional or incremental time control, using level command */
13593 if (seconds == 0) {
13594 /* Note old gnuchess bug -- minutes:seconds used to not work.
13595 Fixed in later versions, but still avoid :seconds
13596 when seconds is 0. */
13597 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
13599 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
13600 seconds, inc/1000.);
13603 SendToProgram(buf, cps);
13605 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13606 /* Orthogonally, limit search to given depth */
13608 if (cps->sdKludge) {
13609 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
13611 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
13613 SendToProgram(buf, cps);
13616 if(cps->nps > 0) { /* [HGM] nps */
13617 if(cps->supportsNPS == FALSE)
13618 cps->nps = -1; // don't use if engine explicitly says not supported!
13620 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
13621 SendToProgram(buf, cps);
13626 ChessProgramState *WhitePlayer()
13627 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13629 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13630 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
13636 SendTimeRemaining(cps, machineWhite)
13637 ChessProgramState *cps;
13638 int /*boolean*/ machineWhite;
13640 char message[MSG_SIZ];
13643 /* Note: this routine must be called when the clocks are stopped
13644 or when they have *just* been set or switched; otherwise
13645 it will be off by the time since the current tick started.
13647 if (machineWhite) {
13648 time = whiteTimeRemaining / 10;
13649 otime = blackTimeRemaining / 10;
13651 time = blackTimeRemaining / 10;
13652 otime = whiteTimeRemaining / 10;
13654 /* [HGM] translate opponent's time by time-odds factor */
13655 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
13656 if (appData.debugMode) {
13657 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
13660 if (time <= 0) time = 1;
13661 if (otime <= 0) otime = 1;
13663 snprintf(message, MSG_SIZ, "time %ld\n", time);
13664 SendToProgram(message, cps);
13666 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
13667 SendToProgram(message, cps);
13671 BoolFeature(p, name, loc, cps)
13675 ChessProgramState *cps;
13678 int len = strlen(name);
13681 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13683 sscanf(*p, "%d", &val);
13685 while (**p && **p != ' ')
13687 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13688 SendToProgram(buf, cps);
13695 IntFeature(p, name, loc, cps)
13699 ChessProgramState *cps;
13702 int len = strlen(name);
13703 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13705 sscanf(*p, "%d", loc);
13706 while (**p && **p != ' ') (*p)++;
13707 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13708 SendToProgram(buf, cps);
13715 StringFeature(p, name, loc, cps)
13719 ChessProgramState *cps;
13722 int len = strlen(name);
13723 if (strncmp((*p), name, len) == 0
13724 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
13726 sscanf(*p, "%[^\"]", loc);
13727 while (**p && **p != '\"') (*p)++;
13728 if (**p == '\"') (*p)++;
13729 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13730 SendToProgram(buf, cps);
13737 ParseOption(Option *opt, ChessProgramState *cps)
13738 // [HGM] options: process the string that defines an engine option, and determine
13739 // name, type, default value, and allowed value range
13741 char *p, *q, buf[MSG_SIZ];
13742 int n, min = (-1)<<31, max = 1<<31, def;
13744 if(p = strstr(opt->name, " -spin ")) {
13745 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
13746 if(max < min) max = min; // enforce consistency
13747 if(def < min) def = min;
13748 if(def > max) def = max;
13753 } else if((p = strstr(opt->name, " -slider "))) {
13754 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
13755 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
13756 if(max < min) max = min; // enforce consistency
13757 if(def < min) def = min;
13758 if(def > max) def = max;
13762 opt->type = Spin; // Slider;
13763 } else if((p = strstr(opt->name, " -string "))) {
13764 opt->textValue = p+9;
13765 opt->type = TextBox;
13766 } else if((p = strstr(opt->name, " -file "))) {
13767 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
13768 opt->textValue = p+7;
13769 opt->type = TextBox; // FileName;
13770 } else if((p = strstr(opt->name, " -path "))) {
13771 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
13772 opt->textValue = p+7;
13773 opt->type = TextBox; // PathName;
13774 } else if(p = strstr(opt->name, " -check ")) {
13775 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
13776 opt->value = (def != 0);
13777 opt->type = CheckBox;
13778 } else if(p = strstr(opt->name, " -combo ")) {
13779 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
13780 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
13781 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
13782 opt->value = n = 0;
13783 while(q = StrStr(q, " /// ")) {
13784 n++; *q = 0; // count choices, and null-terminate each of them
13786 if(*q == '*') { // remember default, which is marked with * prefix
13790 cps->comboList[cps->comboCnt++] = q;
13792 cps->comboList[cps->comboCnt++] = NULL;
13794 opt->type = ComboBox;
13795 } else if(p = strstr(opt->name, " -button")) {
13796 opt->type = Button;
13797 } else if(p = strstr(opt->name, " -save")) {
13798 opt->type = SaveButton;
13799 } else return FALSE;
13800 *p = 0; // terminate option name
13801 // now look if the command-line options define a setting for this engine option.
13802 if(cps->optionSettings && cps->optionSettings[0])
13803 p = strstr(cps->optionSettings, opt->name); else p = NULL;
13804 if(p && (p == cps->optionSettings || p[-1] == ',')) {
13805 snprintf(buf, MSG_SIZ, "option %s", p);
13806 if(p = strstr(buf, ",")) *p = 0;
13807 if(q = strchr(buf, '=')) switch(opt->type) {
13809 for(n=0; n<opt->max; n++)
13810 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
13813 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
13817 opt->value = atoi(q+1);
13822 SendToProgram(buf, cps);
13828 FeatureDone(cps, val)
13829 ChessProgramState* cps;
13832 DelayedEventCallback cb = GetDelayedEvent();
13833 if ((cb == InitBackEnd3 && cps == &first) ||
13834 (cb == TwoMachinesEventIfReady && cps == &second)) {
13835 CancelDelayedEvent();
13836 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
13838 cps->initDone = val;
13841 /* Parse feature command from engine */
13843 ParseFeatures(args, cps)
13845 ChessProgramState *cps;
13853 while (*p == ' ') p++;
13854 if (*p == NULLCHAR) return;
13856 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
13857 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
13858 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
13859 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
13860 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
13861 if (BoolFeature(&p, "reuse", &val, cps)) {
13862 /* Engine can disable reuse, but can't enable it if user said no */
13863 if (!val) cps->reuse = FALSE;
13866 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
13867 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
13868 if (gameMode == TwoMachinesPlay) {
13869 DisplayTwoMachinesTitle();
13875 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
13876 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
13877 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
13878 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
13879 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
13880 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
13881 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
13882 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
13883 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
13884 if (IntFeature(&p, "done", &val, cps)) {
13885 FeatureDone(cps, val);
13888 /* Added by Tord: */
13889 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
13890 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
13891 /* End of additions by Tord */
13893 /* [HGM] added features: */
13894 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
13895 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
13896 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
13897 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
13898 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
13899 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
13900 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
13901 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
13902 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
13903 SendToProgram(buf, cps);
13906 if(cps->nrOptions >= MAX_OPTIONS) {
13908 snprintf(buf, MSG_SIZ, "%s engine has too many options\n", cps->which);
13909 DisplayError(buf, 0);
13913 /* End of additions by HGM */
13915 /* unknown feature: complain and skip */
13917 while (*q && *q != '=') q++;
13918 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
13919 SendToProgram(buf, cps);
13925 while (*p && *p != '\"') p++;
13926 if (*p == '\"') p++;
13928 while (*p && *p != ' ') p++;
13936 PeriodicUpdatesEvent(newState)
13939 if (newState == appData.periodicUpdates)
13942 appData.periodicUpdates=newState;
13944 /* Display type changes, so update it now */
13945 // DisplayAnalysis();
13947 /* Get the ball rolling again... */
13949 AnalysisPeriodicEvent(1);
13950 StartAnalysisClock();
13955 PonderNextMoveEvent(newState)
13958 if (newState == appData.ponderNextMove) return;
13959 if (gameMode == EditPosition) EditPositionDone(TRUE);
13961 SendToProgram("hard\n", &first);
13962 if (gameMode == TwoMachinesPlay) {
13963 SendToProgram("hard\n", &second);
13966 SendToProgram("easy\n", &first);
13967 thinkOutput[0] = NULLCHAR;
13968 if (gameMode == TwoMachinesPlay) {
13969 SendToProgram("easy\n", &second);
13972 appData.ponderNextMove = newState;
13976 NewSettingEvent(option, feature, command, value)
13978 int option, value, *feature;
13982 if (gameMode == EditPosition) EditPositionDone(TRUE);
13983 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
13984 if(feature == NULL || *feature) SendToProgram(buf, &first);
13985 if (gameMode == TwoMachinesPlay) {
13986 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
13991 ShowThinkingEvent()
13992 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
13994 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
13995 int newState = appData.showThinking
13996 // [HGM] thinking: other features now need thinking output as well
13997 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
13999 if (oldState == newState) return;
14000 oldState = newState;
14001 if (gameMode == EditPosition) EditPositionDone(TRUE);
14003 SendToProgram("post\n", &first);
14004 if (gameMode == TwoMachinesPlay) {
14005 SendToProgram("post\n", &second);
14008 SendToProgram("nopost\n", &first);
14009 thinkOutput[0] = NULLCHAR;
14010 if (gameMode == TwoMachinesPlay) {
14011 SendToProgram("nopost\n", &second);
14014 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
14018 AskQuestionEvent(title, question, replyPrefix, which)
14019 char *title; char *question; char *replyPrefix; char *which;
14021 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
14022 if (pr == NoProc) return;
14023 AskQuestion(title, question, replyPrefix, pr);
14027 DisplayMove(moveNumber)
14030 char message[MSG_SIZ];
14032 char cpThinkOutput[MSG_SIZ];
14034 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
14036 if (moveNumber == forwardMostMove - 1 ||
14037 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14039 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
14041 if (strchr(cpThinkOutput, '\n')) {
14042 *strchr(cpThinkOutput, '\n') = NULLCHAR;
14045 *cpThinkOutput = NULLCHAR;
14048 /* [AS] Hide thinking from human user */
14049 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
14050 *cpThinkOutput = NULLCHAR;
14051 if( thinkOutput[0] != NULLCHAR ) {
14054 for( i=0; i<=hiddenThinkOutputState; i++ ) {
14055 cpThinkOutput[i] = '.';
14057 cpThinkOutput[i] = NULLCHAR;
14058 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
14062 if (moveNumber == forwardMostMove - 1 &&
14063 gameInfo.resultDetails != NULL) {
14064 if (gameInfo.resultDetails[0] == NULLCHAR) {
14065 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
14067 snprintf(res, MSG_SIZ, " {%s} %s",
14068 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
14074 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14075 DisplayMessage(res, cpThinkOutput);
14077 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
14078 WhiteOnMove(moveNumber) ? " " : ".. ",
14079 parseList[moveNumber], res);
14080 DisplayMessage(message, cpThinkOutput);
14085 DisplayComment(moveNumber, text)
14089 char title[MSG_SIZ];
14090 char buf[8000]; // comment can be long!
14093 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14094 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
14096 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
14097 WhiteOnMove(moveNumber) ? " " : ".. ",
14098 parseList[moveNumber]);
14100 // [HGM] PV info: display PV info together with (or as) comment
14101 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14102 if(text == NULL) text = "";
14103 score = pvInfoList[moveNumber].score;
14104 snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14105 depth, (pvInfoList[moveNumber].time+50)/100, text);
14108 if (text != NULL && (appData.autoDisplayComment || commentUp))
14109 CommentPopUp(title, text);
14112 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14113 * might be busy thinking or pondering. It can be omitted if your
14114 * gnuchess is configured to stop thinking immediately on any user
14115 * input. However, that gnuchess feature depends on the FIONREAD
14116 * ioctl, which does not work properly on some flavors of Unix.
14120 ChessProgramState *cps;
14123 if (!cps->useSigint) return;
14124 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14125 switch (gameMode) {
14126 case MachinePlaysWhite:
14127 case MachinePlaysBlack:
14128 case TwoMachinesPlay:
14129 case IcsPlayingWhite:
14130 case IcsPlayingBlack:
14133 /* Skip if we know it isn't thinking */
14134 if (!cps->maybeThinking) return;
14135 if (appData.debugMode)
14136 fprintf(debugFP, "Interrupting %s\n", cps->which);
14137 InterruptChildProcess(cps->pr);
14138 cps->maybeThinking = FALSE;
14143 #endif /*ATTENTION*/
14149 if (whiteTimeRemaining <= 0) {
14152 if (appData.icsActive) {
14153 if (appData.autoCallFlag &&
14154 gameMode == IcsPlayingBlack && !blackFlag) {
14155 SendToICS(ics_prefix);
14156 SendToICS("flag\n");
14160 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14162 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14163 if (appData.autoCallFlag) {
14164 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14171 if (blackTimeRemaining <= 0) {
14174 if (appData.icsActive) {
14175 if (appData.autoCallFlag &&
14176 gameMode == IcsPlayingWhite && !whiteFlag) {
14177 SendToICS(ics_prefix);
14178 SendToICS("flag\n");
14182 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14184 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14185 if (appData.autoCallFlag) {
14186 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14199 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14200 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14203 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14205 if ( !WhiteOnMove(forwardMostMove) ) {
14206 /* White made time control */
14207 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
14208 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
14209 /* [HGM] time odds: correct new time quota for time odds! */
14210 / WhitePlayer()->timeOdds;
14211 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
14213 lastBlack -= blackTimeRemaining;
14214 /* Black made time control */
14215 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
14216 / WhitePlayer()->other->timeOdds;
14217 lastWhite = whiteTimeRemaining;
14222 DisplayBothClocks()
14224 int wom = gameMode == EditPosition ?
14225 !blackPlaysFirst : WhiteOnMove(currentMove);
14226 DisplayWhiteClock(whiteTimeRemaining, wom);
14227 DisplayBlackClock(blackTimeRemaining, !wom);
14231 /* Timekeeping seems to be a portability nightmare. I think everyone
14232 has ftime(), but I'm really not sure, so I'm including some ifdefs
14233 to use other calls if you don't. Clocks will be less accurate if
14234 you have neither ftime nor gettimeofday.
14237 /* VS 2008 requires the #include outside of the function */
14238 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14239 #include <sys/timeb.h>
14242 /* Get the current time as a TimeMark */
14247 #if HAVE_GETTIMEOFDAY
14249 struct timeval timeVal;
14250 struct timezone timeZone;
14252 gettimeofday(&timeVal, &timeZone);
14253 tm->sec = (long) timeVal.tv_sec;
14254 tm->ms = (int) (timeVal.tv_usec / 1000L);
14256 #else /*!HAVE_GETTIMEOFDAY*/
14259 // include <sys/timeb.h> / moved to just above start of function
14260 struct timeb timeB;
14263 tm->sec = (long) timeB.time;
14264 tm->ms = (int) timeB.millitm;
14266 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14267 tm->sec = (long) time(NULL);
14273 /* Return the difference in milliseconds between two
14274 time marks. We assume the difference will fit in a long!
14277 SubtractTimeMarks(tm2, tm1)
14278 TimeMark *tm2, *tm1;
14280 return 1000L*(tm2->sec - tm1->sec) +
14281 (long) (tm2->ms - tm1->ms);
14286 * Code to manage the game clocks.
14288 * In tournament play, black starts the clock and then white makes a move.
14289 * We give the human user a slight advantage if he is playing white---the
14290 * clocks don't run until he makes his first move, so it takes zero time.
14291 * Also, we don't account for network lag, so we could get out of sync
14292 * with GNU Chess's clock -- but then, referees are always right.
14295 static TimeMark tickStartTM;
14296 static long intendedTickLength;
14299 NextTickLength(timeRemaining)
14300 long timeRemaining;
14302 long nominalTickLength, nextTickLength;
14304 if (timeRemaining > 0L && timeRemaining <= 10000L)
14305 nominalTickLength = 100L;
14307 nominalTickLength = 1000L;
14308 nextTickLength = timeRemaining % nominalTickLength;
14309 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14311 return nextTickLength;
14314 /* Adjust clock one minute up or down */
14316 AdjustClock(Boolean which, int dir)
14318 if(which) blackTimeRemaining += 60000*dir;
14319 else whiteTimeRemaining += 60000*dir;
14320 DisplayBothClocks();
14323 /* Stop clocks and reset to a fresh time control */
14327 (void) StopClockTimer();
14328 if (appData.icsActive) {
14329 whiteTimeRemaining = blackTimeRemaining = 0;
14330 } else if (searchTime) {
14331 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14332 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14333 } else { /* [HGM] correct new time quote for time odds */
14334 whiteTC = blackTC = fullTimeControlString;
14335 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
14336 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
14338 if (whiteFlag || blackFlag) {
14340 whiteFlag = blackFlag = FALSE;
14342 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
14343 DisplayBothClocks();
14346 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14348 /* Decrement running clock by amount of time that has passed */
14352 long timeRemaining;
14353 long lastTickLength, fudge;
14356 if (!appData.clockMode) return;
14357 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14361 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14363 /* Fudge if we woke up a little too soon */
14364 fudge = intendedTickLength - lastTickLength;
14365 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14367 if (WhiteOnMove(forwardMostMove)) {
14368 if(whiteNPS >= 0) lastTickLength = 0;
14369 timeRemaining = whiteTimeRemaining -= lastTickLength;
14370 if(timeRemaining < 0 && !appData.icsActive) {
14371 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
14372 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
14373 whiteStartMove = forwardMostMove; whiteTC = nextSession;
14374 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
14377 DisplayWhiteClock(whiteTimeRemaining - fudge,
14378 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14380 if(blackNPS >= 0) lastTickLength = 0;
14381 timeRemaining = blackTimeRemaining -= lastTickLength;
14382 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
14383 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
14385 blackStartMove = forwardMostMove;
14386 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
14389 DisplayBlackClock(blackTimeRemaining - fudge,
14390 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14392 if (CheckFlags()) return;
14395 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14396 StartClockTimer(intendedTickLength);
14398 /* if the time remaining has fallen below the alarm threshold, sound the
14399 * alarm. if the alarm has sounded and (due to a takeback or time control
14400 * with increment) the time remaining has increased to a level above the
14401 * threshold, reset the alarm so it can sound again.
14404 if (appData.icsActive && appData.icsAlarm) {
14406 /* make sure we are dealing with the user's clock */
14407 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14408 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14411 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14412 alarmSounded = FALSE;
14413 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14415 alarmSounded = TRUE;
14421 /* A player has just moved, so stop the previously running
14422 clock and (if in clock mode) start the other one.
14423 We redisplay both clocks in case we're in ICS mode, because
14424 ICS gives us an update to both clocks after every move.
14425 Note that this routine is called *after* forwardMostMove
14426 is updated, so the last fractional tick must be subtracted
14427 from the color that is *not* on move now.
14430 SwitchClocks(int newMoveNr)
14432 long lastTickLength;
14434 int flagged = FALSE;
14438 if (StopClockTimer() && appData.clockMode) {
14439 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14440 if (!WhiteOnMove(forwardMostMove)) {
14441 if(blackNPS >= 0) lastTickLength = 0;
14442 blackTimeRemaining -= lastTickLength;
14443 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14444 // if(pvInfoList[forwardMostMove-1].time == -1)
14445 pvInfoList[forwardMostMove-1].time = // use GUI time
14446 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14448 if(whiteNPS >= 0) lastTickLength = 0;
14449 whiteTimeRemaining -= lastTickLength;
14450 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14451 // if(pvInfoList[forwardMostMove-1].time == -1)
14452 pvInfoList[forwardMostMove-1].time =
14453 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14455 flagged = CheckFlags();
14457 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14458 CheckTimeControl();
14460 if (flagged || !appData.clockMode) return;
14462 switch (gameMode) {
14463 case MachinePlaysBlack:
14464 case MachinePlaysWhite:
14465 case BeginningOfGame:
14466 if (pausing) return;
14470 case PlayFromGameFile:
14478 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14479 if(WhiteOnMove(forwardMostMove))
14480 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14481 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14485 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14486 whiteTimeRemaining : blackTimeRemaining);
14487 StartClockTimer(intendedTickLength);
14491 /* Stop both clocks */
14495 long lastTickLength;
14498 if (!StopClockTimer()) return;
14499 if (!appData.clockMode) return;
14503 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14504 if (WhiteOnMove(forwardMostMove)) {
14505 if(whiteNPS >= 0) lastTickLength = 0;
14506 whiteTimeRemaining -= lastTickLength;
14507 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14509 if(blackNPS >= 0) lastTickLength = 0;
14510 blackTimeRemaining -= lastTickLength;
14511 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14516 /* Start clock of player on move. Time may have been reset, so
14517 if clock is already running, stop and restart it. */
14521 (void) StopClockTimer(); /* in case it was running already */
14522 DisplayBothClocks();
14523 if (CheckFlags()) return;
14525 if (!appData.clockMode) return;
14526 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14528 GetTimeMark(&tickStartTM);
14529 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14530 whiteTimeRemaining : blackTimeRemaining);
14532 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14533 whiteNPS = blackNPS = -1;
14534 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14535 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14536 whiteNPS = first.nps;
14537 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14538 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14539 blackNPS = first.nps;
14540 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14541 whiteNPS = second.nps;
14542 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14543 blackNPS = second.nps;
14544 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14546 StartClockTimer(intendedTickLength);
14553 long second, minute, hour, day;
14555 static char buf[32];
14557 if (ms > 0 && ms <= 9900) {
14558 /* convert milliseconds to tenths, rounding up */
14559 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14561 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
14565 /* convert milliseconds to seconds, rounding up */
14566 /* use floating point to avoid strangeness of integer division
14567 with negative dividends on many machines */
14568 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14575 day = second / (60 * 60 * 24);
14576 second = second % (60 * 60 * 24);
14577 hour = second / (60 * 60);
14578 second = second % (60 * 60);
14579 minute = second / 60;
14580 second = second % 60;
14583 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
14584 sign, day, hour, minute, second);
14586 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
14588 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
14595 * This is necessary because some C libraries aren't ANSI C compliant yet.
14598 StrStr(string, match)
14599 char *string, *match;
14603 length = strlen(match);
14605 for (i = strlen(string) - length; i >= 0; i--, string++)
14606 if (!strncmp(match, string, length))
14613 StrCaseStr(string, match)
14614 char *string, *match;
14618 length = strlen(match);
14620 for (i = strlen(string) - length; i >= 0; i--, string++) {
14621 for (j = 0; j < length; j++) {
14622 if (ToLower(match[j]) != ToLower(string[j]))
14625 if (j == length) return string;
14639 c1 = ToLower(*s1++);
14640 c2 = ToLower(*s2++);
14641 if (c1 > c2) return 1;
14642 if (c1 < c2) return -1;
14643 if (c1 == NULLCHAR) return 0;
14652 return isupper(c) ? tolower(c) : c;
14660 return islower(c) ? toupper(c) : c;
14662 #endif /* !_amigados */
14670 if ((ret = (char *) malloc(strlen(s) + 1)))
14672 safeStrCpy(ret, s, strlen(s)+1);
14678 StrSavePtr(s, savePtr)
14679 char *s, **savePtr;
14684 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
14685 safeStrCpy(*savePtr, s, strlen(s)+1);
14697 clock = time((time_t *)NULL);
14698 tm = localtime(&clock);
14699 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
14700 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
14701 return StrSave(buf);
14706 PositionToFEN(move, overrideCastling)
14708 char *overrideCastling;
14710 int i, j, fromX, fromY, toX, toY;
14717 whiteToPlay = (gameMode == EditPosition) ?
14718 !blackPlaysFirst : (move % 2 == 0);
14721 /* Piece placement data */
14722 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14724 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
14725 if (boards[move][i][j] == EmptySquare) {
14727 } else { ChessSquare piece = boards[move][i][j];
14728 if (emptycount > 0) {
14729 if(emptycount<10) /* [HGM] can be >= 10 */
14730 *p++ = '0' + emptycount;
14731 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
14734 if(PieceToChar(piece) == '+') {
14735 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
14737 piece = (ChessSquare)(DEMOTED piece);
14739 *p++ = PieceToChar(piece);
14741 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
14742 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
14747 if (emptycount > 0) {
14748 if(emptycount<10) /* [HGM] can be >= 10 */
14749 *p++ = '0' + emptycount;
14750 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
14757 /* [HGM] print Crazyhouse or Shogi holdings */
14758 if( gameInfo.holdingsWidth ) {
14759 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
14761 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
14762 piece = boards[move][i][BOARD_WIDTH-1];
14763 if( piece != EmptySquare )
14764 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
14765 *p++ = PieceToChar(piece);
14767 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
14768 piece = boards[move][BOARD_HEIGHT-i-1][0];
14769 if( piece != EmptySquare )
14770 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
14771 *p++ = PieceToChar(piece);
14774 if( q == p ) *p++ = '-';
14780 *p++ = whiteToPlay ? 'w' : 'b';
14783 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
14784 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
14786 if(nrCastlingRights) {
14788 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
14789 /* [HGM] write directly from rights */
14790 if(boards[move][CASTLING][2] != NoRights &&
14791 boards[move][CASTLING][0] != NoRights )
14792 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
14793 if(boards[move][CASTLING][2] != NoRights &&
14794 boards[move][CASTLING][1] != NoRights )
14795 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
14796 if(boards[move][CASTLING][5] != NoRights &&
14797 boards[move][CASTLING][3] != NoRights )
14798 *p++ = boards[move][CASTLING][3] + AAA;
14799 if(boards[move][CASTLING][5] != NoRights &&
14800 boards[move][CASTLING][4] != NoRights )
14801 *p++ = boards[move][CASTLING][4] + AAA;
14804 /* [HGM] write true castling rights */
14805 if( nrCastlingRights == 6 ) {
14806 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
14807 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
14808 if(boards[move][CASTLING][1] == BOARD_LEFT &&
14809 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
14810 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
14811 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
14812 if(boards[move][CASTLING][4] == BOARD_LEFT &&
14813 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
14816 if (q == p) *p++ = '-'; /* No castling rights */
14820 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
14821 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
14822 /* En passant target square */
14823 if (move > backwardMostMove) {
14824 fromX = moveList[move - 1][0] - AAA;
14825 fromY = moveList[move - 1][1] - ONE;
14826 toX = moveList[move - 1][2] - AAA;
14827 toY = moveList[move - 1][3] - ONE;
14828 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
14829 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
14830 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
14832 /* 2-square pawn move just happened */
14834 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
14838 } else if(move == backwardMostMove) {
14839 // [HGM] perhaps we should always do it like this, and forget the above?
14840 if((signed char)boards[move][EP_STATUS] >= 0) {
14841 *p++ = boards[move][EP_STATUS] + AAA;
14842 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
14853 /* [HGM] find reversible plies */
14854 { int i = 0, j=move;
14856 if (appData.debugMode) { int k;
14857 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
14858 for(k=backwardMostMove; k<=forwardMostMove; k++)
14859 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
14863 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
14864 if( j == backwardMostMove ) i += initialRulePlies;
14865 sprintf(p, "%d ", i);
14866 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
14868 /* Fullmove number */
14869 sprintf(p, "%d", (move / 2) + 1);
14871 return StrSave(buf);
14875 ParseFEN(board, blackPlaysFirst, fen)
14877 int *blackPlaysFirst;
14887 /* [HGM] by default clear Crazyhouse holdings, if present */
14888 if(gameInfo.holdingsWidth) {
14889 for(i=0; i<BOARD_HEIGHT; i++) {
14890 board[i][0] = EmptySquare; /* black holdings */
14891 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
14892 board[i][1] = (ChessSquare) 0; /* black counts */
14893 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
14897 /* Piece placement data */
14898 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14901 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
14902 if (*p == '/') p++;
14903 emptycount = gameInfo.boardWidth - j;
14904 while (emptycount--)
14905 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14907 #if(BOARD_FILES >= 10)
14908 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
14909 p++; emptycount=10;
14910 if (j + emptycount > gameInfo.boardWidth) return FALSE;
14911 while (emptycount--)
14912 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14914 } else if (isdigit(*p)) {
14915 emptycount = *p++ - '0';
14916 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
14917 if (j + emptycount > gameInfo.boardWidth) return FALSE;
14918 while (emptycount--)
14919 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14920 } else if (*p == '+' || isalpha(*p)) {
14921 if (j >= gameInfo.boardWidth) return FALSE;
14923 piece = CharToPiece(*++p);
14924 if(piece == EmptySquare) return FALSE; /* unknown piece */
14925 piece = (ChessSquare) (PROMOTED piece ); p++;
14926 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
14927 } else piece = CharToPiece(*p++);
14929 if(piece==EmptySquare) return FALSE; /* unknown piece */
14930 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
14931 piece = (ChessSquare) (PROMOTED piece);
14932 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
14935 board[i][(j++)+gameInfo.holdingsWidth] = piece;
14941 while (*p == '/' || *p == ' ') p++;
14943 /* [HGM] look for Crazyhouse holdings here */
14944 while(*p==' ') p++;
14945 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
14947 if(*p == '-' ) p++; /* empty holdings */ else {
14948 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
14949 /* if we would allow FEN reading to set board size, we would */
14950 /* have to add holdings and shift the board read so far here */
14951 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
14953 if((int) piece >= (int) BlackPawn ) {
14954 i = (int)piece - (int)BlackPawn;
14955 i = PieceToNumber((ChessSquare)i);
14956 if( i >= gameInfo.holdingsSize ) return FALSE;
14957 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
14958 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
14960 i = (int)piece - (int)WhitePawn;
14961 i = PieceToNumber((ChessSquare)i);
14962 if( i >= gameInfo.holdingsSize ) return FALSE;
14963 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
14964 board[i][BOARD_WIDTH-2]++; /* black holdings */
14971 while(*p == ' ') p++;
14975 if(appData.colorNickNames) {
14976 if( c == appData.colorNickNames[0] ) c = 'w'; else
14977 if( c == appData.colorNickNames[1] ) c = 'b';
14981 *blackPlaysFirst = FALSE;
14984 *blackPlaysFirst = TRUE;
14990 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
14991 /* return the extra info in global variiables */
14993 /* set defaults in case FEN is incomplete */
14994 board[EP_STATUS] = EP_UNKNOWN;
14995 for(i=0; i<nrCastlingRights; i++ ) {
14996 board[CASTLING][i] =
14997 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
14998 } /* assume possible unless obviously impossible */
14999 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
15000 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
15001 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
15002 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
15003 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
15004 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
15005 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
15006 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
15009 while(*p==' ') p++;
15010 if(nrCastlingRights) {
15011 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
15012 /* castling indicator present, so default becomes no castlings */
15013 for(i=0; i<nrCastlingRights; i++ ) {
15014 board[CASTLING][i] = NoRights;
15017 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
15018 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
15019 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
15020 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
15021 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
15023 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
15024 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
15025 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
15027 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
15028 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
15029 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
15030 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
15031 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
15032 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
15035 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
15036 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
15037 board[CASTLING][2] = whiteKingFile;
15040 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
15041 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
15042 board[CASTLING][2] = whiteKingFile;
15045 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
15046 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
15047 board[CASTLING][5] = blackKingFile;
15050 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
15051 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
15052 board[CASTLING][5] = blackKingFile;
15055 default: /* FRC castlings */
15056 if(c >= 'a') { /* black rights */
15057 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15058 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
15059 if(i == BOARD_RGHT) break;
15060 board[CASTLING][5] = i;
15062 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
15063 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
15065 board[CASTLING][3] = c;
15067 board[CASTLING][4] = c;
15068 } else { /* white rights */
15069 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15070 if(board[0][i] == WhiteKing) break;
15071 if(i == BOARD_RGHT) break;
15072 board[CASTLING][2] = i;
15073 c -= AAA - 'a' + 'A';
15074 if(board[0][c] >= WhiteKing) break;
15076 board[CASTLING][0] = c;
15078 board[CASTLING][1] = c;
15082 for(i=0; i<nrCastlingRights; i++)
15083 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
15084 if (appData.debugMode) {
15085 fprintf(debugFP, "FEN castling rights:");
15086 for(i=0; i<nrCastlingRights; i++)
15087 fprintf(debugFP, " %d", board[CASTLING][i]);
15088 fprintf(debugFP, "\n");
15091 while(*p==' ') p++;
15094 /* read e.p. field in games that know e.p. capture */
15095 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15096 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15098 p++; board[EP_STATUS] = EP_NONE;
15100 char c = *p++ - AAA;
15102 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
15103 if(*p >= '0' && *p <='9') p++;
15104 board[EP_STATUS] = c;
15109 if(sscanf(p, "%d", &i) == 1) {
15110 FENrulePlies = i; /* 50-move ply counter */
15111 /* (The move number is still ignored) */
15118 EditPositionPasteFEN(char *fen)
15121 Board initial_position;
15123 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15124 DisplayError(_("Bad FEN position in clipboard"), 0);
15127 int savedBlackPlaysFirst = blackPlaysFirst;
15128 EditPositionEvent();
15129 blackPlaysFirst = savedBlackPlaysFirst;
15130 CopyBoard(boards[0], initial_position);
15131 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15132 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15133 DisplayBothClocks();
15134 DrawPosition(FALSE, boards[currentMove]);
15139 static char cseq[12] = "\\ ";
15141 Boolean set_cont_sequence(char *new_seq)
15146 // handle bad attempts to set the sequence
15148 return 0; // acceptable error - no debug
15150 len = strlen(new_seq);
15151 ret = (len > 0) && (len < sizeof(cseq));
15153 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
15154 else if (appData.debugMode)
15155 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15160 reformat a source message so words don't cross the width boundary. internal
15161 newlines are not removed. returns the wrapped size (no null character unless
15162 included in source message). If dest is NULL, only calculate the size required
15163 for the dest buffer. lp argument indicats line position upon entry, and it's
15164 passed back upon exit.
15166 int wrap(char *dest, char *src, int count, int width, int *lp)
15168 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15170 cseq_len = strlen(cseq);
15171 old_line = line = *lp;
15172 ansi = len = clen = 0;
15174 for (i=0; i < count; i++)
15176 if (src[i] == '\033')
15179 // if we hit the width, back up
15180 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15182 // store i & len in case the word is too long
15183 old_i = i, old_len = len;
15185 // find the end of the last word
15186 while (i && src[i] != ' ' && src[i] != '\n')
15192 // word too long? restore i & len before splitting it
15193 if ((old_i-i+clen) >= width)
15200 if (i && src[i-1] == ' ')
15203 if (src[i] != ' ' && src[i] != '\n')
15210 // now append the newline and continuation sequence
15215 strncpy(dest+len, cseq, cseq_len);
15223 dest[len] = src[i];
15227 if (src[i] == '\n')
15232 if (dest && appData.debugMode)
15234 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15235 count, width, line, len, *lp);
15236 show_bytes(debugFP, src, count);
15237 fprintf(debugFP, "\ndest: ");
15238 show_bytes(debugFP, dest, len);
15239 fprintf(debugFP, "\n");
15241 *lp = dest ? line : old_line;
15246 // [HGM] vari: routines for shelving variations
15249 PushTail(int firstMove, int lastMove)
15251 int i, j, nrMoves = lastMove - firstMove;
15253 if(appData.icsActive) { // only in local mode
15254 forwardMostMove = currentMove; // mimic old ICS behavior
15257 if(storedGames >= MAX_VARIATIONS-1) return;
15259 // push current tail of game on stack
15260 savedResult[storedGames] = gameInfo.result;
15261 savedDetails[storedGames] = gameInfo.resultDetails;
15262 gameInfo.resultDetails = NULL;
15263 savedFirst[storedGames] = firstMove;
15264 savedLast [storedGames] = lastMove;
15265 savedFramePtr[storedGames] = framePtr;
15266 framePtr -= nrMoves; // reserve space for the boards
15267 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15268 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15269 for(j=0; j<MOVE_LEN; j++)
15270 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15271 for(j=0; j<2*MOVE_LEN; j++)
15272 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15273 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15274 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15275 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15276 pvInfoList[firstMove+i-1].depth = 0;
15277 commentList[framePtr+i] = commentList[firstMove+i];
15278 commentList[firstMove+i] = NULL;
15282 forwardMostMove = firstMove; // truncate game so we can start variation
15283 if(storedGames == 1) GreyRevert(FALSE);
15287 PopTail(Boolean annotate)
15290 char buf[8000], moveBuf[20];
15292 if(appData.icsActive) return FALSE; // only in local mode
15293 if(!storedGames) return FALSE; // sanity
15294 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15297 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15298 nrMoves = savedLast[storedGames] - currentMove;
15301 if(!WhiteOnMove(currentMove))
15302 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
15303 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
15304 for(i=currentMove; i<forwardMostMove; i++) {
15306 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
15307 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
15308 strcat(buf, moveBuf);
15309 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15310 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15314 for(i=1; i<=nrMoves; i++) { // copy last variation back
15315 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15316 for(j=0; j<MOVE_LEN; j++)
15317 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15318 for(j=0; j<2*MOVE_LEN; j++)
15319 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15320 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15321 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15322 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15323 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15324 commentList[currentMove+i] = commentList[framePtr+i];
15325 commentList[framePtr+i] = NULL;
15327 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15328 framePtr = savedFramePtr[storedGames];
15329 gameInfo.result = savedResult[storedGames];
15330 if(gameInfo.resultDetails != NULL) {
15331 free(gameInfo.resultDetails);
15333 gameInfo.resultDetails = savedDetails[storedGames];
15334 forwardMostMove = currentMove + nrMoves;
15335 if(storedGames == 0) GreyRevert(TRUE);
15341 { // remove all shelved variations
15343 for(i=0; i<storedGames; i++) {
15344 if(savedDetails[i])
15345 free(savedDetails[i]);
15346 savedDetails[i] = NULL;
15348 for(i=framePtr; i<MAX_MOVES; i++) {
15349 if(commentList[i]) free(commentList[i]);
15350 commentList[i] = NULL;
15352 framePtr = MAX_MOVES-1;
15357 LoadVariation(int index, char *text)
15358 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15359 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15360 int level = 0, move;
15362 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15363 // first find outermost bracketing variation
15364 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15365 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15366 if(*p == '{') wait = '}'; else
15367 if(*p == '[') wait = ']'; else
15368 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15369 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15371 if(*p == wait) wait = NULLCHAR; // closing ]} found
15374 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15375 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15376 end[1] = NULLCHAR; // clip off comment beyond variation
15377 ToNrEvent(currentMove-1);
15378 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15379 // kludge: use ParsePV() to append variation to game
15380 move = currentMove;
15381 ParsePV(start, TRUE);
15382 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15383 ClearPremoveHighlights();
15385 ToNrEvent(currentMove+1);