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