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