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