Bugfix draw offer to engine if color zippy enable.
[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;\r
95 \r
96 extern void mysrandom(unsigned int seed);\r
97 extern int myrandom(void);
98 \r
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 desired, you can insert more code here to decline matches
748        based on rated, variant, base, and increment, but it is
749        easier to use the ICS formula feature instead. */
750
751     if (variant == VariantLoadable) {
752         sprintf(buf,
753          "%stell %s This computer can't play wild type %s\n%sdecline %s\n",
754                 ics_prefix, opponent, swild, ics_prefix, opponent);
755         SendToICS(buf);
756         return;
757     }
758     if (StrStr(appData.zippyVariants, varname) == NULL) {
759         sprintf(buf,
760          "%stell %s This computer can't play %s [%s], only %s\n%sdecline %s\n",
761                 ics_prefix, opponent, swild, varname, appData.zippyVariants,
762                 ics_prefix, opponent);
763         SendToICS(buf);
764         return;
765     }
766
767     /* Are we blocking match requests from all but one person? */
768     if (appData.zippyAcceptOnly[0] != NULLCHAR &&
769         StrCaseCmp(opponent, appData.zippyAcceptOnly)) {
770         /* Yes, and this isn't him.  Ignore challenge. */
771         return;
772     }
773
774     /* Too many consecutive games with same opponent?  If so, make him
775        wait until someone else has played or a timeout has elapsed. */
776     if (appData.zippyMaxGames &&
777         strcmp(opponent, zippyLastOpp) == 0 &&
778         zippyConsecGames >= appData.zippyMaxGames &&
779         difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) {
780       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",
781               ics_prefix, opponent, zippyConsecGames, ics_handle,
782               appData.zippyReplayTimeout, ics_prefix, opponent);
783       SendToICS(buf);
784       return;
785     }
786
787     /* Engine not yet initialized or still thinking about last game? */
788     if (!first.initDone || first.lastPing != first.lastPong) {
789       sprintf(buf, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n",
790               ics_prefix, opponent, ics_prefix, opponent);
791       SendToICS(buf);
792       return;
793     }
794
795     sprintf(buf, "%saccept %s\n", ics_prefix, opponent);
796     SendToICS(buf);
797     if (appData.zippyTalk) {
798       Speak("tell", opponent);
799     }
800 }
801
802
803 /* Accept matches */
804 int ZippyMatch(buf, i)
805      char *buf;
806      int *i;
807 {
808     if (looking_at(buf, i, "* * match * * requested with * (*)")) {
809
810         ZippyHandleChallenge(star_match[0], star_match[1],
811                              star_match[2], star_match[3],
812                              StripHighlightAndTitle(star_match[4]));
813         return TRUE;
814     }
815
816     /* Old FICS 0-increment form */
817     if (looking_at(buf, i, "* * match * requested with * (*)")) {
818
819         ZippyHandleChallenge(star_match[0], star_match[1],
820                              star_match[2], "0",
821                              StripHighlightAndTitle(star_match[3]));
822         return TRUE;
823     }
824
825     if (looking_at(buf, i,
826                    "* has made an alternate proposal of * * match * *.")) {
827
828         ZippyHandleChallenge(star_match[1], star_match[2],
829                              star_match[3], star_match[4],
830                              StripHighlightAndTitle(star_match[0]));
831         return TRUE;
832     }
833
834     /* FICS wild/nonstandard forms */
835     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * Loaded from *")) {
836         /* note: star_match[2] can include "[white] " or "[black] "
837            before our own name. */
838         ZippyHandleChallenge(star_match[4], star_match[8],
839                              star_match[6], star_match[7],
840                              StripHighlightAndTitle(star_match[0]));
841         return TRUE;
842     }
843
844     if (looking_at(buf, i,
845                    "Challenge: * (*) *(*) * * * * : * * Loaded from *")) {
846         /* note: star_match[2] can include "[white] " or "[black] "
847            before our own name. */
848         ZippyHandleChallenge(star_match[4], star_match[10],
849                              star_match[8], star_match[9],
850                              StripHighlightAndTitle(star_match[0]));
851         return TRUE;
852     }
853
854     /* Regular forms */
855     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * * : * *") |
856         looking_at(buf, i, "Challenge: * (*) *(*) * * * * * *")) {
857         /* note: star_match[2] can include "[white] " or "[black] "
858            before our own name. */
859         ZippyHandleChallenge(star_match[4], star_match[5],
860                              star_match[8], star_match[9],
861                              StripHighlightAndTitle(star_match[0]));
862         return TRUE;
863     }
864
865     if (looking_at(buf, i, "Challenge: * (*) *(*) * * * *")) {
866         /* note: star_match[2] can include "[white] " or "[black] "
867            before our own name. */
868         ZippyHandleChallenge(star_match[4], star_match[5],
869                              star_match[6], star_match[7],
870                              StripHighlightAndTitle(star_match[0]));
871         return TRUE;
872     }
873 \r
874         if (ics_type == ICS_ICC) {
875                 if (looking_at(buf, i, "Your opponent offers you a draw")) {\r
876                         if (first.sendDrawOffers && first.initDone)\r
877                                 SendToProgram("draw\n", &first);\r
878                         return TRUE;\r
879                 }\r
880         } else {\r
881             if (looking_at(buf, i, "offers you a draw")) {
882                 if (first.sendDrawOffers && first.initDone) {
883                         SendToProgram("draw\n", &first);
884                         }
885                         return TRUE;
886         }
887         }\r
888
889     if (looking_at(buf, i, "requests that the game be aborted") ||
890         looking_at(buf, i, "would like to abort")) {
891         if (appData.zippyAbort ||
892             (gameMode == IcsPlayingWhite && whiteTimeRemaining < 0) ||
893             (gameMode == IcsPlayingBlack && blackTimeRemaining < 0)) {
894             SendToICS(ics_prefix);
895             SendToICS("abort\n");
896         } else {
897             SendToICS(ics_prefix);
898             if (appData.zippyTalk)
899               SendToICS("say Whoa no!  I am having FUN!!\n");
900             else
901               SendToICS("say Sorry, this computer doesn't accept aborts.\n");
902         }
903         return TRUE;
904     }
905
906     if (looking_at(buf, i, "requests adjournment") ||
907         looking_at(buf, i, "would like to adjourn")) {
908       if (appData.zippyAdjourn) {
909         SendToICS(ics_prefix);
910         SendToICS("adjourn\n");
911       } else {
912         SendToICS(ics_prefix);
913         if (appData.zippyTalk)
914           SendToICS("say Whoa no!  I am having FUN playing NOW!!\n");
915         else
916           SendToICS("say Sorry, this computer doesn't accept adjourns.\n");
917       }
918       return TRUE;
919     }
920
921     return FALSE;
922 }
923
924 /* Initialize chess program with data from the first board
925  * of a new or resumed game.
926  */
927 void ZippyFirstBoard(moveNum, basetime, increment)
928      int moveNum, basetime, increment;
929 {
930     char buf[MSG_SIZ];
931     int w, b;
932     char *opp = (gameMode==IcsPlayingWhite ? gameInfo.black : gameInfo.white);
933     Boolean sentPos = FALSE;
934
935     if (!first.initDone) {
936       /* Game is starting prematurely.  We can't deal with this */
937       SendToICS(ics_prefix);
938       SendToICS("abort\n");
939       SendToICS(ics_prefix);
940       SendToICS("say Sorry, the chess program is not initialized yet.\n");
941       return;
942     }
943
944     /* Send the variant command if needed */
945     if (gameInfo.variant != VariantNormal) {
946       sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
947       SendToProgram(buf, &first);
948     }
949
950     if ((startedFromSetupPosition && moveNum == 0) ||
951         (!appData.getMoveList && moveNum > 0)) {
952       SendToProgram("force\n", &first);
953       SendBoard(&first, moveNum);
954       sentPos = TRUE;
955     }
956
957     sprintf(buf, "level 0 %d %d\n", basetime, increment);
958     SendToProgram(buf, &first);
959
960     /* Count consecutive games from one opponent */
961     if (strcmp(opp, zippyLastOpp) == 0) {
962       zippyConsecGames++;
963     } else {
964       zippyConsecGames = 1;
965       strcpy(zippyLastOpp, opp);
966     }
967
968     /* Send the "computer" command if the opponent is in the list
969        we've been gathering. */
970     for (w=0; w<num_opps; w++) {
971         if (!strcmp(opp_name[w], opp)) {
972             SendToProgram(first.computerString, &first);
973             break;
974         }
975     }
976
977     /* Ratings might be < 0 which means "we haven't seen a ratings
978        message from ICS." Send 0 in that case */
979     w = (gameInfo.whiteRating >= 0) ? gameInfo.whiteRating : 0;
980     b = (gameInfo.blackRating >= 0) ? gameInfo.blackRating : 0;
981
982     firstMove = FALSE;
983     if (gameMode == IcsPlayingWhite) {
984         if (first.sendName) {
985           sprintf(buf, "name %s\n", gameInfo.black);
986           SendToProgram(buf, &first);
987         }
988         strcpy(ics_handle, gameInfo.white);
989         sprintf(buf, "rating %d %d\n", w, b);
990         SendToProgram(buf, &first);
991         if (sentPos) {
992             /* Position sent above, engine is in force mode */
993             if (WhiteOnMove(moveNum)) {
994               /* Engine is on move now */
995               if (first.sendTime) {
996                 if (first.useColors) {
997                   SendToProgram("black\n", &first); /*gnu kludge*/
998                   SendTimeRemaining(&first, TRUE);
999                   SendToProgram("white\n", &first);
1000                 } else {
1001                   SendTimeRemaining(&first, TRUE);
1002                 }
1003               }
1004               SendToProgram("go\n", &first);
1005             } else {
1006                 /* Engine's opponent is on move now */
1007                 if (first.usePlayother) {
1008                   if (first.sendTime) {
1009                     SendTimeRemaining(&first, TRUE);
1010                   }
1011                   SendToProgram("playother\n", &first);
1012                 } else {
1013                   /* Need to send a "go" after opponent moves */
1014                   firstMove = TRUE;
1015                 }
1016             }
1017         } else {
1018             /* Position not sent above, move list might be sent later */
1019             if (moveNum == 0) {
1020                 /* No move list coming; at start of game */
1021               if (first.sendTime) {
1022                 if (first.useColors) {
1023                   SendToProgram("black\n", &first); /*gnu kludge*/
1024                   SendTimeRemaining(&first, TRUE);
1025                   SendToProgram("white\n", &first);
1026                 } else {
1027                   SendTimeRemaining(&first, TRUE);
1028                 }
1029               }
1030               SendToProgram("go\n", &first);
1031             }
1032         }
1033     } else if (gameMode == IcsPlayingBlack) {
1034         if (first.sendName) {
1035           sprintf(buf, "name %s\n", gameInfo.white);
1036           SendToProgram(buf, &first);
1037         }
1038         strcpy(ics_handle, gameInfo.black);
1039         sprintf(buf, "rating %d %d\n", b, w);
1040         SendToProgram(buf, &first);
1041         if (sentPos) {
1042             /* Position sent above, engine is in force mode */
1043             if (!WhiteOnMove(moveNum)) {
1044                 /* Engine is on move now */
1045               if (first.sendTime) {
1046                 if (first.useColors) {
1047                   SendToProgram("white\n", &first); /*gnu kludge*/
1048                   SendTimeRemaining(&first, FALSE);
1049                   SendToProgram("black\n", &first);
1050                 } else {
1051                   SendTimeRemaining(&first, FALSE);
1052                 }
1053               }
1054               SendToProgram("go\n", &first);
1055             } else {
1056                 /* Engine's opponent is on move now */
1057                 if (first.usePlayother) {
1058                   if (first.sendTime) {
1059                     SendTimeRemaining(&first, FALSE);
1060                   }
1061                   SendToProgram("playother\n", &first);
1062                 } else {
1063                   /* Need to send a "go" after opponent moves */
1064                   firstMove = TRUE;
1065                 }
1066             }
1067         } else {
1068             /* Position not sent above, move list might be sent later */
1069             /* Nothing needs to be done here */
1070         }
1071     }
1072 }
1073
1074
1075 void
1076 ZippyHoldings(white_holding, black_holding, new_piece)
1077      char *white_holding, *black_holding, *new_piece;
1078 {
1079     char buf[MSG_SIZ];
1080     if (gameMode != IcsPlayingBlack && gameMode != IcsPlayingWhite) return;
1081     sprintf(buf, "holding [%s] [%s] %s\n",
1082             white_holding, black_holding, new_piece);
1083     SendToProgram(buf, &first);
1084 }