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