Change name of multi-PV option and version number
[fairymax.git] / fairymax.c
1 /***************************************************************************/\r
2 /*                               fairy-Max,                                */\r
3 /* Version of the sub-2KB (source) micro-Max Chess program, fused to a     */\r
4 /* generic WinBoard interface, loading its move-generator tables from file */\r
5 /***************************************************************************/\r
6 \r
7      /*****************************************************************/\r
8      /*                      LICENCE NOTIFICATION                     */\r
9      /* Fairy-Max 4.8 is free software, and you have my permission do */\r
10      /* with it whatever you want, whether it is commercial or not.   */\r
11      /* Note, however, that Fairy-Max can easily be configured through*/\r
12      /* its fmax.ini file to play Chess variants that are legally pro-*/\r
13      /* tected by patents, and that to do so would also require per-  */\r
14      /* mission of the holders of such patents. No guarantees are     */\r
15      /* given that Fairy-Max does anything in particular, or that it  */\r
16      /* would not wreck the hardware it runs on, and running it is    */\r
17      /* entirely for your own risk.  H.G,Muller, author of Fairy-Max  */\r
18      /*****************************************************************/\r
19 \r
20 #define MULTIPATH\r
21 #define VERSION "4.8N"\r
22 \r
23 #include <stdio.h>\r
24 #include <stdlib.h>\r
25 #include <string.h>\r
26 #include <signal.h>\r
27 #include <time.h>\r
28 \r
29 #ifndef INI_FILE \r
30 #define INI_FILE "fmax.ini"\r
31 #endif\r
32 \r
33 #ifdef WIN32 \r
34 #    include <windows.h>\r
35 #else\r
36 #    include <sys/time.h>\r
37      int GetTickCount() // with thanks to Tord\r
38      {  struct timeval t;\r
39         gettimeofday(&t, NULL);\r
40         return t.tv_sec*1000 + t.tv_usec/1000;\r
41      }\r
42 #endif\r
43 \r
44 int StartKey;\r
45 \r
46 #define EMPTY -1\r
47 #define WHITE 0\r
48 #define BLACK 16\r
49 \r
50 #define STATE 128\r
51 \r
52 /* The following macros indicate the differences between Fairy-Max and its */\r
53 /* dedicated Shatranj derivative ShaMax so that these can now be compiled  */\r
54 /* from the same unified source file.                                      */\r
55 /* Compile with gcc option -DSHATRANJ to build ShaMax.                     */\r
56 #ifdef SHATRANJ\r
57 #    define FAC 175\r
58 #    define EG  13\r
59 #    define NAME "ShaMax"\r
60 #    define SHAMAX(x) x\r
61 #    define FMAX(x)\r
62 #else\r
63 #    define FAC 128\r
64 #    define EG  10\r
65 #    define NAME "Fairy-Max"\r
66 #    define SHAMAX(x)\r
67 #    define FMAX(x) x\r
68 #endif\r
69 \r
70 /* make unique integer from engine move representation */\r
71 #define PACK_MOVE 256*K + L;\r
72 \r
73 /* convert intger argument back to engine move representation */\r
74 #define UNPACK_MOVE(A) K = (A)>>8 & 255; L = (A) & 255;\r
75 \r
76 /* Global variables visible to engine. Normally they */\r
77 /* would be replaced by the names under which these  */\r
78 /* are known to your engine, so that they can be     */\r
79 /* manipulated directly by the interface.            */\r
80 \r
81 int Side;\r
82 int Move;\r
83 int PromPiece;\r
84 int Result;\r
85 int TimeLeft;\r
86 int MovesLeft;\r
87 int MaxDepth;\r
88 int Post;\r
89 int Fifty;\r
90 int UnderProm;\r
91 int GameNr;\r
92 int Resign;\r
93 int Threshold = 800;\r
94 int Score;\r
95 char piecename[32], piecetype[32];\r
96 char *inifile = INI_FILE;\r
97 \r
98 int Ticks, tlim, Setup, SetupQ;\r
99 \r
100 int GameHistory[1024];\r
101 char HistoryBoards[1024][STATE], setupPosition[131];\r
102 int GamePtr, HistPtr;\r
103 \r
104 #define W while\r
105 #define K(A,B) *(int*)(T+A+S*(B&31))\r
106 #define J(A) K(y+A,b[y])-K(x+A,u)-K(H+A,t)\r
107 \r
108 int U=(1<<23)-1;\r
109 struct _ {int K,V;char X,Y,D,F;} *A;           /* hash table, 16M+8 entries*/\r
110 \r
111 int M=136,S=128,I=8e3,Q,O,K,N,j,R,J,Z,LL,      /* M=0x88                   */\r
112 BW,BH,sh,\r
113 w[16]={0,2,2,-1,7,8,12,23,7,5},                /* relative piece values    */\r
114 o[256],\r
115 oo[32],                                        /* initial piece setup      */\r
116 of[256],\r
117 od[16];                                        /* 1st dir. in o[] per piece*/\r
118 \r
119 signed char L,pl[17],\r
120 b[513],                                        /* board: 16x8+dummy, + PST */\r
121 T[4104],                                       /* hash translation table   */\r
122 centr[32],\r
123 n[]=".*XKNBRQEWFMACHG?x+knbrqewfmachg";        /* piece symbols on printout*/\r
124 \r
125 int pv[10000],*sp=pv; // triangular array\r
126 int margin;\r
127 \r
128 pboard()\r
129 {int i;\r
130  i=-1;W(++i<128)printf(" %c",(i&15)==BW&&(i+=15-BW)?10:n[b[i]&31]);\r
131 }\r
132          \r
133 \r
134 D(k,q,l,e,E,z,n)        /* recursive minimax search, k=moving side, n=depth*/\r
135 int k,q,l,e,E,z,n;      /* (q,l)=window, e=current eval. score, E=e.p. sqr.*/\r
136 {                       /* e=score, z=prev.dest; J,Z=hashkeys; return score*/\r
137  int j,r,m,v,d,h,i,F,G,P,V,f=J,g=Z,C,s,flag,FF,*ps=sp;\r
138  signed char t,p,u,x,y,X,Y,H,B;\r
139  struct _*a=A+(J+(k+S)*E&U-1);                 /* lookup pos. in hash table*/\r
140  *sp++=0;\r
141  q-=q<e;l-=l<=e;                               /* adj. window: delay bonus */\r
142  d=a->D;m=a->V;X=a->F;Y=a->Y;                  /* resume at stored depth   */\r
143  if(a->K-Z|z&S  |                              /* miss: other pos. or empty*/\r
144   !(m<=q|X&8&&m>=l|X&S))                       /*   or window incompatible */\r
145   d=Y=0;                                       /* start iter. from scratch */\r
146  X=a->X;                                       /* start at best-move hint  */\r
147  W(d++<n||d<3||              /*** min depth = 2   iterative deepening loop */\r
148    z&S&&K==I&&(GetTickCount()-Ticks<tlim&d<=MaxDepth|| /* root: deepen upto time   */\r
149    (K=X,L=Y&~S,Score=m,d=3)))                  /* time's up: go do best    */\r
150  {x=B=X;                                       /* start scan at prev. best */\r
151   h=Y&S;                                       /* request try noncastl. 1st*/\r
152   P=d>2&&l+I?D(16-k,-l,1-l,-e,2*S,2*S,d-3):I;  /* search null move         */\r
153   m=-P<l|R<5?d-2?-I:e:-P;   /*** prune if > beta  unconsidered:static eval */\r
154   SHAMAX( if(pl[k]<=1&pl[16-k]>1)m=I-1; )      /* bare king loses          */\r
155   N++;                                         /* node count (for timing)  */\r
156   do{u=b[x];                                   /* scan board looking for   */\r
157    if(u&&(u&16)==k)                            /*  own piece (inefficient!)*/\r
158    {r=p=u&15;                                  /* p = piece type (set r>0) */\r
159     j=od[p];                                   /* first step vector f.piece*/\r
160     W(r=o[++j])                                /* loop over directions o[] */\r
161     {A:                                        /* resume normal after best */\r
162      flag=h?3:of[j];                           /* move modes (for fairies) */\r
163      y=x;F=FF=G=S;                             /* (x,y)=move, (F,G)=castl.R*/\r
164      do{                                       /* y traverses ray, or:     */\r
165       H=y=h?Y^h:y+r;                           /* sneak in prev. best move */\r
166       if(flag&1<<8)H=y=(y&15)>13?y+BW:(y&15)>=BW?y-BW:y; /* cylinder board */\r
167       if(y&S|(y&15)>=BW)break;                 /* board edge hit           */\r
168 #ifdef MULTIPATH\r
169       if(flag&1<<9)                            /* if multipath move        */\r
170       {t=flag>>12;                             /* get dir. stepped twice   */\r
171        if(b[x+t]){if(b[y-2*t]|b[y-t])break;}else \r
172        if(b[x+2*t]&&b[y-t])break;              /* test if empty path exists*/\r
173       }\r
174 #endif\r
175       m=E<16|(E^112)<16&&flag&1&y-E<2&E-y<2?I:m;      /* bad castling  */\r
176       if(p<3&y==E)H=z&127;                     /* shift capt.sqr. H if e.p.*/\r
177       t=b[H];\r
178       if(flag&1+!t)                            /* mode (capt/nonc) allowed?*/\r
179       {if(t&&(t&16)==k)break;                  /* capture own              */\r
180        i=w[t&15]+((t&192)>>sh);                /* value of capt. piece t   */\r
181        if(i<0)m=I,d=98;                        /* K capture                */\r
182        if(m>=l&d>1)goto C;                     /* abort on fail high       */\r
183        v=d-1?e:i-p;                            /*** MVV/LVA scoring if d=1**/\r
184        if(d-!t>1)                              /*** all captures if d=2  ***/\r
185        {v=centr[p]?b[x+257]-b[y+257]:0;        /* center positional pts.   */\r
186         b[G]=b[H]=b[x]=0;b[y]=u|32;            /* do move, set non-virgin  */\r
187         if(!(G&S))b[FF]=k+6,v+=50;             /* castling: put R & score  */\r
188         v-=w[p]>0|R<EG?0:20;                   /*** freeze K in mid-game ***/\r
189         if(p<3)                                /* pawns:                   */\r
190         {v-=9*((x-2&M||b[x-2]-u)+              /* structure, undefended    */\r
191                (x+2&M||b[x+2]-u)               /*        squares plus bias */\r
192               +(w[b[x^16]&15]<0))              /*** cling to magnetic K ***/\r
193               +(R-76>>2);                      /* end-game Pawn-push bonus */\r
194          b[y]+=V=y+r+1&S?647-p:2*(u&y+16&32);  /* upgrade P or convert to Q*/\r
195          V>>=sh;                               /* for Shatranj promo to F  */\r
196          i+=V;                                 /* promotion / passer bonus */\r
197         } if(z&S && GamePtr<6) v+=(rand()>>10&31)-16;\r
198         J+=J(0);Z+=J(4)+G-S;\r
199         SHAMAX( pl[k]-=!!t; )                  /* count pieces per side    */\r
200         v+=e+i;V=m>q?m:q;                      /*** new eval & alpha    ****/\r
201         if(z&S)V=m-margin>q?m-margin:q;        /* multiPV                  */\r
202         C=d-1-(d>5&p>2&!t&!h);                 /* nw depth, reduce non-cpt.*/\r
203         C=R<EG|P-I|d<3||t&&p-3?C:d;            /* extend 1 ply if in-check */\r
204         do\r
205          s=C>2|v>V?-D(16-k,-l,-V,-v,/*** futility, recursive eval. of reply */\r
206                                      F,y&255,C):v;\r
207         W(s>q&++C<d); v=s;                     /* no fail:re-srch unreduced*/\r
208         if(v>V&v<l){int *p=sp;\r
209          sp=ps+1;\r
210          W(*sp++=*p++);\r
211          *ps=256*x+y;\r
212         }\r
213         if(z&S&&K-I)                           /* move pending: check legal*/\r
214         {if(v+I&&x==K&y==L)                    /*   if move found          */\r
215          {Q=-e-i;O=F;LL=L;\r
216           if(b[y]-u&15)b[y]-=PromPiece,        /* under-promotion, correct */\r
217                        J+=PromPiece;           /*  piece & invalidate hash */\r
218           a->D=99;a->V=0;                      /* lock game in hash as draw*/\r
219           R-=i/FAC;                            /*** total captd material ***/\r
220           Fifty = t|p<3?0:Fifty+1;\r
221           sp=ps;\r
222                      return l;}                /*   & not in check, signal */\r
223          v=m;                                  /* (prevent fail-lows on    */\r
224         }                                      /*   K-capt. replies)       */\r
225         J=f;Z=g;\r
226         SHAMAX( pl[k]+=!!t; )\r
227         b[G]=k+6;b[FF]=b[y]=0;b[x]=u;b[H]=t;   /* undo move,G can be dummy */\r
228        }                                       /*          if non-castling */\r
229        if(z&S&&Post&v>V&v<l){int *p=ps;char X,Y;\r
230         printf("%2d ",d-2);\r
231         printf("%6d ",v);\r
232         printf("%8d %10d",(GetTickCount()-Ticks)/10,N);\r
233         while(*p){X=*p>>8;Y=*p++;\r
234         printf(" %c%c%c%c",'a'+(X&15),'8'-(X>>4),'a'+(Y&15),'8'-(Y>>4&7));}\r
235         printf("\n");fflush(stdout);\r
236        }       if(v>m)                                 /* new best, update max,best*/\r
237         m=v,X=x,Y=y|S&F;                       /* mark non-double with S   */\r
238        if(h){h=0;goto A;}                      /* redo after doing old best*/\r
239       }\r
240       s=t;\r
241       if(flag&15^4|u&32||                      /* no double or moved before*/\r
242          p>2&&                                 /* no P & no lateral K move,*/\r
243          (b[G=r<0?x&~15:BW-1|x&112]-k-6        /* no virgin R in corner G, */\r
244          ||b[G^1]|b[G^2]|b[FF=r<0?G+3:G-2])    /* no 2 empty sq. next to R */\r
245         )t+=flag&4;                            /* fake capt. for nonsliding*/\r
246       else F=y;                                /* enable e.p.              */\r
247       if(s&&flag&8)t=0,flag^=flag>>4&15;       /* hoppers go to next phase */\r
248       if(!(flag&S))                            /* zig-zag piece?           */\r
249        r^=flag>>12,flag^=flag>>4&15;           /* alternate vector & mode  */\r
250      }W(!t);                                   /* if not capt. continue ray*/\r
251    }}\r
252    if((++x&15)>=BW)x=x+16&112;                 /* next sqr. of board, wrap */\r
253   }W(x-B);           \r
254 C:FMAX( m=m+I|P==I?m:(X=Y=0); )                /* if stalemate, draw-score */\r
255   if(a->D<99)                                  /* protect game history     */\r
256    a->K=Z,a->V=m,a->D=d,a->X=X,                /* always store in hash tab */\r
257    a->F=8*(m>q)|S*(m<l),a->Y=Y;                /* move, type (bound/exact),*/\r
258   }                                            /*    encoded in X S,8 bits */\r
259 if(z&4*S)K=X,L=Y&~S;\r
260  sp=ps;\r
261  return m+=m<e;                                /* delayed-loss bonus       */\r
262 }\r
263 \r
264 \r
265 /* Generic main() for Winboard-compatible engine     */\r
266 /* (Inspired by TSCP)                                */\r
267 /* Author: H.G. Muller                               */\r
268 \r
269 /* The engine is invoked through the following       */\r
270 /* subroutines, that can draw on the global vaiables */\r
271 /* that are maintained by the interface:             */\r
272 /* Side         side to move                         */\r
273 /* Move         move input to or output from engine  */\r
274 /* PromPiece    requested piece on promotion move    */\r
275 /* TimeLeft     ms left to next time control         */\r
276 /* MovesLeft    nr of moves to play within TimeLeft  */\r
277 /* MaxDepth     search-depth limit in ply            */\r
278 /* Post         boolean to invite engine babble      */\r
279 \r
280 /* InitEngine() progran start-up initialization      */\r
281 /* InitGame()   initialization to start new game     */\r
282 /*              (sets Side, but not time control)    */\r
283 /* Think()      think up move from current position  */\r
284 /*              (leaves move in Move, can be invalid */\r
285 /*               if position is check- or stalemate) */\r
286 /* DoMove()     perform the move in Move             */\r
287 /*              (togglese Side)                      */\r
288 /* ReadMove()   convert input move to engine format  */\r
289 /* PrintMove()  print Move on standard output        */\r
290 /* Legal()      check Move for legality              */\r
291 /* ClearBoard() make board empty                     */\r
292 /* PutPiece()   put a piece on the board             */\r
293 \r
294 /* define this to the codes used in your engine,     */\r
295 /* if the engine hasn't defined it already.          */\r
296 \r
297 int PrintResult(int s)\r
298 {\r
299         int i, j, k, cnt=0;\r
300 \r
301         /* search last 50 states with this stm for third repeat */\r
302         for(j=2; j<=100 && j <= HistPtr; j+=2)\r
303         {\r
304             for(k=0; k<STATE; k++)\r
305                 if(HistoryBoards[HistPtr][k] !=\r
306                    HistoryBoards[HistPtr-j&1023][k] )\r
307                    {\r
308                      goto differs;}\r
309             /* is the same, count it */\r
310             if(++cnt > 1) /* third repeat */\r
311             {\r
312                 printf("1/2-1/2 {Draw by repetition}\n");\r
313                 return 1;\r
314             }\r
315           differs: ;\r
316         }\r
317         K=I;\r
318         cnt = D(s,-I,I,Q,O,LL|4*S,3);\r
319         if(cnt>-I+1 && K==0 && L==0) {\r
320                 printf("1/2-1/2 {Stalemate}\n");\r
321                 return 2;\r
322         }\r
323         if(cnt==-I+1) {\r
324                 if (s == WHITE)\r
325                         printf("0-1 {Black mates}\n");\r
326                 else\r
327                         printf("1-0 {White mates}\n");\r
328                 return 3;\r
329         }\r
330         if(Fifty >=100) {\r
331                 printf("1/2-1/2 {Draw by fifty move rule}\n");\r
332                 return 4;\r
333         }\r
334 #ifdef SHATRANJ\r
335         if(pl[s]==1 && pl[16-s]==1) {\r
336                 printf("1/2-1/2 {Insufficient mating material}\n");\r
337                 return 4;\r
338         }\r
339         if(pl[s]<=1 && pl[16-s]>1) {\r
340                 if (s == BLACK)\r
341                         printf("0-1 {Bare King}\n");\r
342                 else\r
343                         printf("1-0 {Bare King}\n");\r
344                 return 5;\r
345         }\r
346 #endif\r
347         return 0;\r
348 }\r
349 \r
350 \r
351 InitEngine()\r
352 {\r
353  int i, j;\r
354 \r
355  N=32*S+7;W(N-->S+3)T[N]=rand()>>9;\r
356  srand(GetTickCount());\r
357 }\r
358 \r
359 InitGame()\r
360 {\r
361  int i,j;\r
362 \r
363  for(i=0;i<16*BH;i++)b[i]=0;\r
364  K=BW;W(K--)\r
365  {b[K]=oo[K+16]+16;b[K+112]=oo[K];b[K+16]=18;b[K+96]=1; /* initial board setup*/\r
366   L=8;W(L--)b[16*L+K+257]=(K-BW/2)*(K-BW/2)+(L-3.5)*(L-3.5); /* center-pts table   */\r
367  }                                                   /*(in unused half b[])*/\r
368  Side = WHITE; Q=0; O=S;\r
369  Fifty = 0; R = 0;\r
370  for(i=0; i<BW; i++) if(i!=3) R += (w[oo[i]]/FAC) + (w[oo[i+16]]/FAC);\r
371  UnderProm = -1; pl[WHITE] = pl[BLACK] = 2*BW;\r
372 }\r
373 \r
374 void CopyBoard(int s)\r
375 {\r
376         int i, j, k, cnt=0;\r
377 \r
378         /* copy game representation of engine to HistoryBoard */\r
379         /* don't forget castling rights and e.p. state!       */\r
380         for(i=0; i<BH; i++)\r
381         for(j=0; j<BW; j++)                 /* board squares  */\r
382             HistoryBoards[s][BW*i+j] = b[16*i+j]|64*(16*i+j==O);\r
383 }\r
384                                          \r
385 void PrintVariants()\r
386 {\r
387         int i, j, count=0; char c, buf[80];\r
388         FILE *f;\r
389 \r
390         f = fopen(INI_FILE, "r");\r
391         if(f==NULL) return;\r
392 \r
393         /* search for game names in definition file */\r
394         do {\r
395            while(fscanf(f, "Game: %s", buf) != 1 && c != EOF) \r
396                while((c = fgetc(f)) != EOF && c != '\n');\r
397            if(c == EOF) break;\r
398            if(count++) printf(",");\r
399            printf("%s", buf);\r
400         } while(c != EOF);\r
401 \r
402         fclose(f);\r
403 }\r
404 \r
405 void PrintOptions()\r
406 {\r
407         printf("feature option=\"Resign -check %d\"\n", Resign);\r
408         printf("feature option=\"Resign Threshold -spin %d 200 1200\"\n", Threshold);\r
409         printf("feature option=\"Ini File -file %s\"\n", inifile);\r
410         printf("feature option=\"Multi-PV Margin -spin %d 0 1000\"\n", margin);\r
411         printf("feature option=\"Playing Style ;-) -combo Brilliant /// *Brave /// Beautiful\"\n");\r
412         printf("feature option=\"Dummy Slider Example -slider 20 0 100\"\n");\r
413         printf("feature option=\"Dummy String Example -file happy birthday!\"\n");\r
414         printf("feature option=\"Dummy Path Example -path .\"\n");\r
415         printf("feature option=\"Clear Hash -button\"\n");\r
416         printf("feature done=1\n");\r
417 }\r
418                                          \r
419 int LoadGame(char *name)\r
420 {\r
421         int i, j, count=0; char c, buf[80];\r
422         static int currentVariant;\r
423         FILE *f;\r
424 \r
425         f = fopen(inifile, "r");\r
426         if(f==NULL)\r
427         {   printf("telluser piece-desription file '%s'  not found\n", inifile);\r
428             exit(0);\r
429         }\r
430         if(fscanf(f, "version 4.8(%c)", &c)!=1 || c != 'w')\r
431         { printf("telluser incompatible fmax.ini file\n"); exit(0); }\r
432 \r
433         if(name != NULL)\r
434         {  /* search for game name in definition file */\r
435            while(fscanf(f, "Game: %s", buf)!=1 || strcmp(name, buf) ) {\r
436                while((c = fgetc(f)) != EOF && c != '\n');\r
437                count++;\r
438                if(c == EOF) {\r
439                    printf("telluser variant %s not supported\n", name);\r
440                    fclose(f);\r
441                    return; /* keep old settings */\r
442                }\r
443            }\r
444            currentVariant = count;\r
445         }\r
446 \r
447         /* We have found variant, or if none specified, are at beginning of file */\r
448         if(fscanf(f, "%dx%d", &BW, &BH)!=2 || BW>12 || BH!=8)\r
449         { printf("telluser unsupported board size %dx%d\n",BW,BH); exit(0); }\r
450 \r
451         for(i=0; i<BW; i++) fscanf(f, "%d", oo+i);\r
452         for(i=0; i<BW; i++) fscanf(f, "%d", oo+i+16);\r
453         for(i= 0; i<=U; i++)\r
454             A[i].K = A[i].D = A[i].X = A[i].Y = A[i].F = 0; /* clear hash */\r
455         for(i=0; i<32; i++) piecetype[i] = 0;\r
456 \r
457         i=0; j=-1; c=0;\r
458         while(fscanf(f, "%d,%x", o+j, of+j)==2 ||\r
459                                       fscanf(f,"%c:%d",&c, w+i+1)==2)\r
460         {   if(c)\r
461             { od[++i]=j; centr[i] = c>='a';\r
462               piecetype[c&31]=i; piecename[i]=c&31;\r
463             }\r
464             j++; o[j]=0;\r
465             /* printf("# c='%c' i=%d od[i]=%d j=%d (%3d,%8x)\n",c?c:' ',i,od[i],j,o[j-1],of[j-1]); /**/\r
466             c=0; if(i>15 || j>255) break;\r
467         }\r
468 \r
469         fclose(f);\r
470         sh = w[7] < 250 ? 3 : 0;\r
471 }\r
472 \r
473 int main(int argc, char **argv)\r
474 {\r
475         int Computer, MaxTime, MaxMoves, TimeInc, sec, i, j;\r
476         char line[256], command[256], c, cc;\r
477         int m, nr;\r
478         FILE *f;\r
479 \r
480         if(argc>1 && sscanf(argv[1], "%d", &m)==1)\r
481         { U = (1<<m)-1; argc--; argv++; }\r
482         A = (struct _ *) calloc(U+1, sizeof(struct _));\r
483         if(argc>1) inifile = argv[1];\r
484 \r
485         signal(SIGINT, SIG_IGN);\r
486         printf("tellics say     " NAME " " VERSION "\n");\r
487         printf("tellics say     by H.G. Muller\n");\r
488         printf("tellics say Gothic Chess is protected by U.S. patent #6,481,716 by Ed Trice.\n");\r
489         printf("tellics say Falcon Chess is protected by U.S. patent #5,690,334 by George W. Duke\n");\r
490         InitEngine();\r
491         LoadGame(NULL);\r
492         InitGame();\r
493         Computer = EMPTY;\r
494         MaxTime  = 10000;  /* 10 sec */\r
495         MaxDepth = 30;     /* maximum depth of your search */\r
496 \r
497         for (;;) {\r
498                 fflush(stdout);\r
499                 if (Side == Computer) {\r
500                         /* think up & do move, measure time used  */\r
501                         /* it is the responsibility of the engine */\r
502                         /* to control its search time based on    */\r
503                         /* MovesLeft, TimeLeft, MaxMoves, TimeInc */\r
504                         /* Next 'MovesLeft' moves have to be done */\r
505                         /* within TimeLeft+(MovesLeft-1)*TimeInc  */\r
506                         /* If MovesLeft<0 all remaining moves of  */\r
507                         /* the game have to be done in this time. */\r
508                         /* If MaxMoves=1 any leftover time is lost*/\r
509                         Ticks = GetTickCount();\r
510                         m = MovesLeft<=0 ? 40 : MovesLeft;\r
511                         tlim = (0.6-0.06*(BW-8))*(TimeLeft+(m-1)*TimeInc)/(m+7);\r
512                         if(tlim>TimeLeft/15) tlim = TimeLeft/15;\r
513                         PromPiece = 0; /* Always promote to Queen ourselves */\r
514                         N=0;K=I;\r
515                         if (D(Side,-I,I,Q,O,LL|S,3)==I) {\r
516                             Side ^= BLACK^WHITE;\r
517                             if(UnderProm>=0 && UnderProm != L)\r
518                             {    printf("tellics I hate under-promotions!\n");\r
519                                  printf("resign { underpromotion } \n");\r
520                                  Computer = EMPTY;\r
521                                  continue;\r
522                             } else UnderProm = -1;\r
523                             printf("move ");\r
524                             printf("%c%c%c%c",'a'+(K&15),'0'+BH-(K>>4),\r
525                                           'a'+(L&15),'0'+BH-(L>>4));\r
526                             printf("\n");\r
527                             m = GetTickCount() - Ticks;\r
528 \r
529                             /* time-control accounting */\r
530                             TimeLeft -= m;\r
531                             TimeLeft += TimeInc;\r
532                             if(--MovesLeft == 0) {\r
533                                 MovesLeft = MaxMoves;\r
534                                 if(MaxMoves == 1)\r
535                                      TimeLeft  = MaxTime;\r
536                                 else TimeLeft += MaxTime;\r
537                             }\r
538 \r
539                             GameHistory[GamePtr++] = PACK_MOVE;\r
540                             CopyBoard(HistPtr=HistPtr+1&1023);\r
541                             if(Resign && Score <= -Threshold) { \r
542                                 printf("resign\n"); Computer=EMPTY;\r
543                             } else if(PrintResult(Side))\r
544                                 Computer = EMPTY;\r
545                         } else {\r
546                             if(!PrintResult(Side))\r
547                                 printf("resign { refuses own move }\n");\r
548                             Computer = EMPTY;\r
549                         }\r
550                         continue;\r
551                 }\r
552                 if (!fgets(line, 256, stdin))\r
553                         return;\r
554                 if (line[0] == '\n')\r
555                         continue;\r
556                 sscanf(line, "%s", command);\r
557                 if (!strcmp(command, "xboard"))\r
558                         continue;\r
559                 if (!strcmp(command, "protover")) {\r
560                         printf("feature myname=\"" NAME " " VERSION "\"\n");\r
561                         printf("feature memory=1\n");\r
562                         printf("feature setboard=0 ping=1 done=0\n");\r
563                         printf("feature variants=\"");\r
564                         PrintVariants();\r
565                         printf("\"\n");\r
566                         PrintOptions();\r
567                         continue;\r
568                 }\r
569                 if (!strcmp(command, "ping")) { int nr=0;\r
570                         sscanf(line, "ping %d", &nr);\r
571                         printf("pong %d\n", nr);\r
572                         continue;\r
573                 }\r
574                 if (!strcmp(command, "p")) {\r
575                         pboard();\r
576                         continue;\r
577                 }\r
578                 if (!strcmp(command, "memory")) {\r
579                         int mem, mask;\r
580                         sscanf(line+6, "%d", &mem); mem = (mem*1024*1024)/12; // max nr of hash entries\r
581                         mask = 0x7FFFFFFF; while(mask > mem) mask >>= 1;\r
582                         if(mask != U) {\r
583                             free(A); U = mask;\r
584                             A = (struct _ *) calloc(U+1, sizeof(struct _));\r
585                         }\r
586                         continue;\r
587                 }\r
588                 if (!strcmp(command, "new")) {\r
589                         /* start new game */\r
590                         LoadGame("normal");\r
591                         InitGame();\r
592                         GamePtr   = Setup = 0;\r
593                         GameNr++;\r
594                         HistPtr   = 0;\r
595                         Computer  = BLACK;\r
596                         TimeLeft  = MaxTime;\r
597                         MovesLeft = MaxMoves;\r
598                         for(nr=0; nr<1024; nr++)\r
599                             for(m=0; m<STATE; m++)\r
600                                 HistoryBoards[nr][m] = 0;\r
601                         continue;\r
602                 }\r
603                 if (!strcmp(command, "quit"))\r
604                         /* exit engine */\r
605                         return;\r
606                 if (!strcmp(command, "force")) {\r
607                         /* computer plays neither */\r
608                         Computer = EMPTY;\r
609                         continue;\r
610                 }\r
611                 if (!strcmp(command, "white")) {\r
612                         /* set white to move in current position */\r
613                         Side     = WHITE;\r
614                         Computer = BLACK;\r
615                         continue;\r
616                 }\r
617                 if (!strcmp(command, "black")) {\r
618                         /* set blck to move in current position */\r
619                         Side     = BLACK;\r
620                         Computer = WHITE;\r
621                         continue;\r
622                 }\r
623                 if (!strcmp(command, "st")) {\r
624                         /* move-on-the-bell mode     */\r
625                         /* indicated by MaxMoves = 1 */\r
626                         sscanf(line, "st %d", &MaxTime);\r
627                         MovesLeft = MaxMoves = 1;\r
628                         TimeLeft  = MaxTime *= 1000;\r
629                         TimeInc   = 0;\r
630                         continue;\r
631                 }\r
632                 if (!strcmp(command, "sd")) {\r
633                         /* set depth limit (remains in force */\r
634                         /* until next 'sd n' command)        */\r
635                         sscanf(line, "sd %d", &MaxDepth);\r
636                         MaxDepth += 2; /* QS depth */\r
637                         continue;\r
638                 }\r
639                 if (!strcmp(command, "level")) {\r
640                         /* normal or blitz time control */\r
641                         sec = 0;\r
642                         if(sscanf(line, "level %d %d %d",\r
643                                  &MaxMoves, &MaxTime, &TimeInc)!=3 &&\r
644                            sscanf(line, "level %d %d:%d %d",\r
645                                  &MaxMoves, &MaxTime, &sec, &TimeInc)!=4)\r
646                              continue;\r
647                         MovesLeft = MaxMoves;\r
648                         TimeLeft  = MaxTime = 60000*MaxTime + 1000*sec;\r
649                         TimeInc  *= 1000;\r
650                         continue;\r
651                 }\r
652                 if (!strcmp(command, "time")) {\r
653                         /* set time left on clock */\r
654                         sscanf(line, "time %d", &TimeLeft);\r
655                         TimeLeft  *= 10; /* centi-sec to ms */\r
656                         continue;\r
657                 }\r
658                 if (!strcmp(command, "otim")) {\r
659                         /* opponent's time (not kept, so ignore) */\r
660                         continue;\r
661                 }\r
662                 if (!strcmp(command, "easy")) {\r
663                         continue;\r
664                 }\r
665                 if (!strcmp(command, "hard")) {\r
666                         continue;\r
667                 }\r
668                 if (!strcmp(command, "accepted")) {\r
669                         continue;\r
670                 }\r
671                 if (!strcmp(command, "rejected")) {\r
672                         continue;\r
673                 }\r
674                 if (!strcmp(command, "random")) {\r
675                         continue;\r
676                 }\r
677                 if (!strcmp(command, "option")) {\r
678                         int i; static char filename[80];\r
679                         if(sscanf(line+7, "Resign=%d", &Resign) == 1) continue;\r
680                         if(sscanf(line+7, "Resign Threshold=%d", &Threshold) == 1) continue;\r
681                         if(sscanf(line+7, "Ini File=%s", filename) == 1) {\r
682                                 inifile = filename; continue;\r
683                         }\r
684                         if(sscanf(line+7, "Clear Hash") == 1) for(i=0; i<U; i++) A->K = 0;\r
685                         if(sscanf(line+7, "MultiVariation Margin=%d", &margin) == 1) continue;\r
686                         continue;\r
687                 }\r
688                 if (!strcmp(command, "go")) {\r
689                         /* set computer to play current side to move */\r
690                         Computer = Side;\r
691                         MovesLeft = -(GamePtr+(Side==WHITE)>>1);\r
692                         while(MaxMoves>0 && MovesLeft<=0)\r
693                             MovesLeft += MaxMoves;\r
694                         continue;\r
695                 }\r
696                 if (!strcmp(command, "hint")) {\r
697                         Ticks = GetTickCount(); tlim = 1000;\r
698                         D(Side,-I,I,Q,O,LL|4*S,6);\r
699                         if (K==0 && L==0)\r
700                                 continue;\r
701                         printf("Hint: ");\r
702                         printf("%c%c%c%c",'a'+(K&7),'8'-(K>>4),\r
703                                           'a'+(L&7),'8'-(L>>4));\r
704                         printf("\n");\r
705                         continue;\r
706                 }\r
707                 if (!strcmp(command, "undo")   && (nr=1) ||\r
708                     !strcmp(command, "remove") && (nr=2)   ) {\r
709                         /* 'take back' moves by replaying game */\r
710                         /* from history until desired ply      */\r
711                         if (GamePtr - nr < 0)\r
712                                 continue;\r
713                         GamePtr -= nr;\r
714                         HistPtr -= nr;   /* erase history boards */\r
715                         while(nr-- > 0)  \r
716                             for(m=0; m<STATE; m++)\r
717                                 HistoryBoards[HistPtr+nr+1&1023][m] = 0;\r
718                         InitGame();\r
719                         if(Setup) {\r
720                             for(i=0; i<128; i++) b[i] = setupPosition[i];\r
721                             Side = setupPosition[128]; Q = SetupQ;\r
722                             pl[WHITE] = setupPosition[129];\r
723                             pl[BLACK] = setupPosition[130];\r
724                         }\r
725                         for(i=0; i<=U; i++) A[i].D = A[i].K = 0; // clear hash table\r
726                         for(nr=0; nr<GamePtr; nr++) {\r
727                             UNPACK_MOVE(GameHistory[nr]);\r
728                             D(Side,-I,I,Q,O,LL|S,3);\r
729                             Side ^= BLACK^WHITE;\r
730                         }\r
731                         continue;\r
732                 }\r
733                 if (!strcmp(command, "post")) {\r
734                         Post = 1;\r
735                         continue;\r
736                 }\r
737                 if (!strcmp(command, "nopost")) {\r
738                         Post = 0;\r
739                         continue;\r
740                 }\r
741                 if (!strcmp(command, "variant")) {\r
742                         sscanf(line, "variant %s", command);\r
743                         LoadGame(command);\r
744                         InitGame(); Setup = 0;\r
745                         continue;\r
746                 }\r
747                 if (!strcmp(command, "edit")) {\r
748                         int color = WHITE, p;\r
749 \r
750                         while(fgets(line, 256, stdin)) {\r
751                                 m = line[0];\r
752                                 if(m=='.') break;\r
753                                 if(m=='#') {\r
754                                         for(i=0; i<128; i++) b[i]=0;\r
755                                         Q=0; R=0; O=S;\r
756                                         pl[WHITE]=pl[BLACK]=0;\r
757                                         continue;\r
758                                 }\r
759                                 if(m=='c') {\r
760                                         color = WHITE+BLACK - color;\r
761                                         Q = -Q;\r
762                                         continue;\r
763                                 }\r
764                                 if( m >= 'A' && m <= 'Z' && piecetype[m&31]\r
765                                     && line[1] >= 'a' && line[1] <= 'a'+BW-1\r
766                                     && line[2] >= '1' && line[2] <= '0'+BH) {\r
767                                         m = line[1]-16*line[2]+799;\r
768                                         switch(p = piecetype[line[0]&31])\r
769                                         {\r
770                                         case 1:\r
771                                         case 2:\r
772                                             if(color==WHITE)\r
773                                                  b[m]=(m&0x70)==0x60?1:33,\r
774                                                  Q+=w[1];\r
775                                             else b[m]=(m&0x70)==0x10?18:50,\r
776                                                  Q+=w[2];\r
777                                             break;\r
778                                         case 3: // can castle, normally King\r
779                                             b[m]=3+color+32;\r
780                                             if(m==BW>>1        && color==BLACK ||\r
781                                                m==0x70+(BW>>1) && color==WHITE)\r
782                                                 b[m] -= 32;\r
783                                             break;\r
784                                         case 6: // can castle, normally Rook\r
785                                             b[m]=6+color+32;\r
786                                             if((m==0x00 || m==BW-1   ) && color==BLACK ||\r
787                                                (m==0x70 || m==0x6F+BW) && color==WHITE)\r
788                                                 b[m] -= 32;\r
789                                             Q+=w[6]; R+=w[6]/FAC;\r
790                                             break;\r
791                                         default:\r
792                                             b[m]=p+color;\r
793                                             Q+=w[p]; R+=w[p]/FAC;\r
794                                                     case 0: // undefined piece, ignore\r
795                                             break;\r
796                                         }\r
797                                         pl[BLACK+WHITE-color]++;\r
798                                         continue;\r
799                                 }\r
800                         }\r
801                         if(Side != color) Q = -Q;\r
802                         GamePtr = HistPtr = 0; Setup = 1; SetupQ = Q; // start anew\r
803                         for(i=0; i<128; i++) setupPosition[i] = b[i]; // remember position\r
804                         setupPosition[128] = Side;\r
805                         setupPosition[129] = pl[WHITE];\r
806                         setupPosition[130] = pl[BLACK];\r
807                         continue;\r
808                 }\r
809                 /* command not recognized, assume input move */\r
810                 m = line[0]<'a' | line[0]>='a'+BW | line[1]<'1' | line[1]>='1'+BH |\r
811                     line[2]<'a' | line[2]>='a'+BW | line[3]<'1' | line[3]>='1'+BH;\r
812                 if(line[4] == '\n') line[4] = piecename[7];\r
813                 PromPiece = 7 - piecetype[line[4]&31];\r
814                     if(PromPiece == 7) PromPiece = 0;\r
815                 {char *c=line; K=c[0]-16*c[1]+799;L=c[2]-16*c[3]+799; }\r
816                 if (m)\r
817                         /* doesn't have move syntax */\r
818                         printf("Error (unknown command): %s\n", command);\r
819                 else if(D(Side,-I,I,Q,O,LL|S,3)!=I) {\r
820                         /* did have move syntax, but illegal move */\r
821                         printf("Illegal move:%s\n", line);\r
822                 } else {  /* legal move, perform it */\r
823                         GameHistory[GamePtr++] = PACK_MOVE;\r
824                         Side ^= BLACK^WHITE;\r
825                         CopyBoard(HistPtr=HistPtr+1&1023);\r
826                         if(PrintResult(Side)) Computer = EMPTY;\r
827                 }\r
828         }\r
829 }\r