cleaned up an old #ifdef in zippy
[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     /* Possibly reject Crafty as opponent */
416     if (appData.zippyPlay && appData.zippyNoplayCrafty && forwardMostMove < 4
417         && looking_at(buf, i, "* kibitzes: Hello from Crafty")) 
418     {
419         player = StripHighlightAndTitle(star_match[0]);
420         if ((gameMode == IcsPlayingWhite &&
421              StrCaseCmp(player, gameInfo.black) == 0) ||
422             (gameMode == IcsPlayingBlack &&
423              StrCaseCmp(player, gameInfo.white) == 0)) {
424
425           sprintf(reply, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n",
426                   ics_prefix, ics_prefix, ics_prefix, player);
427           SendToICS(reply);
428         }
429         return TRUE;
430     }
431
432     /* If this is a computer, save the name.  Then later, once the */
433     /* game is really started, we will send the "computer" notice to */
434     /* the engine.  */ 
435     if (appData.zippyPlay &&
436         looking_at(buf, i, "* is in the computer list")) {
437         int i;
438         for (i=0;i<num_opps;i++)
439           if (!strcmp(opp_name[i],star_match[0])) break;
440         if (i >= num_opps) strcpy(opp_name[num_opps++],star_match[0]);
441     }
442     if (appData.zippyPlay && looking_at(buf, i, "* * is a computer *")) {
443         int i;
444         for (i=0;i<num_opps;i++)
445           if (!strcmp(opp_name[i],star_match[1])) break;
446         if (i >= num_opps) strcpy(opp_name[num_opps++],star_match[1]);
447     }
448
449     /* Tells and says */
450     if (appData.zippyPlay && 
451         (looking_at(buf, i, "* offers to be your bughouse partner") ||
452          looking_at(buf, i, "* tells you: [automatic message] I chose you"))) {
453         player = StripHighlightAndTitle(star_match[0]);
454         if (appData.zippyBughouse > 1 && first.initDone) {
455             sprintf(reply, "%spartner %s\n", ics_prefix, player);
456             SendToICS(reply);
457             if (strcmp(zippyPartner, player) != 0) {
458                 strcpy(zippyPartner, player);
459                 SendToProgram(reply + strlen(ics_prefix), &first);
460             }
461         } else if (appData.zippyBughouse > 0) {
462             sprintf(reply, "%sdecline %s\n", ics_prefix, player);
463             SendToICS(reply);
464         } else {
465             sprintf(reply, "%stell %s This computer cannot play bughouse\n",
466                     ics_prefix, player);
467             SendToICS(reply);
468         }
469         return TRUE;
470     }
471
472     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
473         looking_at(buf, i, "* agrees to be your partner")) {
474         player = StripHighlightAndTitle(star_match[0]);
475         sprintf(reply, "partner %s\n", player);
476         if (strcmp(zippyPartner, player) != 0) {
477             strcpy(zippyPartner, player);
478             SendToProgram(reply, &first);
479         }
480         return TRUE;
481     }
482
483     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
484         (looking_at(buf, i, "are no longer *'s partner") ||
485          looking_at(buf, i,
486                     "* tells you: [automatic message] I'm no longer your"))) {
487         player = StripHighlightAndTitle(star_match[0]);
488         if (strcmp(zippyPartner, player) == 0) {
489             zippyPartner[0] = NULLCHAR;
490             SendToProgram("partner\n", &first);
491         }
492         return TRUE;
493     }
494
495     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
496         (looking_at(buf, i, "no longer have a bughouse partner") ||
497          looking_at(buf, i, "partner has disconnected") ||
498          looking_at(buf, i, "partner has just chosen a new partner"))) {
499       zippyPartner[0] = NULLCHAR;
500       SendToProgram("partner\n", &first);
501       return TRUE;
502     }
503
504     if (appData.zippyPlay && appData.zippyBughouse && first.initDone &&
505         looking_at(buf, i, "* (your partner) tells you: *")) {
506         /* This pattern works on FICS but not ICC */
507         player = StripHighlightAndTitle(star_match[0]);
508         if (strcmp(zippyPartner, player) != 0) {
509             strcpy(zippyPartner, player);
510             sprintf(reply, "partner %s\n", player);
511             SendToProgram(reply, &first);
512         }
513         sprintf(reply, "ptell %s\n", star_match[1]);
514         SendToProgram(reply, &first);
515         return TRUE;
516     }
517
518     if (looking_at(buf, i, "* tells you: *") ||
519         looking_at(buf, i, "* says: *")) 
520     {
521         player = StripHighlightAndTitle(star_match[0]);
522         if (appData.zippyPassword[0] != NULLCHAR &&
523             strncmp(star_match[1], appData.zippyPassword,
524                     strlen(appData.zippyPassword)) == 0) {
525             p = star_match[1] + strlen(appData.zippyPassword);
526             while (*p == ' ') p++;
527             SendToICS(p);
528             SendToICS("\n");
529         } else if (appData.zippyPassword2[0] != NULLCHAR && first.initDone &&
530             strncmp(star_match[1], appData.zippyPassword2,
531                     strlen(appData.zippyPassword2)) == 0) {
532             p = star_match[1] + strlen(appData.zippyPassword2);
533             while (*p == ' ') p++;
534             SendToProgram(p, &first);
535             SendToProgram("\n", &first);
536         } else if (appData.zippyWrongPassword[0] != NULLCHAR &&
537             strncmp(star_match[1], appData.zippyWrongPassword,
538                     strlen(appData.zippyWrongPassword)) == 0) {
539             p = star_match[1] + strlen(appData.zippyWrongPassword);
540             while (*p == ' ') p++;
541             sprintf(reply, "wrong %s\n", player);
542             SendToICS(reply);
543         } else if (appData.zippyBughouse && first.initDone &&
544                    strcmp(player, zippyPartner) == 0) {
545             SendToProgram("ptell ", &first);
546             SendToProgram(star_match[1], &first);
547             SendToProgram("\n", &first);
548         } else if (strncmp(star_match[1], HI, 6) == 0) {
549             extern char* programVersion;
550             sprintf(reply, "%stell %s %s\n",
551                     ics_prefix, player, programVersion);
552             SendToICS(reply);
553         } else if (strncmp(star_match[1], "W0W!! ", 6) == 0) {
554             extern char* programVersion;
555             sprintf(reply, "%stell %s %s\n", ics_prefix,
556                     player, programVersion);
557             SendToICS(reply);
558         } else if (appData.zippyTalk && (((unsigned) random() % 10) < 9)) {
559             if (strcmp(player, ics_handle) != 0) {
560                 Speak("tell", player);
561             }
562         }
563
564         ColorizeEx( ColorTell, FALSE );
565
566         return TRUE;
567     }
568
569     if( appData.colorize && looking_at(buf, i, "* (*) seeking") ) {
570         ColorizeEx(ColorSeek, FALSE);
571         return FALSE;
572     }
573
574     if (looking_at(buf, i, "* spoofs you:")) {
575         player = StripHighlightAndTitle(star_match[0]);
576         sprintf(reply, "spoofedby %s\n", player);
577         SendToICS(reply);
578     }
579
580     return FALSE;
581 }
582
583 int ZippyConverse(buf, i)
584      char *buf;
585      int *i;
586 {
587     static char lastgreet[MSG_SIZ];
588     char reply[MSG_SIZ];
589     int oldi;
590
591     /* Shouts and emotes */
592     if (looking_at(buf, i, "--> * *") ||
593         looking_at(buf, i, "* shouts: *")) 
594     {
595       if (appData.zippyTalk) {
596         char *player = StripHighlightAndTitle(star_match[0]);
597         if (strcmp(player, ics_handle) == 0) {
598             return TRUE;
599         } else if (appData.zippyPinhead[0] != NULLCHAR &&
600                    StrCaseStr(star_match[1], appData.zippyPinhead) != NULL) {
601             sprintf(reply, "insult %s\n", player);
602             SendToICS(reply);
603         } else if (ZippyCalled(star_match[1])) {
604             Speak("shout", NULL);
605         }
606       }
607
608       ColorizeEx(ColorShout, FALSE);
609
610       return TRUE;
611     }
612
613     if (looking_at(buf, i, "* kibitzes: *")) {
614       if (appData.zippyTalk && ((unsigned) random() % 10) < 9) {
615         char *player = StripHighlightAndTitle(star_match[0]);
616         if (strcmp(player, ics_handle) != 0) {
617             Speak("kibitz", NULL);
618         }
619       }
620
621       ColorizeEx(ColorKibitz, FALSE);
622
623       return TRUE;
624     }
625
626     if (looking_at(buf, i, "* whispers: *")) {
627       if (appData.zippyTalk && ((unsigned) random() % 10) < 9) {
628         char *player = StripHighlightAndTitle(star_match[0]);
629         if (strcmp(player, ics_handle) != 0) {
630             Speak("whisper", NULL);
631         }
632       }
633
634       ColorizeEx(ColorKibitz, FALSE);
635
636       return TRUE;
637     }
638
639     /* Messages */
640     if ((looking_at(buf, i, ". * (*:*): *") && isdigit(star_match[1][0])) ||
641          looking_at(buf, i, ". * at *:*: *")) {
642       if (appData.zippyTalk) {
643         FILE *f;
644         char *player = StripHighlightAndTitle(star_match[0]);
645
646         if (strcmp(player, ics_handle) != 0) {
647             if (((unsigned) random() % 10) < 9)
648               Speak("message", player);
649             f = fopen("zippy.messagelog", "a");
650             fprintf(f, "%s (%s:%s): %s\n", player,
651                     star_match[1], star_match[2], star_match[3]);
652             fclose(f);
653         }
654       }
655       return TRUE;
656     }
657
658     /* Channel tells */
659     oldi = *i;
660     if (looking_at(buf, i, "*(*: *")) {
661         char *player;
662         char *channel;
663         if (star_match[0][0] == NULLCHAR  ||
664             strchr(star_match[0], ' ') ||
665             strchr(star_match[1], ' ')) {
666             /* Oops, did not want to match this; probably a message */
667             *i = oldi;
668             return FALSE;
669         }
670         if (appData.zippyTalk) {
671           player = StripHighlightAndTitle(star_match[0]);
672           channel = strrchr(star_match[1], '(');
673           if (channel == NULL) {
674             channel = star_match[1];
675           } else {
676             channel++;
677           }
678           channel[strlen(channel)-1] = NULLCHAR;
679
680           /* Tell to the channel only if someone mentions our name */
681           if (ZippyCalled(star_match[2])) {
682             Speak("tell", channel);
683           }
684
685           ColorizeEx( atoi(channel) == 1 ? ColorChannel1 : ColorChannel, FALSE );
686         }
687         return TRUE;
688     }
689
690     if (!appData.zippyTalk) return FALSE;
691
692     if ((looking_at(buf, i, "You have * message") &&
693          atoi(star_match[0]) != 0) ||
694         looking_at(buf, i, "* has left a message for you") ||
695         looking_at(buf, i, "* just sent you a message")) {
696         sprintf(reply, "%smessages\n%sclearmessages *\n",
697                 ics_prefix, ics_prefix);
698         SendToICS(reply);
699         return TRUE;
700     }
701
702     if (looking_at(buf, i, "Notification: * has arrived")) {
703         if (((unsigned) random() % 3) == 0) {
704             char *player = StripHighlightAndTitle(star_match[0]);
705             strcpy(lastgreet, player);
706             sprintf(reply, "greet %s\n", player);
707             SendToICS(reply);
708             Speak("tell", player);
709         }
710     }   
711
712     if (looking_at(buf, i, "Notification: * has departed")) {
713         if (((unsigned) random() % 3) == 0) {
714             char *player = StripHighlightAndTitle(star_match[0]);
715             sprintf(reply, "farewell %s\n", player);
716             SendToICS(reply);
717         }
718     }   
719
720     if (looking_at(buf, i, "Not sent -- * is censoring you")) {
721         char *player = StripHighlightAndTitle(star_match[0]);
722         if (strcmp(player, lastgreet) == 0) {
723             sprintf(reply, "%s-notify %s\n", ics_prefix, player);
724             SendToICS(reply);
725         }
726     }   
727
728     if (looking_at(buf, i, "command is currently turned off")) {
729         appData.zippyUseI = 0;
730     }
731
732     return FALSE;
733 }
734
735 void ZippyGameStart(white, black)
736      char *white, *black;
737 {
738     if (!first.initDone) {
739       /* Game is starting prematurely.  We can't deal with this */
740       SendToICS(ics_prefix);
741       SendToICS("abort\n");
742       SendToICS(ics_prefix);
743       SendToICS("say Sorry, the chess program is not initialized yet.\n");
744       return;
745     }
746
747     if (appData.zippyGameStart[0] != NULLCHAR) {
748       SendToICS(appData.zippyGameStart);
749       SendToICS("\n");
750     }
751 }
752
753 void ZippyGameEnd(result, resultDetails)
754      ChessMove result;
755      char *resultDetails;
756 {
757     if (appData.zippyAcceptOnly[0] == NULLCHAR &&
758         appData.zippyGameEnd[0] != NULLCHAR) {
759       SendToICS(appData.zippyGameEnd);
760       SendToICS("\n");
761     }
762     zippyLastGameEnd = time(0);
763     if(forwardMostMove < appData.zippyShortGame) 
764         strcpy(zippyOffender, zippyLastOpp); else zippyOffender[0] = 0; // [HGM] aborter
765 }
766
767 /*
768  * Routines to implement Zippy playing chess
769  */
770
771 void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent)
772      char *srated, *swild, *sbase, *sincrement, *opponent;
773 {
774     char buf[MSG_SIZ];
775     int base, increment, i=0;
776     char rated;
777     VariantClass variant;
778     char *varname;
779
780     rated = srated[0];
781     variant = StringToVariant(swild);
782     varname = VariantName(variant);
783     base = atoi(sbase);
784     increment = atoi(sincrement);
785
786     /* [DM] If icsAnalyzeEngine active we don't accept automatic games */
787     if (appData.icsActive && appData.icsEngineAnalyze) return;
788
789     /* If desired, you can insert more code here to decline matches
790        based on rated, variant, base, and increment, but it is
791        easier to use the ICS formula feature instead. */
792
793     if (variant == VariantLoadable) {
794         sprintf(buf,
795          "%stell %s This computer can't play wild type %s\n%sdecline %s\n",
796                 ics_prefix, opponent, swild, ics_prefix, opponent);
797         SendToICS(buf);
798         return;
799     }
800     if (StrStr(appData.zippyVariants, varname) == NULL ||
801               ((i=first.protocolVersion) != 1 && StrStr(first.variants, varname) == NULL) /* [HGM] zippyvar */
802                                                           ) {
803         sprintf(buf,
804          "%stell %s This computer can't play %s [%s], only %s\n%sdecline %s\n",
805                 ics_prefix, opponent, swild, varname, 
806                 i ? first.variants : appData.zippyVariants,                               /* [HGM] zippyvar */
807                 ics_prefix, opponent);
808         SendToICS(buf);
809         return;
810     }
811
812     /* Are we blocking match requests from all but one person? */
813     if (appData.zippyAcceptOnly[0] != NULLCHAR &&
814         StrCaseCmp(opponent, appData.zippyAcceptOnly)) {
815         /* Yes, and this isn't him.  Ignore challenge. */
816         return;
817     }
818     
819     /* Too many consecutive games with same opponent?  If so, make him
820        wait until someone else has played or a timeout has elapsed. */
821     if (appData.zippyMaxGames &&
822         strcmp(opponent, zippyLastOpp) == 0 &&
823         zippyConsecGames >= appData.zippyMaxGames &&
824         difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
825       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",
826               ics_prefix, opponent, zippyConsecGames, ics_handle,
827               appData.zippyReplayTimeout, ics_prefix, opponent);
828       SendToICS(buf);
829       return;
830     }
831
832     /* [HGM] aborter: opponent is cheater that aborts games he doesn't like on first move. Make him wait */
833     if (strcmp(opponent, zippyOffender) == 0 &&
834         difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
835       sprintf(buf, "%stell %s Sorry, your previous game against %s was rather short. "
836                    " It will wait %d seconds to see if a tougher opponent comes along.\n%sdecline %s\n",
837               ics_prefix, opponent, ics_handle,
838               appData.zippyReplayTimeout, ics_prefix, opponent);
839       SendToICS(buf);
840       return;
841     }
842
843     /* Engine not yet initialized or still thinking about last game? */
844     if (!first.initDone || first.lastPing != first.lastPong) {
845       sprintf(buf, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n",
846               ics_prefix, opponent, ics_prefix, opponent);
847       SendToICS(buf);
848       return;
849     }
850
851     sprintf(buf, "%saccept %s\n", ics_prefix, opponent);
852     SendToICS(buf);
853     if (appData.zippyTalk) {
854       Speak("tell", opponent);
855     }
856 }
857
858
859 /* Accept matches */
860 int ZippyMatch(buf, i)
861      char *buf;
862      int *i;
863 {
864     if (looking_at(buf, i, "* * match * * requested with * (*)")) {
865
866         ZippyHandleChallenge(star_match[0], star_match[1],
867                              star_match[2], star_match[3],
868                              StripHighlightAndTitle(star_match[4]));
869         return TRUE;
870     }
871
872     /* Old FICS 0-increment form */
873     if (looking_at(buf, i, "* * match * requested with * (*)")) {
874
875         ZippyHandleChallenge(star_match[0], star_match[1],
876                              star_match[2], "0",
877                              StripHighlightAndTitle(star_match[3]));
878         return TRUE;
879     }
880
881     if (looking_at(buf, i,
882                    "* has made an alternate proposal of * * match * *.")) {
883
884         ZippyHandleChallenge(star_match[1], star_match[2],
885                              star_match[3], star_match[4],
886                              StripHighlightAndTitle(star_match[0]));
887         return TRUE;
888     }
889
890     /* FICS wild/nonstandard forms */
891     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * Loaded from *")) {
892         /* note: star_match[2] can include "[white] " or "[black] "
893            before our own name. */
894         if(star_match[8] == NULL || star_match[8][0] == 0) // [HGM] chessd: open-source ICS has file on next line
895              ZippyHandleChallenge(star_match[4], star_match[5],
896                              star_match[6], star_match[7],                           StripHighlightAndTitle(star_match[0]));
897         else ZippyHandleChallenge(star_match[4], star_match[8],
898                              star_match[6], star_match[7],
899                              StripHighlightAndTitle(star_match[0]));
900         return TRUE;
901     }
902
903     if (looking_at(buf, i,
904                    "Challenge: * (*) *(*) * * * * : * * Loaded from *")) {
905         /* note: star_match[2] can include "[white] " or "[black] "
906            before our own name. */
907         ZippyHandleChallenge(star_match[4], star_match[10],
908                              star_match[8], star_match[9],
909                              StripHighlightAndTitle(star_match[0]));
910         return TRUE;
911     }
912
913     /* Regular forms */
914     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * : * *") |
915         looking_at(buf, i, "Challenge: * (*) *(*) * * * * * *")) {
916         /* note: star_match[2] can include "[white] " or "[black] "
917            before our own name. */
918         ZippyHandleChallenge(star_match[4], star_match[5],
919                              star_match[8], star_match[9],
920                              StripHighlightAndTitle(star_match[0]));
921         return TRUE;
922     }
923
924     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * *")) {
925         /* note: star_match[2] can include "[white] " or "[black] "
926            before our own name. */
927         ZippyHandleChallenge(star_match[4], star_match[5],
928                              star_match[6], star_match[7],
929                              StripHighlightAndTitle(star_match[0]));
930         return TRUE;
931     }
932
933
934     if (ics_type == ICS_ICC) { // [DM]
935         if (looking_at(buf, i, "Your opponent offers you a draw")) {
936             if (first.sendDrawOffers && first.initDone)
937                 SendToProgram("draw\n", &first);
938             return TRUE;
939         }
940     } else {
941         if (looking_at(buf, i, "offers you a draw")) {
942             if (first.sendDrawOffers && first.initDone) {
943                 SendToProgram("draw\n", &first);
944             }
945             return TRUE;
946         }
947     }
948
949     if (looking_at(buf, i, "requests that the game be aborted") ||
950         looking_at(buf, i, "would like to abort")) {
951         if (appData.zippyAbort ||
952             (gameMode == IcsPlayingWhite && whiteTimeRemaining < 0) ||
953             (gameMode == IcsPlayingBlack && blackTimeRemaining < 0)) {
954             SendToICS(ics_prefix);
955             SendToICS("abort\n");
956         } else {
957             SendToICS(ics_prefix);
958             if (appData.zippyTalk)
959               SendToICS("say Whoa no!  I am having FUN!!\n");
960             else
961               SendToICS("say Sorry, this computer doesn't accept aborts.\n");
962         }
963         return TRUE;
964     }
965
966     if (looking_at(buf, i, "requests adjournment") ||
967         looking_at(buf, i, "would like to adjourn")) {
968       if (appData.zippyAdjourn) {
969         SendToICS(ics_prefix);
970         SendToICS("adjourn\n");
971       } else {
972         SendToICS(ics_prefix);
973         if (appData.zippyTalk)
974           SendToICS("say Whoa no!  I am having FUN playing NOW!!\n");
975         else
976           SendToICS("say Sorry, this computer doesn't accept adjourns.\n");
977       }
978       return TRUE;
979     }
980
981     return FALSE;
982 }
983
984 /* Initialize chess program with data from the first board 
985  * of a new or resumed game.
986  */
987 void ZippyFirstBoard(moveNum, basetime, increment)
988      int moveNum, basetime, increment;
989 {
990     char buf[MSG_SIZ];
991     int w, b;
992     char *opp = (gameMode==IcsPlayingWhite ? gameInfo.black : gameInfo.white);
993     Boolean sentPos = FALSE;
994     char *bookHit = NULL; // [HGM] book
995
996     if (!first.initDone) {
997       /* Game is starting prematurely.  We can't deal with this */
998       SendToICS(ics_prefix);
999       SendToICS("abort\n");
1000       SendToICS(ics_prefix);
1001       SendToICS("say Sorry, the chess program is not initialized yet.\n");
1002       return;
1003     }
1004
1005     /* Send the variant command if needed */
1006     if (gameInfo.variant != VariantNormal) {
1007       sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
1008       SendToProgram(buf, &first);
1009     }
1010
1011     if ((startedFromSetupPosition && moveNum == 0) ||
1012         (!appData.getMoveList && moveNum > 0)) {
1013       SendToProgram("force\n", &first);
1014       SendBoard(&first, moveNum);
1015       sentPos = TRUE;
1016     }
1017
1018     sprintf(buf, "level 0 %d %d\n", basetime, increment);
1019     SendToProgram(buf, &first);
1020
1021     /* Count consecutive games from one opponent */
1022     if (strcmp(opp, zippyLastOpp) == 0) {
1023       zippyConsecGames++;
1024     } else {
1025       zippyConsecGames = 1;
1026       strcpy(zippyLastOpp, opp);
1027     }
1028
1029     /* Send the "computer" command if the opponent is in the list
1030        we've been gathering. */
1031     for (w=0; w<num_opps; w++) {
1032         if (!strcmp(opp_name[w], opp)) {
1033             SendToProgram(first.computerString, &first);
1034             break;
1035         }
1036     }
1037
1038     /* Ratings might be < 0 which means "we haven't seen a ratings
1039        message from ICS." Send 0 in that case */
1040     w = (gameInfo.whiteRating >= 0) ? gameInfo.whiteRating : 0;
1041     b = (gameInfo.blackRating >= 0) ? gameInfo.blackRating : 0;
1042     
1043     firstMove = FALSE;
1044     if (gameMode == IcsPlayingWhite) {
1045         if (first.sendName) {
1046           sprintf(buf, "name %s\n", gameInfo.black);
1047           SendToProgram(buf, &first);
1048         }
1049         strcpy(ics_handle, gameInfo.white);
1050         sprintf(buf, "rating %d %d\n", w, b);
1051         SendToProgram(buf, &first);
1052         if (sentPos) {
1053             /* Position sent above, engine is in force mode */
1054             if (WhiteOnMove(moveNum)) {
1055               /* Engine is on move now */
1056               if (first.sendTime) {
1057                 if (first.useColors) {
1058                   SendToProgram("black\n", &first); /*gnu kludge*/
1059                   SendTimeRemaining(&first, TRUE);
1060                   SendToProgram("white\n", &first);
1061                 } else {
1062                   SendTimeRemaining(&first, TRUE);
1063                 }
1064               }
1065               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1066             } else {
1067                 /* Engine's opponent is on move now */
1068                 if (first.usePlayother) {
1069                   if (first.sendTime) {
1070                     SendTimeRemaining(&first, TRUE);
1071                   }
1072                   SendToProgram("playother\n", &first);
1073                 } else {
1074                   /* Need to send a "go" after opponent moves */
1075                   firstMove = TRUE;
1076                 }
1077             }
1078         } else {
1079             /* Position not sent above, move list might be sent later */
1080             if (moveNum == 0) {
1081                 /* No move list coming; at start of game */
1082               if (first.sendTime) {
1083                 if (first.useColors) {
1084                   SendToProgram("black\n", &first); /*gnu kludge*/
1085                   SendTimeRemaining(&first, TRUE);
1086                   SendToProgram("white\n", &first);
1087                 } else {
1088                   SendTimeRemaining(&first, TRUE);
1089                 }
1090               }
1091 //            SendToProgram("go\n", &first);
1092               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1093             }
1094         }
1095     } else if (gameMode == IcsPlayingBlack) {
1096         if (first.sendName) {
1097           sprintf(buf, "name %s\n", gameInfo.white);
1098           SendToProgram(buf, &first);
1099         }
1100         strcpy(ics_handle, gameInfo.black);
1101         sprintf(buf, "rating %d %d\n", b, w);
1102         SendToProgram(buf, &first);
1103         if (sentPos) {
1104             /* Position sent above, engine is in force mode */
1105             if (!WhiteOnMove(moveNum)) {
1106                 /* Engine is on move now */
1107               if (first.sendTime) {
1108                 if (first.useColors) {
1109                   SendToProgram("white\n", &first); /*gnu kludge*/
1110                   SendTimeRemaining(&first, FALSE);
1111                   SendToProgram("black\n", &first);
1112                 } else {
1113                   SendTimeRemaining(&first, FALSE);
1114                 }
1115               }
1116 //            SendToProgram("go\n", &first);
1117               bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
1118             } else {
1119                 /* Engine's opponent is on move now */
1120                 if (first.usePlayother) {
1121                   if (first.sendTime) {
1122                     SendTimeRemaining(&first, FALSE);
1123                   }
1124                   SendToProgram("playother\n", &first);
1125                 } else {
1126                   /* Need to send a "go" after opponent moves */
1127                   firstMove = TRUE;
1128                 }
1129             }
1130         } else {
1131             /* Position not sent above, move list might be sent later */
1132             /* Nothing needs to be done here */
1133         }       
1134     }
1135
1136     if(bookHit) { // [HGM] book: simulate book reply
1137         static char bookMove[MSG_SIZ]; // a bit generous?
1138
1139         programStats.depth = programStats.nodes = programStats.time = 
1140         programStats.score = programStats.got_only_move = 0;
1141         sprintf(programStats.movelist, "%s (xbook)", bookHit);
1142
1143         strcpy(bookMove, "move ");
1144         strcat(bookMove, bookHit);
1145         HandleMachineMove(bookMove, &first);
1146     }
1147 }
1148
1149
1150 void
1151 ZippyHoldings(white_holding, black_holding, new_piece)
1152      char *white_holding, *black_holding, *new_piece;
1153 {
1154     char buf[MSG_SIZ];
1155     if (gameMode != IcsPlayingBlack && gameMode != IcsPlayingWhite) return;
1156     sprintf(buf, "holding [%s] [%s] %s\n",
1157             white_holding, black_holding, new_piece);
1158     SendToProgram(buf, &first);
1159 }