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