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