Adjusted alternative joining method to obey keepLineBreaksICS
[xboard.git] / zippy.c
1 /*
2  * zippy.c -- Implements Zippy the Pinhead chess player on ICS in XBoard
3  *
4  * Copyright 1991 by Digital Equipment Corporation, Maynard,
5  * Massachusetts. 
6  *
7  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8  * 2007, 2008, 2009 Free Software Foundation, Inc.
9  *
10  * Enhancements Copyright 2005 Alessandro Scotti
11  *
12  * The following terms apply to Digital Equipment Corporation's copyright
13  * interest in XBoard:
14  * ------------------------------------------------------------------------
15  * All Rights Reserved
16  *
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.
24  *
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
31  * SOFTWARE.
32  * ------------------------------------------------------------------------
33  *
34  * The following terms apply to the enhanced version of XBoard
35  * distributed by the Free Software Foundation:
36  * ------------------------------------------------------------------------
37  *
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.
42  *
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.
47  *
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/.
50  *
51  *------------------------------------------------------------------------
52  ** See the file ChangeLog for a revision history.  */
53
54 #include "config.h"
55
56 #include <stdio.h>
57 #include <errno.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <ctype.h>
61
62 #if STDC_HEADERS
63 # include <stdlib.h>
64 # include <string.h>
65 #else /* not STDC_HEADERS */
66 extern char *getenv();
67 # if HAVE_STRING_H
68 #  include <string.h>
69 # else /* not HAVE_STRING_H */
70 #  include <strings.h>
71 # endif /* not HAVE_STRING_H */
72 #endif /* not STDC_HEADERS */
73
74 #if TIME_WITH_SYS_TIME
75 # include <sys/time.h>
76 # include <time.h>
77 #else
78 # if HAVE_SYS_TIME_H
79 #  include <sys/time.h>
80 # else
81 #  include <time.h>
82 # endif
83 #endif
84 #define HI "hlelo "
85
86 #if HAVE_UNISTD_H
87 # include <unistd.h>
88 #endif
89
90 #include "common.h"
91 #include "zippy.h"
92 #include "frontend.h"
93 #include "backend.h"
94 #include "backendz.h"
95
96 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
97 void HandleMachineMove P((char *message, ChessProgramState *cps));
98
99 static char zippyPartner[MSG_SIZ];
100 static char zippyLastOpp[MSG_SIZ];
101 static char zippyOffender[MSG_SIZ]; // [HGM] aborter
102 static int zippyConsecGames;
103 static time_t zippyLastGameEnd;
104
105 extern void mysrandom(unsigned int seed);
106 extern int myrandom(void);
107
108 void ZippyInit()
109 {
110     char *p;
111
112     /* Get name of Zippy lines file */
113     p = getenv("ZIPPYLINES");
114     if (p != NULL) {
115       appData.zippyLines = p;
116     }
117
118     /* Get word that Zippy thinks is insulting */
119     p = getenv("ZIPPYPINHEAD");
120     if (p != NULL) {
121       appData.zippyPinhead = p;
122     }
123
124     /* What password is used for remote control? */
125     p = getenv("ZIPPYPASSWORD");
126     if (p != NULL) {
127       appData.zippyPassword = p;
128     }
129
130     /* What password is used for remote commands to gnuchess? */
131     p = getenv("ZIPPYPASSWORD2");
132     if (p != NULL) {
133       appData.zippyPassword2 = p;
134     }
135
136     /* Joke feature for people who try an old password */
137     p = getenv("ZIPPYWRONGPASSWORD");
138     if (p != NULL) {
139       appData.zippyWrongPassword = p;
140     }
141
142     /* While testing, I want to accept challenges from only one person
143        (namely, my "anonymous" account), so I set an environment
144        variable ZIPPYACCEPTONLY. */
145     p = getenv("ZIPPYACCEPTONLY");
146     if ( p != NULL ) {
147       appData.zippyAcceptOnly = p;
148     }
149     
150     /* Should Zippy use "i" command? */
151     /* Defaults to 1=true */
152     p = getenv("ZIPPYUSEI");
153     if (p != NULL) {
154       appData.zippyUseI = atoi(p);
155     }
156
157     /* How does Zippy handle bughouse partnering? */
158     /* 0=say we can't play, 1=manual partnering, 2=auto partnering */
159     p = getenv("ZIPPYBUGHOUSE");
160     if (p != NULL) {
161       appData.zippyBughouse = atoi(p);
162     }
163
164     /* Does Zippy abort games with Crafty? */
165     /* Defaults to 0=false */
166     p = getenv("ZIPPYNOPLAYCRAFTY");
167     if (p != NULL) {
168       appData.zippyNoplayCrafty = atoi(p);
169     }
170
171     /* What ICS command does Zippy send at game end?  Default: "gameend". */
172     p = getenv("ZIPPYGAMEEND");
173     if (p != NULL) {
174       appData.zippyGameEnd = p;
175     }
176
177     /* What ICS command does Zippy send at game start?  Default: none. */
178     p = getenv("ZIPPYGAMESTART");
179     if (p != NULL) {
180       appData.zippyGameStart = p;
181     }
182
183     /* Should Zippy accept adjourns? */
184     /* Defaults to 0=false */
185     p = getenv("ZIPPYADJOURN");
186     if (p != NULL) {
187       appData.zippyAdjourn = atoi(p);
188     }
189
190     /* Should Zippy accept aborts? */
191     /* Defaults to 0=false */
192     p = getenv("ZIPPYABORT");
193     if (p != NULL) {
194       appData.zippyAbort = atoi(p);
195     }
196
197     /* Should Zippy play chess variants (besides bughouse)? */
198     p = getenv("ZIPPYVARIANTS");
199     if (p != NULL) {
200       appData.zippyVariants = p;
201     }
202     strcpy(first.variants, appData.zippyVariants);
203
204     srandom(time(NULL));
205 }
206
207 /*
208  * Routines to implement Zippy talking
209  */
210
211
212 char *swifties[] = { 
213     "i acclaims:", "i admonishes:", "i advertises:", "i advises:",
214     "i advocates:", "i affirms:", "i alleges:", "i anathematizes:",
215     "i animadverts:", "i announces:", "i apostrophizes:",
216     "i appeals:", "i applauds:", "i approves:", "i argues:",
217     "i articulates:", "i asserts:", "i asseverates:", "i attests:",
218     "i avers:", "i avows:", "i baas:", "i babbles:", "i banters:",
219     "i barks:", "i bawls:", "i bays:", "i begs:", "i belches:",
220     "i bellows:", "i belts out:", "i berates:", "i beshrews:",
221     "i blabbers:", "i blabs:", "i blares:", "i blasphemes:",
222     "i blasts:", "i blathers:", "i bleats:", "i blithers:",
223     "i blubbers:", "i blurts out:", "i blusters:", "i boasts:",
224     "i brags:", "i brays:", "i broadcasts:", "i burbles:",
225     "i buzzes:", "i cachinnates:", "i cackles:", "i caterwauls:",
226     "i calumniates:", "i caws:", "i censures:", "i chants:",
227     "i chatters:", "i cheeps:", "i cheers:", "i chides:", "i chins:",
228     "i chirps:", "i chortles:", "i chuckles:", "i claims:",
229     "i clamors:", "i clucks:", "i commands:", "i commends:",
230     "i comments:", "i commiserates:", "i communicates:",
231     "i complains:", "i concludes:", "i confabulates:", "i confesses:",
232     "i coos:", "i coughs:", "i counsels:", "i cries:", "i croaks:",
233     "i crows:", "i curses:", "i daydreams:", "i debates:",
234     "i declaims:", "i declares:", "i delivers:", "i denounces:",
235     "i deposes:", "i directs:", "i discloses:", "i disparages:",
236     "i discourses:", "i divulges:", "i documents:", "i drawls:",
237     "i dreams:", "i drivels:", "i drones:", "i effuses:",
238     /*"i ejaculates:",*/ "i elucidates:", "i emotes:", "i endorses:",
239     "i enthuses:", "i entreats:", "i enunciates:", "i eulogizes:",
240     "i exclaims:", "i execrates:", "i exhorts:", "i expatiates:",
241     "i explains:", "i explicates:", "i explodes:", "i exposes:",
242     "i exposits:", "i expostulates: ",
243     "i expounds:", "i expresses:", "i extols:",
244     "i exults:", "i fantasizes:", "i fibs:", "i filibusters:",
245     "i flatters:", "i flutes:", "i fools:", "i free-associates:",
246     "i fulminates:", "i gabbles:", "i gabs:", "i gasps:",
247     "i giggles:", "i gossips:", "i gripes:", "i groans:", "i growls:",
248     "i grunts:", "i guesses:", "i guffaws:", "i gushes:", "i hails:",
249     "i hallucinates:", "i harangues:", "i harmonizes:", "i hectors:",
250     "i hints:", "i hisses:", "i hollers:", "i honks:", "i hoots:",
251     "i hosannas:", "i howls:", "i hums:", "i hypothecates:",
252     "i hypothesizes:", "i imagines:", "i implies:", "i implores:",
253     "i imprecates:", "i indicates:", "i infers:",
254     "i informs everyone:",  "i instructs:", "i interjects:", 
255     "i interposes:", "i intimates:", "i intones:", "i introspects:",
256     "i inveighs:", "i jabbers:", "i japes:", "i jests:", "i jibes:",
257     "i jives:", "i jokes:", "i joshes:", "i keens:", "i laments:",
258     "i lauds:", "i laughs:", "i lectures:", "i lies:", "i lilts:",
259     "i lisps:", "i maintains:", "i maledicts:", "i maunders:",
260     "i meows:", "i mewls:", "i mimes:", "i minces:", "i moans:",
261     "i moos:", "i mourns:", "i mouths:", "i mumbles:", "i murmurs:",
262     "i muses:", "i mutters:", "i nags:", "i natters:", "i neighs:",
263     "i notes:", "i nuncupates:", "i objurgates:", "i observes:",
264     "i offers:", "i oinks:", "i opines:", "i orates:", "i orders:",
265     "i panegyrizes:", "i pantomimes:", "i pants:", "i peals:",
266     "i peeps:", "i perorates:", "i persuades:", "i petitions:",
267     "i phonates:", "i pipes up:", "i pitches:", "i pleads:",
268     "i points out:", "i pontificates:", "i postulates:", "i praises:",
269     "i prates:", "i prattles:", "i preaches:", "i prescribes:",
270     "i prevaricates:", "i proclaims:", "i projects:", "i pronounces:",
271     "i proposes:", "i proscribes:", "i quacks:", "i queries:",
272     "i questions:", "i quips:", "i quotes:", "i rages:", "i rambles:",
273     "i rants:", "i raps:", "i rasps:", "i rattles:", "i raves:",
274     "i reacts:", "i recites:", "i recommends:", "i records:",
275     "i reiterates:", "i rejoins:", "i releases:", "i remarks:",
276     "i reminisces:", "i remonstrates:", "i repeats:", "i replies:",
277     "i reports:", "i reprimands:", "i reproaches:", "i reproves:",
278     "i resounds:", "i responds:", "i retorts:", "i reveals:",
279     "i reviles:", "i roars:", "i rumbles:", "i sanctions:",
280     "i satirizes:", "i sauces:", "i scolds:", "i screams:",
281     "i screeches:", "i semaphores:", "i sends:", "i sermonizes:",
282     "i shrieks:", "i sibilates:", "i sighs:", "i signals:",
283     "i signifies:", "i signs:", "i sings:", "i slurs:", "i snaps:",
284     "i snarls:", "i sneezes:", "i snickers:", "i sniggers:",
285     "i snivels:", "i snores:", "i snorts:", "i sobs:",
286     "i soliloquizes:", "i sounds off:", "i sounds out:", "i speaks:",
287     "i spews:", "i spits out:", "i splutters:", "i spoofs:",
288     "i spouts:", "i sputters:", "i squalls:", "i squawks:",
289     "i squeaks:", "i squeals:", "i stammers:", "i states:",
290     "i stresses:", "i stutters:", "i submits:", "i suggests:",
291     "i summarizes:", "i sums up:", "i swears:", "i talks:",
292     "i tattles:", "i teases:", "i telegraphs:", "i testifies:",
293     "i threatens:", "i thunders:", "i titters:", "i tongue-lashes:",
294     "i toots:", "i transcribes:", "i transmits:", "i trills:",
295     "i trumpets:", "i twaddles:", "i tweets:", "i twitters:",
296     "i types:", "i upbraids:", "i urges:", "i utters:", "i ventures:",
297     "i vibrates:", "i vilifies:", "i vituperates:", "i vocalizes:",
298     "i vociferates:", "i voices:", "i waffles:", "i wails:",
299     "i warbles:", "i warns:", "i weeps:", "i wheezes:", "i whimpers:",
300     "i whines:", "i whinnies:", "i whistles:", "i wisecracks:",
301     "i witnesses:", "i woofs:", "i writes:", "i yammers:", "i yawps:",
302     "i yells:", "i yelps:", "i yodels:", "i yowls:", "i zings:",
303 };
304
305 #define MAX_SPEECH 250
306
307 void Speak(how, whom) 
308      char *how, *whom;
309 {
310     static FILE *zipfile = NULL;
311     static struct stat zipstat;
312     char zipbuf[MAX_SPEECH + 1];
313     static time_t lastShout = 0;
314     time_t now;
315     char  *p;
316     int c, speechlen;
317     Boolean done;
318                 
319     if (strcmp(how, "shout") == 0) {
320         now = time((time_t *) NULL);
321         if (now - lastShout < 1*60) return;
322         lastShout = now;
323         if (appData.zippyUseI) {
324             how = swifties[(unsigned) random() %
325                            (sizeof(swifties)/sizeof(char *))];
326         }
327     }
328
329     if (zipfile == NULL) {
330         zipfile = fopen(appData.zippyLines, "r");
331         if (zipfile == NULL) {
332             DisplayFatalError("Can't open Zippy lines file", errno, 1);
333             return;
334         }
335         fstat(fileno(zipfile), &zipstat);
336     }
337                 
338     for (;;) {
339         fseek(zipfile, (unsigned) random() % zipstat.st_size, 0);
340         do {
341           c = getc(zipfile);
342         } while (c != NULLCHAR && c != '^' && c != EOF);
343         if (c == EOF) continue;
344         while ((c = getc(zipfile)) == '\n') ;
345         if (c == EOF) continue;
346         break;
347     }
348     done = FALSE;
349
350     /* Don't use ics_prefix; we need to let FICS expand the alias i -> it,
351        but use the real command "i" on ICC */
352     strcpy(zipbuf, how);
353     strcat(zipbuf, " ");
354     if (whom != NULL) {
355         strcat(zipbuf, whom);
356         strcat(zipbuf, " ");
357     }
358     speechlen = strlen(zipbuf);
359     p = zipbuf + speechlen;
360
361     while (++speechlen < MAX_SPEECH) {
362         if (c == NULLCHAR || c == '^') {
363             *p++ = '\n';
364             *p = '\0';
365             SendToICS(zipbuf);
366             return;
367         } else if (c == '\n') {
368             *p++ = ' ';
369             do {
370                 c = getc(zipfile);
371             } while (c == ' ');
372         } else if (c == EOF) {
373             break;
374         } else {
375             *p++ = c;
376             c = getc(zipfile);
377         }
378     }
379     /* Tried to say something too long, or junk at the end of the
380        file.  Try something else. */
381     Speak(how, whom);  /* tail recursion */
382 }
383
384 int ZippyCalled(str)
385      char *str;
386 {
387     return ics_handle[0] != NULLCHAR && StrCaseStr(str, ics_handle) != NULL;
388 }
389
390 static char opp_name[128][32];
391 static int num_opps=0;
392
393 extern ColorClass curColor;
394
395 static void SetCurColor( ColorClass color )
396 {
397     curColor = color;
398 }
399
400 static void ColorizeEx( ColorClass color, int cont )
401 {
402     if( appData.colorize ) {
403         Colorize( color, cont );
404         SetCurColor( color );
405     }
406 }
407
408 int ZippyControl(buf, i)
409      char *buf;
410      int *i;
411 {
412     char *player, *p;
413     char reply[MSG_SIZ];
414
415 #if TRIVIA
416 #include "trivia.c"
417 #endif
418
419     /* Possibly reject Crafty as opponent */
420     if (appData.zippyPlay && appData.zippyNoplayCrafty && forwardMostMove < 4
421         && looking_at(buf, i, "* kibitzes: Hello from Crafty")) 
422     {
423         player = StripHighlightAndTitle(star_match[0]);
424         if ((gameMode == IcsPlayingWhite &&
425              StrCaseCmp(player, gameInfo.black) == 0) ||
426             (gameMode == IcsPlayingBlack &&
427              StrCaseCmp(player, gameInfo.white) == 0)) {
428
429           sprintf(reply, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n",
430                   ics_prefix, ics_prefix, ics_prefix, player);
431           SendToICS(reply);
432         }
433         return TRUE;
434     }
435
436     /* If this is a computer, save the name.  Then later, once the */
437     /* game is really started, we will send the "computer" notice to */
438     /* the engine.  */ 
439     if (appData.zippyPlay &&
440         looking_at(buf, i, "* is in the computer list")) {
441         int i;
442         for (i=0;i<num_opps;i++)
443           if (!strcmp(opp_name[i],star_match[0])) break;
444         if (i >= num_opps) strcpy(opp_name[num_opps++],star_match[0]);
445     }
446     if (appData.zippyPlay && looking_at(buf, i, "* * is a computer *")) {
447         int i;
448         for (i=0;i<num_opps;i++)
449           if (!strcmp(opp_name[i],star_match[1])) break;
450         if (i >= num_opps) strcpy(opp_name[num_opps++],star_match[1]);
451     }
452
453     /* Tells and says */
454     if (appData.zippyPlay && 
455         (looking_at(buf, i, "* offers to be your bughouse partner") ||
456          looking_at(buf, i, "* tells you: [automatic message] I chose you"))) {
457         player = StripHighlightAndTitle(star_match[0]);
458         if (appData.zippyBughouse > 1 && first.initDone) {
459             sprintf(reply, "%spartner %s\n", ics_prefix, player);
460             SendToICS(reply);
461             if (strcmp(zippyPartner, player) != 0) {
462                 strcpy(zippyPartner, player);
463                 SendToProgram(reply + strlen(ics_prefix), &first);
464             }
465         } else if (appData.zippyBughouse > 0) {
466             sprintf(reply, "%sdecline %s\n", ics_prefix, player);
467             SendToICS(reply);
468         } else {
469             sprintf(reply, "%stell %s This computer cannot play bughouse\n",
470                     ics_prefix, player);
471             SendToICS(reply);
472         }
473         return TRUE;
474     }
475
476     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
477         looking_at(buf, i, "* agrees to be your partner")) {
478         player = StripHighlightAndTitle(star_match[0]);
479         sprintf(reply, "partner %s\n", player);
480         if (strcmp(zippyPartner, player) != 0) {
481             strcpy(zippyPartner, player);
482             SendToProgram(reply, &first);
483         }
484         return TRUE;
485     }
486
487     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
488         (looking_at(buf, i, "are no longer *'s partner") ||
489          looking_at(buf, i,
490                     "* tells you: [automatic message] I'm no longer your"))) {
491         player = StripHighlightAndTitle(star_match[0]);
492         if (strcmp(zippyPartner, player) == 0) {
493             zippyPartner[0] = NULLCHAR;
494             SendToProgram("partner\n", &first);
495         }
496         return TRUE;
497     }
498
499     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
500         (looking_at(buf, i, "no longer have a bughouse partner") ||
501          looking_at(buf, i, "partner has disconnected") ||
502          looking_at(buf, i, "partner has just chosen a new partner"))) {
503       zippyPartner[0] = NULLCHAR;
504       SendToProgram("partner\n", &first);
505       return TRUE;
506     }
507
508     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
509         looking_at(buf, i, "* (your partner) tells you: *")) {
510         /* This pattern works on FICS but not ICC */
511         player = StripHighlightAndTitle(star_match[0]);
512         if (strcmp(zippyPartner, player) != 0) {
513             strcpy(zippyPartner, player);
514             sprintf(reply, "partner %s\n", player);
515             SendToProgram(reply, &first);
516         }
517         sprintf(reply, "ptell %s\n", star_match[1]);
518         SendToProgram(reply, &first);
519         return TRUE;
520     }
521
522     if (looking_at(buf, i, "* tells you: *") ||
523         looking_at(buf, i, "* says: *")) 
524     {
525         player = StripHighlightAndTitle(star_match[0]);
526         if (appData.zippyPassword[0] != NULLCHAR &&
527             strncmp(star_match[1], appData.zippyPassword,
528                     strlen(appData.zippyPassword)) == 0) {
529             p = star_match[1] + strlen(appData.zippyPassword);
530             while (*p == ' ') p++;
531             SendToICS(p);
532             SendToICS("\n");
533         } else if (appData.zippyPassword2[0] != NULLCHAR && first.initDone &&
534             strncmp(star_match[1], appData.zippyPassword2,
535                     strlen(appData.zippyPassword2)) == 0) {
536             p = star_match[1] + strlen(appData.zippyPassword2);
537             while (*p == ' ') p++;
538             SendToProgram(p, &first);
539             SendToProgram("\n", &first);
540         } else if (appData.zippyWrongPassword[0] != NULLCHAR &&
541             strncmp(star_match[1], appData.zippyWrongPassword,
542                     strlen(appData.zippyWrongPassword)) == 0) {
543             p = star_match[1] + strlen(appData.zippyWrongPassword);
544             while (*p == ' ') p++;
545             sprintf(reply, "wrong %s\n", player);
546             SendToICS(reply);
547         } else if (appData.zippyBughouse && first.initDone &&
548                    strcmp(player, zippyPartner) == 0) {
549             SendToProgram("ptell ", &first);
550             SendToProgram(star_match[1], &first);
551             SendToProgram("\n", &first);
552         } else if (strncmp(star_match[1], HI, 6) == 0) {
553             extern char* programVersion;
554             sprintf(reply, "%stell %s %s\n",
555                     ics_prefix, player, programVersion);
556             SendToICS(reply);
557         } else if (strncmp(star_match[1], "W0W!! ", 6) == 0) {
558             extern char* programVersion;
559             sprintf(reply, "%stell %s %s\n", ics_prefix,
560                     player, programVersion);
561             SendToICS(reply);
562         } else if (appData.zippyTalk && (((unsigned) random() % 10) < 9)) {
563             if (strcmp(player, ics_handle) != 0) {
564                 Speak("tell", player);
565             }
566         }
567
568         ColorizeEx( ColorTell, FALSE );
569
570         return TRUE;
571     }
572
573     if( appData.colorize && looking_at(buf, i, "* (*) seeking") ) {
574         ColorizeEx(ColorSeek, FALSE);
575         return FALSE;
576     }
577
578     if (looking_at(buf, i, "* spoofs you:")) {
579         player = StripHighlightAndTitle(star_match[0]);
580         sprintf(reply, "spoofedby %s\n", player);
581         SendToICS(reply);
582     }
583
584     return FALSE;
585 }
586
587 int ZippyConverse(buf, i)
588      char *buf;
589      int *i;
590 {
591     static char lastgreet[MSG_SIZ];
592     char reply[MSG_SIZ];
593     int oldi;
594
595     /* Shouts and emotes */
596     if (looking_at(buf, i, "--> * *") ||
597         looking_at(buf, i, "* shouts: *")) 
598     {
599       if (appData.zippyTalk) {
600         char *player = StripHighlightAndTitle(star_match[0]);
601         if (strcmp(player, ics_handle) == 0) {
602             return TRUE;
603         } else if (appData.zippyPinhead[0] != NULLCHAR &&
604                    StrCaseStr(star_match[1], appData.zippyPinhead) != NULL) {
605             sprintf(reply, "insult %s\n", player);
606             SendToICS(reply);
607         } else if (ZippyCalled(star_match[1])) {
608             Speak("shout", NULL);
609         }
610       }
611
612       ColorizeEx(ColorShout, FALSE);
613
614       return TRUE;
615     }
616
617     if (looking_at(buf, i, "* kibitzes: *")) {
618       if (appData.zippyTalk && ((unsigned) random() % 10) < 9) {
619         char *player = StripHighlightAndTitle(star_match[0]);
620         if (strcmp(player, ics_handle) != 0) {
621             Speak("kibitz", NULL);
622         }
623       }
624
625       ColorizeEx(ColorKibitz, FALSE);
626
627       return TRUE;
628     }
629
630     if (looking_at(buf, i, "* whispers: *")) {
631       if (appData.zippyTalk && ((unsigned) random() % 10) < 9) {
632         char *player = StripHighlightAndTitle(star_match[0]);
633         if (strcmp(player, ics_handle) != 0) {
634             Speak("whisper", NULL);
635         }
636       }
637
638       ColorizeEx(ColorKibitz, FALSE);
639
640       return TRUE;
641     }
642
643     /* Messages */
644     if ((looking_at(buf, i, ". * (*:*): *") && isdigit(star_match[1][0])) ||
645          looking_at(buf, i, ". * at *:*: *")) {
646       if (appData.zippyTalk) {
647         FILE *f;
648         char *player = StripHighlightAndTitle(star_match[0]);
649
650         if (strcmp(player, ics_handle) != 0) {
651             if (((unsigned) random() % 10) < 9)
652               Speak("message", player);
653             f = fopen("zippy.messagelog", "a");
654             fprintf(f, "%s (%s:%s): %s\n", player,
655                     star_match[1], star_match[2], star_match[3]);
656             fclose(f);
657         }
658       }
659       return TRUE;
660     }
661
662     /* Channel tells */
663     oldi = *i;
664     if (looking_at(buf, i, "*(*: *")) {
665         char *player;
666         char *channel;
667         if (star_match[0][0] == NULLCHAR  ||
668             strchr(star_match[0], ' ') ||
669             strchr(star_match[1], ' ')) {
670             /* Oops, did not want to match this; probably a message */
671             *i = oldi;
672             return FALSE;
673         }
674         if (appData.zippyTalk) {
675           player = StripHighlightAndTitle(star_match[0]);
676           channel = strrchr(star_match[1], '(');
677           if (channel == NULL) {
678             channel = star_match[1];
679           } else {
680             channel++;
681           }
682           channel[strlen(channel)-1] = NULLCHAR;
683
684           /* Tell to the channel only if someone mentions our name */
685           if (ZippyCalled(star_match[2])) {
686             Speak("tell", channel);
687           }
688
689           ColorizeEx( atoi(channel) == 1 ? ColorChannel1 : ColorChannel, FALSE );
690         }
691         return TRUE;
692     }
693
694     if (!appData.zippyTalk) return FALSE;
695
696     if ((looking_at(buf, i, "You have * message") &&
697          atoi(star_match[0]) != 0) ||
698         looking_at(buf, i, "* has left a message for you") ||
699         looking_at(buf, i, "* just sent you a message")) {
700         sprintf(reply, "%smessages\n%sclearmessages *\n",
701                 ics_prefix, ics_prefix);
702         SendToICS(reply);
703         return TRUE;
704     }
705
706     if (looking_at(buf, i, "Notification: * has arrived")) {
707         if (((unsigned) random() % 3) == 0) {
708             char *player = StripHighlightAndTitle(star_match[0]);
709             strcpy(lastgreet, player);
710             sprintf(reply, "greet %s\n", player);
711             SendToICS(reply);
712             Speak("tell", player);
713         }
714     }   
715
716     if (looking_at(buf, i, "Notification: * has departed")) {
717         if (((unsigned) random() % 3) == 0) {
718             char *player = StripHighlightAndTitle(star_match[0]);
719             sprintf(reply, "farewell %s\n", player);
720             SendToICS(reply);
721         }
722     }   
723
724     if (looking_at(buf, i, "Not sent -- * is censoring you")) {
725         char *player = StripHighlightAndTitle(star_match[0]);
726         if (strcmp(player, lastgreet) == 0) {
727             sprintf(reply, "%s-notify %s\n", ics_prefix, player);
728             SendToICS(reply);
729         }
730     }   
731
732     if (looking_at(buf, i, "command is currently turned off")) {
733         appData.zippyUseI = 0;
734     }
735
736     return FALSE;
737 }
738
739 void ZippyGameStart(white, black)
740      char *white, *black;
741 {
742     if (!first.initDone) {
743       /* Game is starting prematurely.  We can't deal with this */
744       SendToICS(ics_prefix);
745       SendToICS("abort\n");
746       SendToICS(ics_prefix);
747       SendToICS("say Sorry, the chess program is not initialized yet.\n");
748       return;
749     }
750
751     if (appData.zippyGameStart[0] != NULLCHAR) {
752       SendToICS(appData.zippyGameStart);
753       SendToICS("\n");
754     }
755 }
756
757 void ZippyGameEnd(result, resultDetails)
758      ChessMove result;
759      char *resultDetails;
760 {
761     if (appData.zippyAcceptOnly[0] == NULLCHAR &&
762         appData.zippyGameEnd[0] != NULLCHAR) {
763       SendToICS(appData.zippyGameEnd);
764       SendToICS("\n");
765     }
766     zippyLastGameEnd = time(0);
767     if(forwardMostMove < appData.zippyShortGame) 
768         strcpy(zippyOffender, zippyLastOpp); else zippyOffender[0] = 0; // [HGM] aborter
769 }
770
771 /*
772  * Routines to implement Zippy playing chess
773  */
774
775 void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
776      char *srated, *swild, *sbase, *sincrement, *opponent;
777 {
778     char buf[MSG_SIZ];
779     int base, increment, i=0;
780     char rated;
781     VariantClass variant;
782     char *varname;
783
784     rated = srated[0];
785     variant = StringToVariant(swild);
786     varname = VariantName(variant);
787     base = atoi(sbase);
788     increment = atoi(sincrement);
789
790     /* [DM] If icsAnalyzeEngine active we don't accept automatic games */
791     if (appData.icsActive && appData.icsEngineAnalyze) return;
792
793     /* If desired, you can insert more code here to decline matches
794        based on rated, variant, base, and increment, but it is
795        easier to use the ICS formula feature instead. */
796
797     if (variant == VariantLoadable) {
798         sprintf(buf,
799          "%stell %s This computer can't play wild type %s\n%sdecline %s\n",
800                 ics_prefix, opponent, swild, ics_prefix, opponent);
801         SendToICS(buf);
802         return;
803     }
804     if (StrStr(appData.zippyVariants, varname) == NULL ||
805               ((i=first.protocolVersion) != 1 && StrStr(first.variants, varname) == NULL) /* [HGM] zippyvar */
806                                                           ) {
807         sprintf(buf,
808          "%stell %s This computer can't play %s [%s], only %s\n%sdecline %s\n",
809                 ics_prefix, opponent, swild, varname, 
810                 i ? first.variants : appData.zippyVariants,                               /* [HGM] zippyvar */
811                 ics_prefix, opponent);
812         SendToICS(buf);
813         return;
814     }
815
816     /* Are we blocking match requests from all but one person? */
817     if (appData.zippyAcceptOnly[0] != NULLCHAR &&
818         StrCaseCmp(opponent, appData.zippyAcceptOnly)) {
819         /* Yes, and this isn't him.  Ignore challenge. */
820         return;
821     }
822     
823     /* Too many consecutive games with same opponent?  If so, make him
824        wait until someone else has played or a timeout has elapsed. */
825     if (appData.zippyMaxGames &&
826         strcmp(opponent, zippyLastOpp) == 0 &&
827         zippyConsecGames >= appData.zippyMaxGames &&
828         difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
829       sprintf(buf, "%stell %s Sorry, you have just played %d consecutive games against %s.  To give others a chance, please wait %d seconds or until someone else has played.\n%sdecline %s\n",
830               ics_prefix, opponent, zippyConsecGames, ics_handle,
831               appData.zippyReplayTimeout, ics_prefix, opponent);
832       SendToICS(buf);
833       return;
834     }
835
836     /* [HGM] aborter: opponent is cheater that aborts games he doesn't like on first move. Make him wait */
837     if (strcmp(opponent, zippyOffender) == 0 &&
838         difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
839       sprintf(buf, "%stell %s Sorry, your previous game against %s was rather short. "
840                    " It will wait %d seconds to see if a tougher opponent comes along.\n%sdecline %s\n",
841               ics_prefix, opponent, ics_handle,
842               appData.zippyReplayTimeout, ics_prefix, opponent);
843       SendToICS(buf);
844       return;
845     }
846
847     /* Engine not yet initialized or still thinking about last game? */
848     if (!first.initDone || first.lastPing != first.lastPong) {
849       sprintf(buf, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n",
850               ics_prefix, opponent, ics_prefix, opponent);
851       SendToICS(buf);
852       return;
853     }
854
855     sprintf(buf, "%saccept %s\n", ics_prefix, opponent);
856     SendToICS(buf);
857     if (appData.zippyTalk) {
858       Speak("tell", opponent);
859     }
860 }
861
862
863 /* Accept matches */
864 int ZippyMatch(buf, i)
865      char *buf;
866      int *i;
867 {
868     if (looking_at(buf, i, "* * match * * requested with * (*)")) {
869
870         ZippyHandleChallenge(star_match[0], star_match[1],
871                              star_match[2], star_match[3],
872                              StripHighlightAndTitle(star_match[4]));
873         return TRUE;
874     }
875
876     /* Old FICS 0-increment form */
877     if (looking_at(buf, i, "* * match * requested with * (*)")) {
878
879         ZippyHandleChallenge(star_match[0], star_match[1],
880                              star_match[2], "0",
881                              StripHighlightAndTitle(star_match[3]));
882         return TRUE;
883     }
884
885     if (looking_at(buf, i,
886                    "* has made an alternate proposal of * * match * *.")) {
887
888         ZippyHandleChallenge(star_match[1], star_match[2],
889                              star_match[3], star_match[4],
890                              StripHighlightAndTitle(star_match[0]));
891         return TRUE;
892     }
893
894     /* FICS wild/nonstandard forms */
895     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * Loaded from *")) {
896         /* note: star_match[2] can include "[white] " or "[black] "
897            before our own name. */
898         if(star_match[8] == NULL || star_match[8][0] == 0) // [HGM] chessd: open-source ICS has file on next line
899              ZippyHandleChallenge(star_match[4], star_match[5],
900                              star_match[6], star_match[7],                           StripHighlightAndTitle(star_match[0]));
901         else ZippyHandleChallenge(star_match[4], star_match[8],
902                              star_match[6], star_match[7],
903                              StripHighlightAndTitle(star_match[0]));
904         return TRUE;
905     }
906
907     if (looking_at(buf, i,
908                    "Challenge: * (*) *(*) * * * * : * * Loaded from *")) {
909         /* note: star_match[2] can include "[white] " or "[black] "
910            before our own name. */
911         ZippyHandleChallenge(star_match[4], star_match[10],
912                              star_match[8], star_match[9],
913                              StripHighlightAndTitle(star_match[0]));
914         return TRUE;
915     }
916
917     /* Regular forms */
918     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * : * *") |
919         looking_at(buf, i, "Challenge: * (*) *(*) * * * * * *")) {
920         /* note: star_match[2] can include "[white] " or "[black] "
921            before our own name. */
922         ZippyHandleChallenge(star_match[4], star_match[5],
923                              star_match[8], star_match[9],
924                              StripHighlightAndTitle(star_match[0]));
925         return TRUE;
926     }
927
928     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * *")) {
929         /* note: star_match[2] can include "[white] " or "[black] "
930            before our own name. */
931         ZippyHandleChallenge(star_match[4], star_match[5],
932                              star_match[6], star_match[7],
933                              StripHighlightAndTitle(star_match[0]));
934         return TRUE;
935     }
936
937
938     if (ics_type == ICS_ICC) { // [DM]
939         if (looking_at(buf, i, "Your opponent offers you a draw")) {
940             if (first.sendDrawOffers && first.initDone)
941                 SendToProgram("draw\n", &first);
942             return TRUE;
943         }
944     } else {
945         if (looking_at(buf, i, "offers you a draw")) {
946             if (first.sendDrawOffers && first.initDone) {
947                 SendToProgram("draw\n", &first);
948             }
949             return TRUE;
950         }
951     }
952
953     if (looking_at(buf, i, "requests that the game be aborted") ||
954         looking_at(buf, i, "would like to abort")) {
955         if (appData.zippyAbort ||
956             (gameMode == IcsPlayingWhite && whiteTimeRemaining < 0) ||
957             (gameMode == IcsPlayingBlack && blackTimeRemaining < 0)) {
958             SendToICS(ics_prefix);
959             SendToICS("abort\n");
960         } else {
961             SendToICS(ics_prefix);
962             if (appData.zippyTalk)
963               SendToICS("say Whoa no!  I am having FUN!!\n");
964             else
965               SendToICS("say Sorry, this computer doesn't accept aborts.\n");
966         }
967         return TRUE;
968     }
969
970     if (looking_at(buf, i, "requests adjournment") ||
971         looking_at(buf, i, "would like to adjourn")) {
972       if (appData.zippyAdjourn) {
973         SendToICS(ics_prefix);
974         SendToICS("adjourn\n");
975       } else {
976         SendToICS(ics_prefix);
977         if (appData.zippyTalk)
978           SendToICS("say Whoa no!  I am having FUN playing NOW!!\n");
979         else
980           SendToICS("say Sorry, this computer doesn't accept adjourns.\n");
981       }
982       return TRUE;
983     }
984
985     return FALSE;
986 }
987
988 /* Initialize chess program with data from the first board 
989  * of a new or resumed game.
990  */
991 void ZippyFirstBoard(moveNum, basetime, increment)
992      int moveNum, basetime, increment;
993 {
994     char buf[MSG_SIZ];
995     int w, b;
996     char *opp = (gameMode==IcsPlayingWhite ? gameInfo.black : gameInfo.white);
997     Boolean sentPos = FALSE;
998     char *bookHit = NULL; // [HGM] book
999
1000     if (!first.initDone) {
1001       /* Game is starting prematurely.  We can't deal with this */
1002       SendToICS(ics_prefix);
1003       SendToICS("abort\n");
1004       SendToICS(ics_prefix);
1005       SendToICS("say Sorry, the chess program is not initialized yet.\n");
1006       return;
1007     }
1008
1009     /* Send the variant command if needed */
1010     if (gameInfo.variant != VariantNormal) {
1011       sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
1012       SendToProgram(buf, &first);
1013     }
1014
1015     if ((startedFromSetupPosition && moveNum == 0) ||
1016         (!appData.getMoveList && moveNum > 0)) {
1017       SendToProgram("force\n", &first);
1018       SendBoard(&first, moveNum);
1019       sentPos = TRUE;
1020     }
1021
1022     sprintf(buf, "level 0 %d %d\n", basetime, increment);
1023     SendToProgram(buf, &first);
1024
1025     /* Count consecutive games from one opponent */
1026     if (strcmp(opp, zippyLastOpp) == 0) {
1027       zippyConsecGames++;
1028     } else {
1029       zippyConsecGames = 1;
1030       strcpy(zippyLastOpp, opp);
1031     }
1032
1033     /* Send the "computer" command if the opponent is in the list
1034        we've been gathering. */
1035     for (w=0; w<num_opps; w++) {
1036         if (!strcmp(opp_name[w], opp)) {
1037             SendToProgram(first.computerString, &first);
1038             break;
1039         }
1040     }
1041
1042     /* Ratings might be < 0 which means "we haven't seen a ratings
1043        message from ICS." Send 0 in that case */
1044     w = (gameInfo.whiteRating >= 0) ? gameInfo.whiteRating : 0;
1045     b = (gameInfo.blackRating >= 0) ? gameInfo.blackRating : 0;
1046     
1047     firstMove = FALSE;
1048     if (gameMode == IcsPlayingWhite) {
1049         if (first.sendName) {
1050           sprintf(buf, "name %s\n", gameInfo.black);
1051           SendToProgram(buf, &first);
1052         }
1053         strcpy(ics_handle, gameInfo.white);
1054         sprintf(buf, "rating %d %d\n", w, b);
1055         SendToProgram(buf, &first);
1056         if (sentPos) {
1057             /* Position sent above, engine is in force mode */
1058             if (WhiteOnMove(moveNum)) {
1059               /* Engine is on move now */
1060               if (first.sendTime) {
1061                 if (first.useColors) {
1062                   SendToProgram("black\n", &first); /*gnu kludge*/
1063                   SendTimeRemaining(&first, TRUE);
1064                   SendToProgram("white\n", &first);
1065                 } else {
1066                   SendTimeRemaining(&first, TRUE);
1067                 }
1068               }
1069               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1070             } else {
1071                 /* Engine's opponent is on move now */
1072                 if (first.usePlayother) {
1073                   if (first.sendTime) {
1074                     SendTimeRemaining(&first, TRUE);
1075                   }
1076                   SendToProgram("playother\n", &first);
1077                 } else {
1078                   /* Need to send a "go" after opponent moves */
1079                   firstMove = TRUE;
1080                 }
1081             }
1082         } else {
1083             /* Position not sent above, move list might be sent later */
1084             if (moveNum == 0) {
1085                 /* No move list coming; at start of game */
1086               if (first.sendTime) {
1087                 if (first.useColors) {
1088                   SendToProgram("black\n", &first); /*gnu kludge*/
1089                   SendTimeRemaining(&first, TRUE);
1090                   SendToProgram("white\n", &first);
1091                 } else {
1092                   SendTimeRemaining(&first, TRUE);
1093                 }
1094               }
1095 //            SendToProgram("go\n", &first);
1096               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1097             }
1098         }
1099     } else if (gameMode == IcsPlayingBlack) {
1100         if (first.sendName) {
1101           sprintf(buf, "name %s\n", gameInfo.white);
1102           SendToProgram(buf, &first);
1103         }
1104         strcpy(ics_handle, gameInfo.black);
1105         sprintf(buf, "rating %d %d\n", b, w);
1106         SendToProgram(buf, &first);
1107         if (sentPos) {
1108             /* Position sent above, engine is in force mode */
1109             if (!WhiteOnMove(moveNum)) {
1110                 /* Engine is on move now */
1111               if (first.sendTime) {
1112                 if (first.useColors) {
1113                   SendToProgram("white\n", &first); /*gnu kludge*/
1114                   SendTimeRemaining(&first, FALSE);
1115                   SendToProgram("black\n", &first);
1116                 } else {
1117                   SendTimeRemaining(&first, FALSE);
1118                 }
1119               }
1120 //            SendToProgram("go\n", &first);
1121               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1122             } else {
1123                 /* Engine's opponent is on move now */
1124                 if (first.usePlayother) {
1125                   if (first.sendTime) {
1126                     SendTimeRemaining(&first, FALSE);
1127                   }
1128                   SendToProgram("playother\n", &first);
1129                 } else {
1130                   /* Need to send a "go" after opponent moves */
1131                   firstMove = TRUE;
1132                 }
1133             }
1134         } else {
1135             /* Position not sent above, move list might be sent later */
1136             /* Nothing needs to be done here */
1137         }       
1138     }
1139
1140     if(bookHit) { // [HGM] book: simulate book reply
1141         static char bookMove[MSG_SIZ]; // a bit generous?
1142
1143         programStats.depth = programStats.nodes = programStats.time = 
1144         programStats.score = programStats.got_only_move = 0;
1145         sprintf(programStats.movelist, "%s (xbook)", bookHit);
1146
1147         strcpy(bookMove, "move ");
1148         strcat(bookMove, bookHit);
1149         HandleMachineMove(bookMove, &first);
1150     }
1151 }
1152
1153
1154 void
1155 ZippyHoldings(white_holding, black_holding, new_piece)
1156      char *white_holding, *black_holding, *new_piece;
1157 {
1158     char buf[MSG_SIZ];
1159     if (gameMode != IcsPlayingBlack && gameMode != IcsPlayingWhite) return;
1160     sprintf(buf, "holding [%s] [%s] %s\n",
1161             white_holding, black_holding, new_piece);
1162     SendToProgram(buf, &first);
1163 }