Remove incremental-update code from HaChu
[hachu.git] / hachu.c
1 /**************************************************************************/\r
2 /*                               HaChu                                    */\r
3 /* A WinBoard engine for Chu Shogi (and some related games) by H.G.Muller */\r
4 /**************************************************************************/\r
5 /* This source code is released in the public domain                      */\r
6 /**************************************************************************/\r
7 \r
8 // TODO:\r
9 // in GenCapts we do not generate jumps of more than two squares yet\r
10 // promotions by pieces with Lion power stepping in & out the zone in same turn\r
11 // promotion on capture\r
12 \r
13 #define VERSION "0.16 k+ky"\r
14 \r
15 #define PATH level==0 /*|| path[0] == 0x3490a &&  (level==1 || path[1] == 0x285b3 && (level == 2 || path[2] == 0x8710f && (level == 3 /*|| path[3] == 0x3e865 && (level == 4 || path[4] == 0x4b865 && (level == 5)))))*/\r
16 //define PATH 0\r
17 \r
18 #define HASH\r
19 #define KILLERS\r
20 #define NULLMOVE\r
21 #define CHECKEXT\r
22 #define LMR 4\r
23 #define LIONTRAP\r
24 #define WINGS\r
25 #define KINGSAFETY\r
26 #define KSHIELD\r
27 #define XFORTRESS\r
28 #define PAWNBLOCK\r
29 #define KYLIN 100 /* extra end-game value of Kylin for promotability */\r
30 #define PROMO 0 /* extra bonus for 'vertical' piece when it actually promotes (diagonal pieces get half) */\r
31 \r
32 #include <stdio.h>\r
33 #include <stdlib.h>\r
34 #include <string.h>\r
35 #include <signal.h>\r
36 #include <time.h>\r
37 #include <stdint.h>\r
38 \r
39 #ifdef WIN32 \r
40 #    include <windows.h>\r
41      int InputWaiting()\r
42      {  // checks for waiting input in pipe\r
43         static int pipe, init;\r
44         static HANDLE inp;\r
45         DWORD cnt;\r
46 \r
47         if(!init) inp = GetStdHandle(STD_INPUT_HANDLE);\r
48         if(!PeekNamedPipe(inp, NULL, 0, NULL, &cnt, NULL)) return 1;\r
49         return cnt;\r
50     }\r
51 #else\r
52 #    include <sys/time.h>\r
53 #    include <sys/ioctl.h>\r
54      int InputWaiting()\r
55      {\r
56         int cnt;\r
57         if(ioctl(0, FIONREAD, &cnt)) return 1;\r
58         return cnt;\r
59      }\r
60      int GetTickCount() // with thanks to Tord\r
61      {  struct timeval t;\r
62         gettimeofday(&t, NULL);\r
63         return t.tv_sec*1000 + t.tv_usec/1000;\r
64      }\r
65 #endif\r
66 \r
67 #define BW bWidth\r
68 #define BH bHeight\r
69 #define BHMAX 16\r
70 #define BWMAX (2*BHMAX)\r
71 #define BSIZE BWMAX*BHMAX\r
72 #define ZONE  zone\r
73 \r
74 #define ONE (currentVariant == V_SHO || currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK)\r
75 \r
76 #define BLACK      0\r
77 #define WHITE      1\r
78 #define EMPTY      0\r
79 #define EDGE   (1<<11)\r
80 #define TYPE   (WHITE|BLACK|EDGE)\r
81 #define ABSENT  2047\r
82 #define INF     8000\r
83 #define NPIECES EDGE+1               /* length of piece list    */\r
84 \r
85 #define SQLEN    11                /* bits in square number   */\r
86 #define SQUARE  ((1<<SQLEN) - 1)   /* mask for square in move */\r
87 #define DEFER   (1<<2*SQLEN)       /* deferral on zone entry  */\r
88 #define PROMOTE (1<<2*SQLEN+1)     /* promotion bit in move   */\r
89 #define SPECIAL  1400              /* start of special moves  */\r
90 #define BURN    (SPECIAL + 96)     /* start of burn encodings */\r
91 #define STEP(X,Y) (BW*(X)+ (Y))\r
92 #define SORTKEY(X) 0\r
93 \r
94 #define UPDATE_MOBILITY(X,Y)\r
95 #define ADDMOVE(X,Y)\r
96 \r
97 // promotion codes\r
98 #define CAN_PROMOTE 0x11\r
99 #define DONT_DEFER  0x22\r
100 #define CANT_DEFER  0x44\r
101 #define LAST_RANK   0x88\r
102 #define P_WHITE     0x0F\r
103 #define P_BLACK     0xF0\r
104 \r
105 typedef unsigned int Move;\r
106 \r
107 char *MoveToText(Move move, int m);     // from WB driver\r
108 void pmap(int *m, int col);\r
109 void pboard(int *b);\r
110 void pbytes(unsigned char *b);\r
111 \r
112 typedef struct {\r
113   int lock[5];\r
114   int move[5];\r
115   short int score[5];\r
116   char depth[5];\r
117   char flag[5];\r
118   char age[4];\r
119 } HashBucket;\r
120 \r
121 HashBucket *hashTable;\r
122 int hashMask;\r
123 \r
124 #define H_UPPER 2\r
125 #define H_LOWER 1\r
126 \r
127 typedef struct {\r
128   char *name, *promoted;\r
129   int value;\r
130   signed char range[8];\r
131   char bulk;\r
132   char ranking;\r
133   int whiteKey, blackKey;\r
134 } PieceDesc;\r
135 \r
136 typedef struct {\r
137   int from, to, piece, victim, new, booty, epSquare, epVictim[8], ep2Square, revMoveCount;\r
138   int savKeyL, savKeyH, gain, loss, filling, saveDelta;\r
139   char fireMask;\r
140 } UndoInfo;\r
141 \r
142 char *array, fenArray[4000], startPos[4000], *reason, checkStack[300];\r
143 int bWidth, bHeight, bsize, zone, currentVariant, chuFlag, tenFlag, chessFlag, repDraws, tsume, pvCuts, allowRep, entryProm;\r
144 int stm, xstm, hashKeyH=1, hashKeyL=1, framePtr, msp, nonCapts, rootEval, filling, promoDelta;\r
145 int retMSP, retFirst, retDep, pvPtr, level, cnt50, mobilityScore;\r
146 int ll, lr, ul, ur; // corner squares\r
147 int nodes, startTime, lastRootMove, lastRootIter, tlim1, tlim2, tlim3, repCnt, comp, abortFlag;\r
148 Move ponderMove;\r
149 Move retMove, moveStack[10000], path[100], repStack[300], pv[1000], repeatMove[300], killer[100][2];\r
150 \r
151       int maxDepth;                            // used by search\r
152 \r
153 #define X 36 /* slider              */\r
154 #define R 37 /* jump capture        */\r
155 #define N -1 /* Knight              */\r
156 #define J -2 /* jump                */\r
157 #define D -3 /* linear double move  */\r
158 #define T -4 /* linear triple move  */\r
159 #define L -5 /* true Lion move      */\r
160 #define F -6 /* Lion + 3-step       */\r
161 #define S -7 /* Lion + range        */\r
162 #define H -9 /* hook move           */\r
163 #define C -10 /* capture only       */\r
164 #define M -11 /* non-capture only   */\r
165 \r
166 #define LVAL 1000 /* piece value of Lion. Used in chu for recognizing it to implement Lion-trade rules  */\r
167 #define FVAL 5000 /* piece value of Fire Demon. Used in code for recognizing moves with it and do burns */\r
168 \r
169 PieceDesc chuPieces[] = {\r
170   {"LN", "",  LVAL, { L,L,L,L,L,L,L,L }, 4 }, // lion\r
171   {"FK", "",   600, { X,X,X,X,X,X,X,X }, 4 }, // free king\r
172   {"SE", "",   550, { X,D,X,X,X,X,X,D }, 4 }, // soaring eagle\r
173   {"HF", "",   500, { D,X,X,X,X,X,X,X }, 4 }, // horned falcon\r
174   {"FO", "",   400, { X,X,0,X,X,X,0,X }, 4 }, // flying ox\r
175   {"FB", "",   400, { 0,X,X,X,0,X,X,X }, 4 }, // free boar\r
176   {"DK", "SE", 400, { X,1,X,1,X,1,X,1 }, 4 }, // dragon king\r
177   {"DH", "HF", 350, { 1,X,1,X,1,X,1,X }, 4 }, // dragon horse\r
178   {"WH", "",   350, { X,X,0,0,X,0,0,X }, 3 }, // white horse\r
179   {"R",  "DK", 300, { X,0,X,0,X,0,X,0 }, 4 }, // rook\r
180   {"FS", "",   300, { X,1,1,1,X,1,1,1 }, 3 }, // flying stag\r
181   {"WL", "",   250, { X,0,0,X,X,X,0,0 }, 4 }, // whale\r
182   {"K",  "",   280, { 1,1,1,1,1,1,1,1 }, 2, 4 }, // king\r
183   {"CP", "",   270, { 1,1,1,1,1,1,1,1 }, 2, 4 }, // king\r
184   {"B",  "DH", 250, { 0,X,0,X,0,X,0,X }, 2 }, // bishop\r
185   {"VM", "FO", 200, { X,0,1,0,X,0,1,0 }, 2 }, // vertical mover\r
186   {"SM", "FB", 200, { 1,0,X,0,1,0,X,0 }, 6 }, // side mover\r
187   {"DE", "CP", 201, { 1,1,1,1,0,1,1,1 }, 2 }, // drunk elephant\r
188   {"BT", "FS", 152, { 0,1,1,1,1,1,1,1 }, 2 }, // blind tiger\r
189   {"G",  "R",  151, { 1,1,1,0,1,0,1,1 }, 2 }, // gold\r
190   {"FL", "B",  150, { 1,1,0,1,1,1,0,1 }, 2 }, // ferocious leopard\r
191   {"KN", "LN", 154, { J,1,J,1,J,1,J,1 }, 2 }, // kirin\r
192   {"PH", "FK", 153, { 1,J,1,J,1,J,1,J }, 2 }, // phoenix\r
193   {"RV", "WL", 150, { X,0,0,0,X,0,0,0 }, 1 }, // reverse chariot\r
194   {"L",  "WH", 150, { X,0,0,0,0,0,0,0 }, 1 }, // lance\r
195   {"S",  "VM", 100, { 1,1,0,1,0,1,0,1 }, 2 }, // silver\r
196   {"C",  "SM", 100, { 1,1,0,0,1,0,0,1 }, 2 }, // copper\r
197   {"GB", "DE",  50, { 1,0,0,0,1,0,0,0 }, 1 }, // go between\r
198   {"P",  "G",   40, { 1,0,0,0,0,0,0,0 }, 2 }, // pawn\r
199   { NULL }  // sentinel\r
200 };\r
201 \r
202 PieceDesc shoPieces[] = {\r
203   {"DK", "",   700, { X,1,X,1,X,1,X,1 } }, // dragon king\r
204   {"DH", "",   520, { 1,X,1,X,1,X,1,X } }, // dragon horse\r
205   {"R",  "DK", 500, { X,0,X,0,X,0,X,0 } }, // rook\r
206   {"B",  "DH", 320, { 0,X,0,X,0,X,0,X } }, // bishop\r
207   {"K",  "",   410, { 1,1,1,1,1,1,1,1 } }, // king\r
208   {"CP", "",   400, { 1,1,1,1,1,1,1,1 } }, // king\r
209   {"DE", "CP", 250, { 1,1,1,1,0,1,1,1 } }, // silver\r
210   {"G",  "",   220, { 1,1,1,0,1,0,1,1 } }, // gold\r
211   {"S",  "G",  200, { 1,1,0,1,0,1,0,1 } }, // silver\r
212   {"L",  "G",  150, { X,0,0,0,0,0,0,0 } }, // lance\r
213   {"N",  "G",  110, { N,0,0,0,0,0,0,N } }, // Knight\r
214   {"P",  "G",   80, { 1,0,0,0,0,0,0,0 } }, // pawn\r
215   { NULL }  // sentinel\r
216 };\r
217 \r
218 PieceDesc daiPieces[] = {\r
219   {"FD", "G", 150, { 0,2,0,2,0,2,0,2 }, 2 }, // Flying Dragon\r
220   {"VO", "G", 200, { 2,0,2,0,2,0,2,0 }, 2 }, // Violent Ox\r
221   {"EW", "G",  80, { 1,1,1,0,0,0,1,1 }, 2 }, // Evil Wolf\r
222   {"CS", "G",  70, { 0,1,0,1,0,1,0,1 }, 1 }, // Cat Sword\r
223   {"AB", "G",  60, { 1,0,1,0,1,0,1,0 }, 1 }, // Angry Boar\r
224   {"I",  "G",  80, { 1,1,0,0,0,0,0,1 }, 2 }, // Iron\r
225   {"N",  "G",  60, { N,0,0,0,0,0,0,N }, 0 }, // Knight\r
226   {"ST", "G",  50, { 0,1,0,0,0,0,0,1 }, 0 }, // Stone\r
227   { NULL }  // sentinel\r
228 };\r
229 \r
230 PieceDesc ddPieces[] = {\r
231   {"LO", "",   10, { 1,H,1,H,1,H,1,H } }, // Long-Nosed Goblin\r
232   {"OK", "LO", 10, { 2,1,2,0,2,0,2,1 } }, // Old Kite\r
233   {"PS", "HM", 10, { J,0,1,J,0,J,1,0 } }, // Poisonous Snake\r
234   {"GE", "",   10, { 3,3,5,5,3,5,5,3 } }, // Great Elephant\r
235   {"WS", "LD", 10, { 1,1,2,0,1,0,2,1 } }, // Western Barbarian\r
236   {"EA", "LN", 10, { 2,1,1,0,2,0,1,1 } }, // Eastern Barbarian\r
237   {"NO", "FE", 10, { 0,2,1,1,0,1,1,2 } }, // Northern Barbarian\r
238   {"SO", "WE", 10, { 0,1,1,2,0,2,1,1 } }, // Southern Barbarian\r
239   {"FE", "",   10, { 2,X,2,2,2,2,2,X } }, // Fragrant Elephant\r
240   {"WE", "",   10, { 2,2,2,X,2,X,2,2 } }, // White Elephant\r
241   {"FT", "",   10, { X,X,5,0,X,0,5,X } }, // Free Dream-Eater\r
242   {"FR", "",   10, { 5,X,X,0,5,0,X,X } }, // Free Demon\r
243   {"WB", "FT", 10, { 2,X,X,X,2,X,X,X } }, // Water Buffalo\r
244   {"RB", "FR", 10, { X,X,X,X,0,X,X,X } }, // Rushing Bird\r
245   {"SB", "",   10, { X,X,2,2,2,2,2,X } }, // Standard Bearer\r
246 \r
247   {"FH", "FK", 10, { 1,2,1,0,1,0,1,2 } }, // Flying Horse\r
248   {"NK", "SB", 10, { 1,1,1,1,1,1,1,1 } }, // Neighbor King\r
249   {"BM", "MW", 10, { 0,1,1,1,0,1,1,1 } }, // Blind Monkey\r
250   {"DO", "",   10, { 2,X,2,X,2,X,2,X } }, // Dove\r
251   {"EB", "DO", 10, { 2,0,2,0,0,0,2,0 } }, // Enchanted Badger\r
252   {"EF", "SD", 10, { 0,2,0,0,2,0,0,2 } }, // Enchanted Fox\r
253   {"RA", "",   10, { X,0,X,1,X,1,X,0 } }, // Racing Chariot\r
254   {"SQ", "",   10, { X,1,X,0,X,0,X,1 } }, // Square Mover\r
255   {"PR", "SQ", 10, { 1,1,2,1,0,1,2,1 } }, // Prancing Stag\r
256   {"WT", "",   10, { X,1,2,0,X,0,2,X } }, // White Tiger\r
257   {"BD", "",   10, { 2,X,X,0,2,0,X,1 } }, // Blue Dragon\r
258   {"HD", "",   10, { X,0,0,0,1,0,0,0 } }, // Howling Dog\r
259   {"VB", "",   10, { 0,2,1,0,0,0,1,2 } }, // Violent Bear\r
260   {"SA", "",   10, { 2,1,0,0,2,0,0,1 } }, // Savage Tiger\r
261   {"W",  "",   10, { 0,2,0,0,0,0,0,2 } }, // Wood\r
262   {"CS", "DH",  70, { 0,1,0,1,0,1,0,1 } }, // cat sword\r
263   {"FD", "DK", 150, { 0,2,0,2,0,2,0,2 } }, // flying dragon\r
264   {"KN", "GD", 150, { J,1,J,1,J,1,J,1 } }, // kirin\r
265   {"PH", "GB", 150, { 1,J,1,J,1,J,1,J } }, // phoenix\r
266   {"LN", "FF",  1000, { L,L,L,L,L,L,L,L } }, // lion\r
267   {"LD", "GE", 10, { T,T,T,T,T,T,T,T } }, // Lion Dog\r
268   {"AB", "", 10, { 1,0,1,0,1,0,1,0 } }, // Angry Boar\r
269   {"B",  "", 10, { 0,X,0,X,0,X,0,X } }, // Bishop\r
270   {"C",  "", 10, { 1,1,0,0,1,0,0,1 } }, // Copper\r
271   {"DH", "", 10, { 1,X,1,X,1,X,1,X } }, // Dragon Horse\r
272   {"DK", "", 10, { X,1,X,1,X,1,X,1 } }, // Dragon King\r
273   {"FK", "", 10, {  } }, // \r
274   {"EW", "", 10, { 1,1,1,0,0,0,1,1 } }, // Evil Wolf\r
275   {"FL", "", 10, {  } }, // \r
276   {"", "", 10, {  } }, // \r
277   {"", "", 10, {  } }, // \r
278   {"", "", 10, {  } }, // \r
279   {"", "", 10, {  } }, // \r
280   { NULL }  // sentinel\r
281 };\r
282 \r
283 PieceDesc makaPieces[] = {\r
284   {"DV", "", 10, { 0,1,0,1,0,0,1,1 } }, // Deva\r
285   {"DS", "", 10, { 0,1,1,0,0,1,0,1 } }, // Dark Spirit\r
286   {"T",  "", 10, { 0,1,0,0,1,0,0,1 } }, // Tile\r
287   {"CS", "", 10, { 1,0,0,1,1,1,0,0 } }, // Coiled Serpent\r
288   {"RD", "", 10, { 1,0,1,1,1,1,1,0 } }, // Reclining Dragon\r
289   {"CC", "", 10, { 0,1,1,0,1,0,1,1 } }, // Chinese Cock\r
290   {"OM", "", 10, { 0,1,0,1,1,1,0,1 } }, // Old Monkey\r
291   {"BB", "", 10, { 0,1,0,1,X,1,0,1 } }, // Blind Bear\r
292   {"OR", "", 10, { 0,2,0,0,2,0,0,2 } }, // Old Rat\r
293   {"LD", "WS", 10, { T,T,T,T,T,T,T,T } }, // Lion Dog\r
294   {"WR", "", 10, { 0,3,1,3,0,3,1,3 } }, // Wrestler\r
295   {"GG", "", 10, { 3,1,3,0,3,0,3,1 } }, // Guardian of the Gods\r
296   {"BD", "", 10, { 0,3,1,0,1,0,1,3 } }, // Budhist Devil\r
297   {"SD", "", 10, { 5,2,5,2,5,2,5,2 } }, // She-Devil\r
298   {"DY", "", 10, { J,0,1,0,J,0,1,0 } }, // Donkey\r
299   {"CP", "", 10, { 0,H,0,2,0,2,0,H } }, // Capricorn\r
300   {"HM", "", 10, { H,0,H,0,H,0,H,0 } }, // Hook Mover\r
301   {"SF", "", 10, { 0,1,X,1,0,1,0,1 } }, // Side Flier\r
302   {"LC", "", 10, { X,0,0,X,1,0,0,X } }, // Left Chariot\r
303   {"RC", "", 10, { X,X,0,0,1,X,0,0 } }, // Right Chariot\r
304   {"FG", "", 10, { X,X,X,0,X,0,X,X } }, // Free Gold\r
305   {"FS", "", 10, { X,X,0,X,0,X,0,X } }, // Free Silver\r
306   {"FC", "", 10, { X,X,0,0,X,0,0,X } }, // Free Copper\r
307   {"FI", "", 10, { X,X,0,0,0,0,0,X } }, // Free Iron\r
308   {"FT", "", 10, { 0,X,0,0,X,0,0,X } }, // Free Tile\r
309   {"FN", "", 10, { 0,X,0,0,0,0,0,X } }, // Free Stone\r
310   {"FTg", "", 10, { 0,X,X,X,X,X,X,X } }, // Free Tiger\r
311   {"FLp", "", 10, { X,X,0,X,X,X,0,X } }, // Free Leopard (Free Boar?)\r
312   {"FSp", "", 10, { X,0,0,X,X,X,0,0 } }, // Free Serpent (Whale?)\r
313   {"FrD", "", 10, { X,0,X,X,X,X,X,0 } }, // Free Dragon\r
314   {"FC", "", 10, { 0,X,0,X,0,X,0,X } }, // Free Cat (Bishop?)\r
315   {"EM", "", 10, {  } }, // Emperor\r
316   {"TK", "", 10, {  } }, // Teaching King\r
317   {"BS", "", 10, {  } }, // Budhist Spirit\r
318   {"WS", "", 10, { X,X,0,X,1,X,0,X } }, // Wizard Stork\r
319   {"MW", "", 10, { 1,X,0,X,X,X,0,X } }, // Mountain Witch\r
320   {"FF", "", 10, {  } }, // Furious Fiend\r
321   {"GD", "", 10, { 2,3,X,3,2,3,X,3 } }, // Great Dragon\r
322   {"GB", "", 10, { X,3,2,3,X,3,2,3 } }, // Golden Bird\r
323   {"FrW", "", 10, {  } }, // Free Wolf\r
324   {"FrB", "", 10, {  } }, // Free Bear\r
325   {"BT", "", 10, { X,0,0,X,0,X,0,0 } }, // Bat\r
326   {"", "", 10, {  } }, // \r
327   { NULL }  // sentinel\r
328 };\r
329 \r
330 PieceDesc taiPieces[] = {\r
331   {"", "", 10, {  } }, // Peacock\r
332   {"", "", 10, {  } }, // Vermillion Sparrow\r
333   {"", "", 10, {  } }, // Turtle Snake\r
334   {"", "", 10, {  } }, // Silver Hare\r
335   {"", "", 10, {  } }, // Golden Deer\r
336   {"", "", 10, {  } }, // \r
337   {"", "", 10, {  } }, // \r
338   {"", "", 10, {  } }, // \r
339   { NULL }  // sentinel\r
340 };\r
341 \r
342 PieceDesc tenjikuPieces[] = { // only those not in Chu, or different (because of different promotion)\r
343   {"FI", "",  FVAL, { X,X,0,X,X,X,0,X } }, // Fire Demon\r
344   {"GG", "",  1500, { R,R,R,R,R,R,R,R }, 0, 3 }, // Great General\r
345   {"VG", "",  1400, { 0,R,0,R,0,R,0,R }, 0, 2 }, // Vice General\r
346   {"RG", "GG",1200, { R,0,R,0,R,0,R,0 }, 0, 1 }, // Rook General\r
347   {"BG", "VG",1100, { 0,R,0,R,0,R,0,R }, 0, 1 }, // Bishop General\r
348   {"SE", "RG", 10, { X,D,X,X,X,X,X,D } }, // Soaring Eagle\r
349   {"HF", "BG", 10, { D,X,X,X,X,X,X,X } }, // Horned Falcon\r
350   {"LH", "",   10, { L,S,L,S,L,S,L,S } }, // Lion-Hawk\r
351   {"LN", "LH",LVAL, { L,L,L,L,L,L,L,L } }, // Lion\r
352   {"FE", "",   1,   { X,X,X,X,X,X,X,X } }, // Free Eagle\r
353   {"FK", "FE", 600, { X,X,X,X,X,X,X,X } }, // Free King\r
354   {"HT", "",   10, { X,X,2,X,X,X,2,X } }, // Heavenly Tetrarchs\r
355   {"CS", "HT", 10, { X,X,2,X,X,X,2,X } }, // Chariot Soldier\r
356   {"WB", "FI", 10, { 2,X,X,X,2,X,X,X } }, // Water Buffalo\r
357   {"VS", "CS", 10, { X,0,2,0,1,0,2,0 } }, // Vertical Soldier\r
358   {"SS", "WB", 10, { 2,0,X,0,1,0,X,0 } }, // Side Soldier\r
359   {"I",  "VS", 10, { 1,1,0,0,0,0,0,1 } }, // Iron\r
360   {"N",  "SS", 10, { N,0,0,0,0,0,0,N } }, // Knight\r
361   {"MG", "",   10, { X,0,0,X,0,X,0,0 } }, // Multi-General\r
362   {"D",  "MG", 10, { 1,0,0,1,0,1,0,0 } }, // Dog\r
363   { NULL }  // sentinel\r
364 };\r
365 \r
366 PieceDesc taikyokuPieces[] = {\r
367   {"", "", 10, {  } }, // \r
368   { NULL }  // sentinel\r
369 };\r
370 \r
371 PieceDesc chessPieces[] = {\r
372   {"Q", "",  950, { X,X,X,X,X,X,X,X } },\r
373   {"R", "",  500, { X,0,X,0,X,0,X,0 } },\r
374   {"B", "",  320, { 0,X,0,X,0,X,0,X } },\r
375   {"N", "",  300, { N,N,N,N,N,N,N,N } },\r
376   {"K", "",  280, { 1,1,1,1,1,1,1,1 } },\r
377   {"P", "Q",  80, { M,C,0,0,0,0,0,C } },\r
378   { NULL }  // sentinel\r
379 };\r
380 \r
381 PieceDesc shatranjPieces[] = {\r
382   {"FK", "", 150, { 0,1,0,1,0,1,0,1 } },\r
383   {"R", "",  500, { X,0,X,0,X,0,X,0 } },\r
384   {"B", "",   90, { 0,J,0,J,0,J,0,J } },\r
385   {"N", "",  300, { N,N,N,N,N,N,N,N } },\r
386   {"K", "",  280, { 1,1,1,1,1,1,1,1 } },\r
387   {"P", "FK", 80, { M,C,0,0,0,0,0,C } },\r
388   { NULL }  // sentinel\r
389 };\r
390 \r
391 PieceDesc makrukPieces[] = {\r
392   {"SM","",  150, { 0,1,0,1,0,1,0,1 } },\r
393   {"R", "",  500, { X,0,X,0,X,0,X,0 } },\r
394   {"S", "",  200, { 1,1,0,1,0,1,0,1 } }, // silver\r
395   {"N", "",  300, { N,N,N,N,N,N,N,N } },\r
396   {"K", "",  280, { 1,1,1,1,1,1,1,1 } },\r
397   {"P", "SM", 80, { M,C,0,0,0,0,0,C } },\r
398   { NULL }  // sentinel\r
399 };\r
400 \r
401 char chuArray[] = "L:FLCSGK:DEGSC:FLL/:RV.B.:BT:KN:PH:BT.B.:RV/:SM:VMR:DH:DK:LN:FK:DK:DHR:VM:SM/PPPPPPPPPPPP/...:GB....:GB..."\r
402                   "/............/............/"\r
403                   "...:gb....:gb.../pppppppppppp/:sm:vmr:dh:dk:fk:ln:dk:dhr:vm:sm/:rv.b.:bt:ph:kn:bt.b.:rv/l:flcsg:dekgsc:fll";\r
404 char daiArray[] = "LN:STICSGKGSCI:STNL/:RV.:CS.:FL.:BT:DE:BT.:FL.:CS.:RV/.:VO.:AB.:EW:KN:LN:PH:EW.:AB.:VO./R:FD:SM:VMB:DH:DK:FK:DK:DHB:VM:SM:FDR"\r
405                   "/PPPPPPPPPPPPPPP/....:GB.....:GB..../.............../.............../.............../....:gb.....:gb..../ppppppppppppppp/"\r
406                   "r:fd:sm:vmb:dh:dk:fk:dk:dhb:vm:sm:fdr/.:vo.:ab.:ew:ph:ln:kn:ew.:ab.:vo./:rv.:cs.:fl.:bt:de:bt.:fl.:cs.:rv/ln:sticsgkgsci:stnl";\r
407 char tenArray[] = "LN:FLICSGK:DEGSCI:FLNL/:RV.:CS:CS.:BT:KN:LN:FK:PH:BT.:CS:CS.:RV/:SS:VSB:DH:DK:WB:FI:LH:FE:FI:WB:DK:DHB:VS:SS/"\r
408                   ":SM:VMR:HF:SE:BG:RG:GG:VG:RG:BG:SE:HFR:VM:SM/PPPPPPPPPPPPPPPP/....D......D..../"\r
409                   "................/................/................/................/"\r
410                   "....d......d..../pppppppppppppppp/:sm:vmr:hf:se:bg:rg:vg:gg:rg:bg:se:hfr:vm:sm/"\r
411                   ":ss:vsb:dh:dk:wb:fi:fe:lh:fi:wb:dk:dhb:vs:ss/:rv.:cs:cs.:bt:ph:fk:ln:kn:bt.:cs:cs.:rv/ln:flicsg:dekgsci:flnl";\r
412 char shoArray[] = "LNSGKGSNL/.B..:DE..R./PPPPPPPPP/........./........./........./ppppppppp/.r..:de..b./lnsgkgsnl";\r
413 char chessArray[] = "RNBQKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbqkbnr";\r
414 char shatArray[]= "RNBK:FKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbk:fkbnr";\r
415 char thaiArray[]= "RNSK:SMSNR/......../PPPPPPPP/......../......../pppppppp/......../rnsk:smsnr";\r
416 \r
417 typedef struct {\r
418   int boardWidth, boardFiles, boardRanks, zoneDepth, varNr; // board sizes\r
419   char *name;  // WinBoard name\r
420   char *array; // initial position\r
421 } VariantDesc;\r
422 \r
423 typedef enum { V_CHESS, V_SHO, V_CHU, V_DAI, V_TENJIKU, V_DADA, V_MAKA, V_TAI, V_KYOKU, V_SHATRANJ, V_MAKRUK } Variant;\r
424 \r
425 VariantDesc variants[] = {\r
426   { 16,  8,  8, 1, V_CHESS,  "normal", chessArray }, // FIDE\r
427   { 18,  9,  9, 3, V_SHO, "9x9+0_shogi", shoArray }, // Sho\r
428   { 24, 12, 12, 4, V_CHU,     "chu",     chuArray }, // Chu\r
429   { 30, 15, 15, 5, V_DAI,     "dai",     daiArray }, // Dai\r
430   { 32, 16, 16, 5, V_TENJIKU, "tenjiku", tenArray }, // Tenjiku\r
431   { 16,  8,  8, 1, V_SHATRANJ,"shatranj",shatArray}, // Shatranj\r
432   { 16,  8,  8, 3, V_MAKRUK,  "makruk",  thaiArray}, // Makruk\r
433 \r
434 //  { 0, 0, 0, 0, 0 }, // sentinel\r
435   { 34, 17, 17, 0, V_DADA,    "dada",    chuArray }, // Dai Dai\r
436   { 38, 19, 19, 0, V_MAKA,    "maka",    chuArray }, // Maka Dai Dai\r
437   { 50, 25, 25, 0, V_TAI,     "tai",     chuArray }, // Tai\r
438   { 40, 36, 36, 0, V_KYOKU,   "kyoku",   chuArray }  // Taikyoku\r
439 };\r
440 \r
441 typedef struct {\r
442   int x, y;\r
443 } Vector;\r
444 \r
445 Vector direction[] = { // clockwise!\r
446   {1,  0},\r
447   {1,  1},\r
448   {0,  1},\r
449   {-1, 1},\r
450   {-1, 0},\r
451   {-1,-1},\r
452   {0, -1},\r
453   {1, -1},\r
454 \r
455   { 2, 1}, // Knight jumps\r
456   { 1, 2},\r
457   {-1, 2},\r
458   {-2, 1},\r
459   {-2,-1},\r
460   {-1,-2},\r
461   { 1,-2},\r
462   { 2,-1}\r
463 };\r
464 \r
465 int epList[96], ep2List[96], toList[96], reverse[96];  // decoding tables for double and triple moves\r
466 int kingStep[10], knightStep[10];         // raw tables for step vectors (indexed as -1 .. 8)\r
467 int neighbors[9];   // similar to kingStep, but starts with null-step\r
468 char fireFlags[10]; // flags for Fire-Demon presence (last two are dummies, which stay 0, for compactify)\r
469 #define kStep (kingStep+1)\r
470 #define nStep (knightStep+1)\r
471 \r
472 int attackMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction\r
473   000000007,\r
474   000000070,\r
475   000000700,\r
476   000007000,\r
477   000070000,\r
478   000700000,\r
479   007000000,\r
480   070000000\r
481 };\r
482 \r
483 int rayMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction\r
484   000000077,\r
485   000000077,\r
486   000007700,\r
487   000007700,\r
488   000770000,\r
489   000770000,\r
490   077000000,\r
491   077000000\r
492 };\r
493 \r
494 int one[] = { // 1 in the bit fields for the various directions\r
495   000000001,\r
496   000000010,\r
497   000000100,\r
498   000001000,\r
499   000010000,\r
500   000100000,\r
501   001000000,\r
502   010000000,\r
503  0100000000  // marks knight jumps\r
504 };\r
505 \r
506 //                                           Main Data structures\r
507 //\r
508 // Piece List: \r
509 //   Interleaved lists for black and white, white taking the odd slots\r
510 //   Pieces in general have two entries: one for the basic, and one for the promoted version\r
511 //   The unused one gets its position set to the invalid square number ABSENT\r
512 //   The list is sorted by piece value, most valuable pieces first\r
513 //   When a piece is captured in the search, both its versions are marked ABSENT\r
514 //   In the root the list is packed to eliminate all captured pieces\r
515 //   The list contains a table for how far the piece moves in each direction\r
516 //   Range encoding: -3 = full Lion, -2 = on-ray Lion, -1 = plain jump, 0 = none, 1 = step, >1 = (limited) range\r
517 // Attack table:\r
518 //   A table in board format, containing pairs of consecutive integers for each square (indexed as 2*sqr and 2*sqr+1)\r
519 //   The first integer contains info on black attacks to the square, the second similarly for white attacks\r
520 //   Each integer contains eight 3-bit fields, which count the number of attacks on it with moves in a particular direction\r
521 //   (If there are attacks by range-jumpers, the 3-bit count is increased by 2 over the actual value)\r
522 // Board:\r
523 //   The board has twice as many files as actually used, in 0x88 fashion\r
524 //   The used squares hold the piece numbers (for use as index in the piece list)\r
525 //   Unused squares are set to the invalid piece number EDGE\r
526 //   There are also 3 guard ranks of EDGE on each side\r
527 // Moves:\r
528 //   Moves are encoded as 11-bit from-square and to-square numbers packed in the low bits of an int\r
529 //   Special moves (like Lion double moves) are encoded by off-board to-squares above a certain value\r
530 //   Promotions are indicated by bit 22\r
531 // Hash table:\r
532 //   Entries of 16 bytes, holding a 32-bit signature, 16-bit lower- and upper-bound scores,\r
533 //   8-bit draft of each of those scores, an age counter that stores the search number of the last access.\r
534 //   The hash key is derived as the XOR of the products pieceKey[piece]*squareKey[square].\r
535 // Promotion zones\r
536 //   the promoBoard contains one byte with flags for each square, to indicate for each side whether the square\r
537 //   is in the promotion zone (twice), on the last two ranks, or on the last rank\r
538 //   the promoFlag field in the piece list can select which bits of this are tested, to see if it\r
539 //   (1) can promote (2) can defer when the to-square is on last rank, last two ranks, or anywhere.\r
540 //   Pawns normally can't defer anywhere, but if the user defers with them, their promoFlag is set to promote on last rank only\r
541 \r
542 typedef struct {\r
543   int pos;\r
544   int pieceKey;\r
545   int promo;\r
546   int value;\r
547   int pst;\r
548   signed char range[8];\r
549   char promoFlag;\r
550   char qval;\r
551   char mobility;\r
552   char mobWeight;\r
553   unsigned char promoGain;\r
554   char bulk;\r
555 } PieceInfo; // piece-list entry\r
556 \r
557 int last[2], royal[2], kylin[2];\r
558 PieceInfo p[NPIECES]; // piece list\r
559 \r
560 typedef struct {\r
561   int lock;\r
562   Move move;\r
563   short int upper;\r
564   short int lower;\r
565   char depthU;\r
566   char depthL;\r
567   char flags;\r
568   char age;\r
569 } HashEntry; // hash-table entry\r
570 \r
571     // Some global variables that control your engine's behavior\r
572     int ponder;\r
573     int randomize;\r
574     int postThinking;\r
575     int noCut=1;        // engine-defined option\r
576     int resign;         // engine-defined option\r
577     int contemptFactor; // likewise\r
578     int seed;\r
579 \r
580 int squareKey[BSIZE];\r
581 \r
582 int rawBoard[BSIZE + 11*BHMAX + 6];\r
583 //int attacks[2*BSIZE];   // attack map\r
584 int attackMaps[200*BSIZE], *attacks = attackMaps;\r
585 char distance[2*BSIZE]; // distance table\r
586 char promoBoard[BSIZE]; // flags to indicate promotion zones\r
587 char rawFire[BSIZE+2*BWMAX]; // flags to indicate squares controlled by Fire Demons\r
588 signed char PST[5*BSIZE];\r
589 \r
590 #define board     (rawBoard + 6*BHMAX + 3)\r
591 #define fireBoard (rawFire + BWMAX + 1)\r
592 #define dist      (distance + BSIZE)\r
593 \r
594 PieceDesc *\r
595 ListLookUp (char *name, PieceDesc *list)\r
596 { // find piece of given name in list of descriptors\r
597   while(list->name && strcmp(name, list->name)) list++;\r
598   return (list->name == NULL ? NULL : list);\r
599 }\r
600 \r
601 PieceDesc *\r
602 LookUp (char *name, int var)\r
603 { // search piece of given name in all lists relevant for given variant\r
604   PieceDesc *desc;\r
605   switch(var) {\r
606     case V_TENJIKU: // Tenjiku\r
607       desc = ListLookUp(name, tenjikuPieces);\r
608       if(desc) return desc;\r
609       return ListLookUp(name, chuPieces);\r
610     case V_SHO: // Sho\r
611       return ListLookUp(name, shoPieces);\r
612     case V_DAI: // Dai\r
613       desc = ListLookUp(name, daiPieces);\r
614       if(desc) return desc;\r
615     case V_CHU: // Chu\r
616       return ListLookUp(name, chuPieces);\r
617     case V_CHESS: // FIDE\r
618       return ListLookUp(name, chessPieces);\r
619     case V_SHATRANJ: // Shatranj\r
620       return ListLookUp(name, shatranjPieces);\r
621     case V_MAKRUK: // Makruk\r
622       return ListLookUp(name, makrukPieces);\r
623   }\r
624   return NULL;\r
625 }\r
626 \r
627 void\r
628 SqueezeOut (int n)\r
629 { // remove piece number n from the mentioned side's piece list (and adapt the reference to the displaced pieces!)\r
630   int i;\r
631   for(i=stm+2; i<=last[stm]; i+=2)\r
632     if(p[i].promo > n) p[i].promo -= 2;\r
633   for(i=n; i<last[stm]; i+=2) {\r
634     p[i] = p[i+2];\r
635     if(i+2 == royal[stm]) royal[stm] -= 2; // NB: squeezing out the King moves up Crown Prince to royal[stm]\r
636     if(i+2 == kylin[stm]) kylin[stm] -= 2;\r
637     if(i < 10) fireFlags[i-2] = fireFlags[i];\r
638   }\r
639   last[stm] -= 2;\r
640 }\r
641 \r
642 int\r
643 Worse (int a, int b)\r
644 { // determine if range a not upward compatible with b\r
645   if(a == b) return 0;\r
646   if(a >= 0 && b >= 0) return a < b;\r
647   if(a >= 0) return 1; // a (limited) range can never do the same as a special move\r
648   switch(a) {\r
649     case J: return b < J; // any special move is better than a plain jump\r
650     case D: return b > 2 || b < D;\r
651     case T: return b > 3 || b < T;\r
652     case L: return b > 2 || b < D;\r
653     case F: return b > 3 || b < F || b == T;\r
654     case S: return b == H || b == T;\r
655     case H: return b < 0;\r
656     default: return 1; // a >= 0, so b must be < 0 and can always do something a ranging move cannot do\r
657   }\r
658   return 0;\r
659 }\r
660 \r
661 int\r
662 Lance (signed char *r)\r
663 { // File-bound forward slider\r
664   int i;\r
665   for(i=1; i<4; i++) if(r[i] || r[i+4]) return 0;\r
666   return r[0] == X;\r
667 }\r
668 \r
669 int\r
670 EasyProm (signed char *r)\r
671 {\r
672   int i;\r
673   if(r[0] == X) return 30 + PROMO*((unsigned int)(r[1] | r[2] | r[3] | r[5] | r[6] | r[7]) <= 1);\r
674   if(r[1] == X || r[7] == X) return 30 + PROMO/2;\r
675   return 0;\r
676 }\r
677 \r
678 int\r
679 IsUpwardCompatible (signed char *r, signed char *s)\r
680 {\r
681   int i;\r
682   for(i=0; i<8; i++) {\r
683     if(Worse(r[i], s[i])) return 0;\r
684   }\r
685   return 1;\r
686 }\r
687 \r
688 int\r
689 Forward (signed char *r)\r
690 {\r
691   int i;\r
692   for(i=2; i<7; i++) if(r[i]) return 0;\r
693   return 1;\r
694 }\r
695 \r
696 int\r
697 Range (signed char *r)\r
698 {\r
699   int i, m=0;\r
700   for(i=0; i<8; i++) {\r
701     int d = r[i];\r
702     if(r[i] < 0) d == r[i] >= L ? 2 : 36;\r
703     if(d > m) m = d;\r
704   }\r
705   return m;\r
706 }\r
707 \r
708 int multis[2], multiMovers[100];\r
709 \r
710 void\r
711 StackMultis (int col)\r
712 {\r
713   int i, j;\r
714   multis[col] = col;\r
715   for(i=col+2; i<=last[col]; i+=2) { // scan piece list for multi-capturers\r
716     for(j=0; j<8; j++) if(p[i].range[j] < J && p[i].range[j] >= S || p[i].value == FVAL) {\r
717       multiMovers[multis[col]] = i; // found one: put its piece number in list\r
718       multis[col] += 2;\r
719       break;\r
720     }\r
721   }\r
722 }\r
723 \r
724 void\r
725 Compactify (int stm)\r
726 { // remove pieces that are permanently gone (captured or promoted) from one side's piece list\r
727   int i, j, k;\r
728   for(i=stm+2; i<=last[stm]; i+=2) { // first pass: unpromoted pieces\r
729     if((k = p[i].promo) >= 0 && p[i].pos == ABSENT) { // unpromoted piece no longer there\r
730       p[k].promo = -2; // orphan promoted version\r
731       SqueezeOut(i);\r
732     }\r
733   }\r
734   for(i=stm+2; i<=last[stm]; i+=2) { // second pass: promoted pieces\r
735 \r
736     if((k = p[i].promo) == -2 && p[i].pos == ABSENT) { // orphaned promoted piece not present\r
737       SqueezeOut(i);\r
738     }\r
739   }\r
740   StackMultis(stm);\r
741 }\r
742 \r
743 int\r
744 AddPiece (int stm, PieceDesc *list)\r
745 {\r
746   int i, j, *key, v;\r
747   for(i=stm+2; i<=last[stm]; i += 2) {\r
748     if(p[i].value < list->value || p[i].value == list->value && (p[i].promo < 0)) break;\r
749   }\r
750   last[stm] += 2;\r
751   for(j=last[stm]; j>i; j-= 2) p[j] = p[j-2];\r
752   p[i].value = v = list->value;\r
753   for(j=0; j<8; j++) p[i].range[j] = list->range[j^4*(WHITE-stm)];\r
754   switch(Range(p[i].range)) {\r
755     case 1:  p[i].pst = BH; break;\r
756     case 2:  p[i].pst = bsize; break;\r
757     default: p[i].pst = bsize + BH; break;\r
758   }\r
759   key = (stm == WHITE ? &list->whiteKey : &list->blackKey);\r
760   if(!*key) *key = ~(myRandom()*myRandom());\r
761   p[i].promoGain = EasyProm(list->range); // flag easy promotion based on white view\r
762   p[i].pieceKey = *key;\r
763   p[i].promoFlag = 0;\r
764   p[i].bulk = list->bulk;\r
765   p[i].mobWeight = v > 600 ? 0 : v >= 400 ? 1 : v >= 300 ? 2 : v > 150 ? 3 : v >= 100 ? 2 : 0;\r
766   if(Lance(list->range))\r
767     p[i].mobWeight = 5 + 3*(list->range[4]==X), p[i].pst = 0; // clear path but don't move forward\r
768   for(j=stm+2; j<= last[stm]; j+=2) {\r
769     if(p[j].promo >= i) p[j].promo += 2;\r
770   }\r
771   if(royal[stm] >= i) royal[stm] += 2;\r
772   if(kylin[stm] >= i) kylin[stm] += 2;\r
773   if(p[i].value == (currentVariant == V_SHO ? 410 : 280) ) royal[stm] = i, p[i].pst = 0;\r
774   p[i].qval = (currentVariant == V_TENJIKU ? list->ranking : 0); // jump-capture hierarchy\r
775   return i;\r
776 }\r
777 \r
778 void\r
779 SetUp(char *array, int var)\r
780 {\r
781   int i, j, n, m, nr, color;\r
782   char c, *q, name[3], prince = 0;\r
783   PieceDesc *p1, *p2;\r
784   last[WHITE] = 1; last[BLACK] = 0;\r
785   for(i=0; ; i++) {\r
786 //printf("next rank: %s\n", array);\r
787     for(j = BW*i; ; j++) {\r
788       int pflag=0;\r
789       if(*array == '+') pflag++, array++;\r
790       c = name[0] = *array++;\r
791       if(!c) goto eos;\r
792       if(c == '.') continue;\r
793       if(c == '/') break;\r
794       name[1] = name[2] = 0;\r
795       if(c == ':') name[0] = *array++, name[1] = *array++;\r
796       if(name[0] >= 'a') {\r
797         color = BLACK;\r
798         name[0] += 'A' - 'a';\r
799         if(name[1]) name[1] += 'A' - 'a';\r
800       } else color = WHITE;\r
801       if(!strcmp(name, "CP")) prince |= color+1; // remember if we added Crown Prince\r
802       p1 = LookUp(name, var);\r
803       if(!p1) printf("tellusererror Unknown piece '%s' in setup\n", name), exit(-1);\r
804       if(pflag && p1->promoted) p1 = LookUp(p1->promoted, var); // use promoted piece instead\r
805       n = AddPiece(color, p1);\r
806       p[n].pos = j;\r
807       if(p1->promoted[0] && !pflag) {\r
808         if(!strcmp(p1->promoted, "CP")) prince |= color+1; // remember if we added Crown Prince\r
809         p2 = LookUp(p1->promoted, var);\r
810         m = AddPiece(color, p2);\r
811         if(m <= n) n += 2;\r
812         p[n].promo = m;\r
813         p[n].promoFlag = IsUpwardCompatible(p2->range, p1->range) * DONT_DEFER + CAN_PROMOTE;\r
814         if(Forward(p1->range)) p[n].promoFlag |= LAST_RANK; // Pieces that only move forward can't defer on last rank\r
815         if(!strcmp(p1->name, "N")) p[n].promoFlag |= CANT_DEFER; // Knights can't defer on last 2 ranks\r
816         p[n].promoFlag &= n&1 ? P_WHITE : P_BLACK;\r
817         p[m].promo = -1;\r
818         p[m].pos = ABSENT;\r
819         if(p[m].value == LVAL) kylin[color] = n; // remember piece that promotes to Lion\r
820       } else p[n].promo = -1; // unpromotable piece\r
821 //printf("piece = %c%-2s %d(%d) %d/%d\n", color ? 'w' : 'b', name, n, m, last[color], last[!color]);\r
822     }\r
823   }\r
824  eos:\r
825   // add dummy Crown Princes if not yet added\r
826   if(!(prince & WHITE+1)) p[AddPiece(WHITE, LookUp("CP", V_CHU))].pos = ABSENT;\r
827   if(!(prince & BLACK+1)) p[AddPiece(BLACK, LookUp("CP", V_CHU))].pos = ABSENT;\r
828   for(i=0; i<8; i++)  fireFlags[i] = 0;\r
829   for(i=2, n=1; i<10; i++) if(p[i].value == FVAL) {\r
830     int x = p[i].pos; // mark all burn zones\r
831     fireFlags[i-2] = n;\r
832     if(x != ABSENT) for(j=0; j<8; j++) fireBoard[x+kStep[j]] |= n;\r
833     n <<= 1;\r
834   }\r
835   for(i=0; i<BH; i++) for(j=0; j<BH; j++) board[BW*i+j] = EMPTY;\r
836   for(i=WHITE+2; i<=last[WHITE]; i+=2) if(p[i].pos != ABSENT) {\r
837     int g = p[i].promoGain;\r
838     if((j = p[i].promo) > 0 && g)\r
839       p[i].promoGain = (p[j].value - p[i].value - g)*1.25, p[i].value = p[j].value - g;\r
840     else p[i].promoGain = 0;\r
841     if(i == kylin[WHITE]) p[i].promoGain = 1.25*KYLIN, p[i].value += KYLIN;\r
842     if(j > 0 && p[i].pst == BH) p[i].pst = 3*BW*BH;      // use white pre-prom bonus\r
843     board[p[i].pos] = i;\r
844     rootEval += p[i].value + PST[p[i].pst + p[i].pos];\r
845     promoDelta += p[i].promoGain;\r
846     filling += p[i].bulk;\r
847   } else p[i].promoGain = 0;\r
848   for(i=BLACK+2; i<=last[BLACK]; i+=2) if(p[i].pos != ABSENT) {\r
849     int g = p[i].promoGain;\r
850     if((j = p[i].promo) > 0 && g)\r
851       p[i].promoGain = (p[j].value - p[i].value - g)*1.25, p[i].value = p[j].value - g;\r
852     else p[i].promoGain = 0;\r
853     if(i == kylin[BLACK]) p[i].promoGain = 1.25*KYLIN, p[i].value += KYLIN;\r
854     if(j > 0 && p[i].pst == BH) p[i].pst = 3*BW*BH + BH; // use black pre-prom bonus\r
855     if(j > 0 && p[i].pst == bsize) p[i].pst = 4*BW*BH;      // use white pre-prom bonus\r
856     board[p[i].pos] = i;\r
857     rootEval -= p[i].value + PST[p[i].pst + p[i].pos];\r
858     promoDelta -= p[i].promoGain;\r
859     filling += p[i].bulk;\r
860   } else p[i].promoGain = 0;\r
861   StackMultis(WHITE);\r
862   StackMultis(BLACK);\r
863   stm = WHITE; xstm = BLACK;\r
864 }\r
865 \r
866 int myRandom()\r
867 {\r
868   return rand() ^ rand()>>10 ^ rand() << 10 ^ rand() << 20;\r
869 }\r
870 \r
871 void\r
872 Init (int var)\r
873 {\r
874   int i, j, k;\r
875 \r
876   currentVariant = variants[var].varNr;\r
877   bWidth  = variants[var].boardWidth;\r
878   bHeight = variants[var].boardRanks;\r
879   zone    = variants[var].zoneDepth;\r
880   array   = variants[var].array;\r
881   bsize = bWidth*bHeight;\r
882   chuFlag = (currentVariant == V_CHU);\r
883   tenFlag = (currentVariant == V_TENJIKU);\r
884   chessFlag = (currentVariant == V_CHESS);\r
885   repDraws  = (currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK);\r
886   ll = 0; lr = bHeight - 1; ul = (bHeight - 1)*bWidth; ur = ul + bHeight - 1;\r
887 \r
888   for(i= -1; i<9; i++) { // board steps in linear coordinates\r
889     kStep[i] = STEP(direction[i&7].x,   direction[i&7].y);       // King\r
890     nStep[i] = STEP(direction[(i&7)+8].x, direction[(i&7)+8].y); // Knight\r
891   }\r
892   for(i=0; i<8; i++) neighbors[i+1] = kStep[i];\r
893 \r
894   for(i=0; i<8; i++) { // Lion double-move decoding tables\r
895     for(j=0; j<8; j++) {\r
896       epList[8*i+j] = kStep[i];\r
897       toList[8*i+j] = kStep[j] + kStep[i];\r
898       for(k=0; k<8*i+j; k++)\r
899         if(epList[k] == toList[8*i+j] && toList[k] == epList[8*i+j])\r
900           reverse[k] = 8*i+j, reverse[8*i+j] = k;\r
901     }\r
902     // Lion-Dog triple moves\r
903     toList[64+i] = 3*kStep[i]; epList[64+i] =   kStep[i];\r
904     toList[72+i] = 3*kStep[i]; epList[72+i] = 2*kStep[i];\r
905     toList[80+i] = 3*kStep[i]; epList[80+i] =   kStep[i]; ep2List[80+i] = 2*kStep[i];\r
906     toList[88+i] =   kStep[i]; epList[88+i] = 2*kStep[i];\r
907   }\r
908 \r
909   // fill distance table\r
910   for(i=0; i<2*BSIZE; i++) {\r
911     distance[i] = 0;\r
912   }\r
913 //  for(i=0; i<8; i++)\r
914 //    for(j=1; j<BH; j++)\r
915 //      dist[j * kStep[i]] = j;\r
916 //  if(currentVariant == V_TENJIKU)\r
917     for(i=1-BH; i<BH; i++) for(j=1-BH; j<BH; j++) dist[BW*i+j] = abs(i) > abs(j) ? abs(i) : abs(j);\r
918 \r
919   // hash key tables\r
920   for(i=0; i<bsize; i++) squareKey[i] = ~(myRandom()*myRandom());\r
921 \r
922   // board edge\r
923   for(i=0; i<BSIZE + 11*BHMAX + 6; i++) rawBoard[i] = EDGE;\r
924 \r
925   // promotion zones\r
926   for(i=0; i<BH; i++) for(j=0; j<BH; j++) {\r
927     char v = 0;\r
928     if(i == 0)       v |= LAST_RANK & P_BLACK;\r
929     if(i < 2)        v |= CANT_DEFER & P_BLACK;\r
930     if(i < ZONE)     v |= (CAN_PROMOTE | DONT_DEFER) & P_BLACK; else v &= ~P_BLACK;\r
931     if(i >= BH-ZONE) v |= (CAN_PROMOTE | DONT_DEFER) & P_WHITE; else v &= ~P_WHITE;\r
932     if(i >= BH-2)    v |= CANT_DEFER & P_WHITE;\r
933     if(i == BH-1)    v |= LAST_RANK & P_WHITE;\r
934     promoBoard[BW*i + j] = v;\r
935   }\r
936 \r
937   // piece-square tables\r
938   for(j=0; j<BH; j++) {\r
939    for(i=0; i<BH; i++) {\r
940     int s = BW*i + j, d = BH*(BH-2) - abs(2*i - BH + 1)*(BH-1) - (2*j - BH + 1)*(2*j - BH + 1);\r
941     PST[s] = 2*(i==0 | i==BH-1) + (i==1 | i==BH-2);      // last-rank markers in null table\r
942     PST[BH+s] = d/4 - (i < 2 || i > BH-3 ? 3 : 0) - (j == 0 || j == BH-1 ? 5 : 0)\r
943                     + 3*(i==zone || i==BH-zone-1);       // stepper centralization\r
944     PST[BH*BW+s] = d/6;                                  // double-stepper centralization\r
945     PST[BH*BW+BH+s] = d/12 - 5*(i==BH/2 || i==(BH-1)/2); // slider centralization\r
946     PST[2*BH*BW+s] = j < 3 || j > BH-4 ? (i < 3 ? 7 : i == 3 ? 4 : i == 4 ? 2 : 0) : 0;\r
947     PST[2*BH*BW+BH+s] = ((BH-1)*(BH-1) - (2*i - BH + 1)*(2*i - BH + 1) - (2*j - BH + 1)*(2*j - BH + 1))/6;\r
948     PST[3*BH*BW+s] = PST[3*BH*BW+BH+s] = PST[BH+s];      // as stepper, but with pre-promotion bonus W/B\r
949     PST[4*BH*BW+s] = PST[BW*BH+s];                       // as jumper, but with pre-promotion bonus B\r
950     PST[4*BH*BW+BH+s] = BW*(zone - 1 - i);               // board step to enter promo zone black\r
951    }\r
952    if(zone > 0) PST[3*BW*BH+BW*(BH-1-zone) + j] += 10, PST[3*BW*BH+BH + BW*zone + j] += 10;\r
953 #if KYLIN\r
954    // pre-promotion bonuses for jumpers\r
955    if(zone > 0) PST[BW*BH + BW*(BH-2-zone) + j] = PST[4*BW*BH + BW*(zone+1) + j] = 100,\r
956                 PST[BW*BH + BW*(BH-1-zone) + j] = PST[4*BW*BH + BW*zone + j] = 200;\r
957 #endif\r
958   }\r
959 \r
960   p[EDGE].qval = 5; // tenjiku jump-capturer sentinel\r
961 }\r
962 \r
963 int\r
964 PSTest ()\r
965 {\r
966   int r, f, score, tot=0;\r
967   for(r=0; r<BH; r++) for(f=0; f<BH; f++) {\r
968     int s = BW*r+f;\r
969     int piece = board[s];\r
970     if(!piece) continue;\r
971     score = p[piece].value + PST[p[piece].pst + s];\r
972     if(piece & 1) tot += score; else tot -= score;\r
973   }\r
974   return tot;\r
975 }\r
976 \r
977 int\r
978 Dtest ()\r
979 {\r
980   int r, f, score, tot=0;\r
981   for(r=0; r<BH; r++) for(f=0; f<BH; f++) {\r
982     int s = BW*r+f;\r
983     int piece = board[s];\r
984     if(!piece) continue;\r
985     score = p[piece].promoGain;\r
986     if(piece & 1) tot += score; else tot -= score;\r
987   }\r
988   return tot;\r
989 }\r
990 \r
991 int flag;\r
992 \r
993 inline int\r
994 NewNonCapture (int x, int y, int promoFlags)\r
995 {\r
996   if(board[y] != EMPTY) return 1; // edge, capture or own piece\r
997 //if(flag) printf("# add %c%d%c%d, pf=%d\n", x%BW+'a',x/BW,y%BW+'a',y/BW, promoFlags);\r
998   if( (promoBoard[x] | promoBoard[y]) & promoFlags &&\r
999       (!entryProm || promoBoard[y] & ~promoBoard[x] & CAN_PROMOTE )){ // piece can promote with this move\r
1000     moveStack[msp++] = moveStack[nonCapts];           // create space for promotion\r
1001     moveStack[nonCapts++] = x<<SQLEN | y | PROMOTE;   // push promotion\r
1002     if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative\r
1003       moveStack[msp++] = x<<SQLEN | y;                // push deferral\r
1004       if( (promoBoard[x] & CAN_PROMOTE) == 0 ) {      // enters zone\r
1005         moveStack[msp-1] |= DEFER;                    // flag that promo-suppression takes place after this move\r
1006       }\r
1007     }\r
1008   } else\r
1009     moveStack[msp++] = x<<SQLEN | y; // push normal move\r
1010 //if(flag) printf("msp=%d nc=%d\n", msp, nonCapts);     \r
1011   return 0;\r
1012 }\r
1013 \r
1014 inline int\r
1015 NewCapture (int x, int y, int promoFlags)\r
1016 {\r
1017   if( (promoBoard[x] | promoBoard[y]) & promoFlags) { // piece can promote with this move\r
1018     moveStack[msp++] = x<<SQLEN | y | PROMOTE;        // push promotion\r
1019     if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative\r
1020       moveStack[msp++] = x<<SQLEN | y;                // push deferral\r
1021       if( (promoBoard[x] & CAN_PROMOTE) == 0 ) {      // enters zone\r
1022         moveStack[msp-1] |= DEFER;                    // flag that promo-suppression takes place after this move\r
1023       }\r
1024     }\r
1025   } else\r
1026     moveStack[msp++] = x<<SQLEN | y; // push normal move\r
1027   return 0;\r
1028 }\r
1029 \r
1030 char map[49]; // 7x7 map for area movers\r
1031 char mapStep[] = { 7, 8, 1, -6, -7, -8, -1, 6 };\r
1032 char rowMask[] = { 0100, 0140, 0160, 070, 034, 016, 07, 03, 01 };\r
1033 char rows[9];\r
1034 \r
1035 int\r
1036 AreaStep (int from, int x, int flags, int n, int d)\r
1037 {\r
1038   int i;\r
1039   for(i=0; i<8; i++) {\r
1040     int to = x + kStep[i], m = n + mapStep[i];\r
1041     if(board[to] == EDGE) continue; // off board\r
1042     if(map[m] >= d) continue;   // already done\r
1043     if(!map[m]) moveStack[msp++] = from<<SQLEN | to;\r
1044     map[m] = d;\r
1045     if(d > 1 && board[to] == EMPTY) AreaStep(from, to, flags, m, d-1);\r
1046   }\r
1047 }\r
1048 \r
1049 int\r
1050 AreaMoves (int from, int piece, int range)\r
1051 {\r
1052   int i;\r
1053   for(i=0; i<49; i++) map[i] = 0;\r
1054   map[3*7+7] = range;\r
1055   AreaStep(from, from, p[piece].promoFlag, 3*7+3, range);\r
1056 }\r
1057 \r
1058 void\r
1059 MarkBurns (int x)\r
1060 { // make bitmap of squares in FI (7x7) neighborhood where opponents can be captured or burned\r
1061   int r=x>>5, f=x&15, top=8, bottom=0, b=0, t=8, left=0, right=8; // 9x9 area; assumes 32x16 board\r
1062   if(r < 4) bottom = 4 - r, rows[b=bottom-1] = 0; else\r
1063   if(r > 11) top   = 19 - r, rows[t=top+1] = 0; // adjust area to board edges\r
1064   if(f < 4) left   = 4 - f; else if(f > 11) right = 19 - f;\r
1065   for(r=bottom; r<=top; r++) {\r
1066     int mask = 0, y = x + 16*r;\r
1067     for(f=left; f <= right; f++) {\r
1068       if(board[y + f - (4*16+4)] != EMPTY && (board[y + f - (4*16+4)] & TYPE) == xstm)\r
1069         mask |= rowMask[f]; // on-rank attacks\r
1070     }\r
1071     rows[r+2] = mask;\r
1072   }\r
1073   for(r=b; r<=t-2; r++) rows[r] |= rows[r+1] | rows[r+2]; // smear vertically\r
1074 }\r
1075 \r
1076 int\r
1077 GenNonCapts (int promoSuppress)\r
1078 {\r
1079   int i, j, nullMove = ABSENT;\r
1080   for(i=stm+2; i<=last[stm]; i+=2) {\r
1081     int x = p[i].pos, pFlag = p[i].promoFlag;\r
1082     if(x == ABSENT) continue;\r
1083     if(x == promoSuppress && chuFlag) pFlag = 0;\r
1084     for(j=0; j<8; j++) {\r
1085       int y, v = kStep[j], r = p[i].range[j];\r
1086       if(r < 0) { // jumping piece, special treatment\r
1087         if(r == N) { // pure Knightm do off-ray jump\r
1088           NewNonCapture(x, x + nStep[j], pFlag);\r
1089         } else\r
1090         if(r >= S) { // in any case, do a jump of 2\r
1091           int occup = NewNonCapture(x, x + 2*v, pFlag);\r
1092           if(r < J) { // Lion power, also single step\r
1093             if(!NewNonCapture(x, x + v, pFlag)) nullMove = x; else occup = 1;\r
1094             if(r <= L) { // true Lion, also Knight jump\r
1095               if(!occup & r < L) for(y=x+2*v; !NewNonCapture(x, y+=v, pFlag) && r == S; ); // BS and FF moves\r
1096               v = nStep[j];\r
1097               NewNonCapture(x, x + v, pFlag);\r
1098             }\r
1099           }\r
1100         } else\r
1101         if(r == M) { // FIDE Pawn; check double-move\r
1102           if(!NewNonCapture(x, x+v, pFlag) && chessFlag && promoBoard[x-v])\r
1103             NewNonCapture(x, x+2*v, pFlag), moveStack[msp-1] |= DEFER; // use promoSuppress flag as e.p. flag\r
1104         }\r
1105         continue;\r
1106       }\r
1107       y = x;\r
1108       while(r-- > 0)\r
1109         if(NewNonCapture(x, y+=v, pFlag)) break;\r
1110     }\r
1111   }\r
1112   return nullMove;\r
1113 }\r
1114 \r
1115 void\r
1116 report (int x, int y, int i)\r
1117 {\r
1118 }\r
1119 \r
1120 int\r
1121 MapOneColor (int start, int last, int *map)\r
1122 {\r
1123   int i, j, k, totMob = 0;\r
1124   for(i=start+2; i<=last; i+=2) {\r
1125     int mob = 0;\r
1126     if(p[i].pos == ABSENT) continue;\r
1127     for(j=0; j<8; j++) {\r
1128       int x = p[i].pos, v = kStep[j], r = p[i].range[j];\r
1129       if(r < 0) { // jumping piece, special treatment\r
1130         if(r == N) {\r
1131           x += nStep[j];\r
1132           if(board[x] != EMPTY && board[x] != EDGE)\r
1133             map[2*x + start] += one[8];\r
1134         } else\r
1135         if(r >= S) { // in any case, do a jump of 2\r
1136           if(board[x + 2*v] != EMPTY && board[x + 2*v] != EDGE)\r
1137             map[2*(x + 2*v) + start] += one[j], mob += (board[x + 2*v] ^ start) & 1;\r
1138           if(r < J) { // Lion power, also single step\r
1139             if(board[x + v] != EMPTY && board[x + v] != EDGE)\r
1140               map[2*(x + v) + start] += one[j];\r
1141             if(r == T) { // Lion Dog, also jump of 3\r
1142               if(board[x + 3*v] != EMPTY && board[x + 3*v] != EDGE)\r
1143                 map[2*(x + 3*v) + start] += one[j];\r
1144             } else\r
1145             if(r <= L) {  // true Lion, also Knight jump\r
1146               if(r < L) { // Lion plus (limited) range\r
1147                 int y = x, n = 0;\r
1148                 r = (r == S ? 36 : 3);\r
1149                 while(n++ <= r) {\r
1150                   if(board[y+=v] == EDGE) break;\r
1151                   if(board[y] != EMPTY) {\r
1152                     if(n > 2) map[2*y + start] += one[j]; // outside Lion range\r
1153                     break;\r
1154                   }\r
1155                 }\r
1156               }\r
1157               v = nStep[j];\r
1158               if(board[x + v] != EMPTY && board[x + v] != EDGE)\r
1159                 map[2*(x + v) + start] += one[8];\r
1160             }\r
1161           }\r
1162         } else\r
1163         if(r == C) { // FIDE Pawn diagonal\r
1164           if(board[x + v] != EMPTY && board[x + v] != EDGE)\r
1165             map[2*(x + v) + start] += one[j];\r
1166         }\r
1167         continue;\r
1168       }\r
1169       while(r-- > 0) {\r
1170         if(board[x+=v] != EMPTY) {\r
1171           mob += dist[x-v-p[i].pos];\r
1172           if(board[x] != EDGE) map[2*x + start] += one[j], mob += (board[x] ^ start) & 1;\r
1173 #if 1\r
1174           if(p[i].range[j] > X) { // jump capturer\r
1175             int c = p[i].qval;\r
1176             if(p[board[x]].qval < c) {\r
1177               x += v; // go behind directly captured piece, if jumpable\r
1178               while(p[board[x]].qval < c) { // kludge alert: EDGE has qval = 5, blocking everything\r
1179                 if(board[x] != EMPTY) {\r
1180 //                int n = map[2*x + start] & attackMask[j];\r
1181 //                map[2*x + start] += (n < 3*one[j] ? 3*one[j] : one[j]); // first jumper gets 2 extra (to ease incremental update)\r
1182                   map[2*x + start] += one[j]; // for now use true count\r
1183                 }\r
1184                 x += v;\r
1185               }\r
1186             }\r
1187           }\r
1188 #endif\r
1189           break;\r
1190         }\r
1191       }\r
1192     }\r
1193     totMob += mob * p[i].mobWeight;\r
1194   }\r
1195 if(!level) printf("# mobility %d = %d\n", start, totMob);\r
1196   return totMob;\r
1197 }\r
1198 \r
1199 void\r
1200 MapFromScratch (int *map)\r
1201 {\r
1202   int i;\r
1203   for(i=0; i<2*bsize; i++) map[i] = 0;\r
1204   mobilityScore  = MapOneColor(1, last[WHITE], map);\r
1205   mobilityScore -= MapOneColor(0, last[BLACK], map);\r
1206 }\r
1207 \r
1208 int\r
1209 MakeMove(Move m, UndoInfo *u)\r
1210 {\r
1211   int deferred = ABSENT;\r
1212   // first execute move on board\r
1213   u->from = m>>SQLEN & SQUARE;\r
1214   u->to = m & SQUARE;\r
1215   u->piece = board[u->from];\r
1216   board[u->from] = EMPTY;\r
1217   u->booty = 0;\r
1218   u->gain  = 0;\r
1219   u->loss  = 0;\r
1220   u->revMoveCount = cnt50++;\r
1221   u->savKeyL = hashKeyL;\r
1222   u->savKeyH = hashKeyH;\r
1223   u->epVictim[0] = EMPTY;\r
1224   u->saveDelta = promoDelta;\r
1225   u->filling = filling;\r
1226 \r
1227   if(p[u->piece].promoFlag & LAST_RANK) cnt50 = 0; // forward piece: move is irreversible\r
1228   // TODO: put in some test for forward moves of non-backward pieces?\r
1229 \r
1230   if(p[u->piece].value == FVAL) { // move with Fire Demon\r
1231     int i, f=~fireFlags[u->piece-2];\r
1232     for(i=0; i<8; i++) fireBoard[u->from + kStep[i]] &= f; // clear old burn zone\r
1233   }\r
1234 \r
1235   if(m & (PROMOTE | DEFER)) {\r
1236     if(m & DEFER) { // essential deferral: inform caller, but nothing special\r
1237       deferred = u->to;\r
1238       u->new = u->piece;\r
1239     } else {\r
1240       p[u->piece].pos = ABSENT;\r
1241       u->new = p[u->piece].promo;\r
1242       u->booty = p[u->new].value - p[u->piece].value;\r
1243       cnt50 = 0; // promotion irreversible\r
1244     }\r
1245   } else u->new = u->piece;\r
1246 \r
1247   if(u->to >= SPECIAL) { // two-step Lion move\r
1248     // take care of first e.p. victim\r
1249     u->epSquare = u->from + epList[u->to - SPECIAL]; // decode\r
1250     u->epVictim[0] = board[u->epSquare]; // remember for takeback\r
1251     board[u->epSquare] = EMPTY;       // and remove\r
1252     p[u->epVictim[0]].pos = ABSENT;\r
1253     // now take care of (optional) second e.p. victim\r
1254     u->ep2Square = u->from + ep2List[u->to - SPECIAL]; // This is the (already evacuated) from-square when there is none!\r
1255     u->epVictim[1] = board[u->ep2Square]; // remember\r
1256     board[u->ep2Square] = EMPTY;        // and remove\r
1257     p[u->epVictim[1]].pos = ABSENT;\r
1258     // decode the true to-square, and correct difEval and hash key for the e.p. captures\r
1259     u->to       = u->from + toList[u->to - SPECIAL];\r
1260     u->booty += p[u->epVictim[1]].value + PST[p[u->epVictim[1]].pst + u->ep2Square];\r
1261     u->booty += p[u->epVictim[0]].value + PST[p[u->epVictim[0]].pst + u->epSquare];\r
1262     u->gain  += p[u->epVictim[1]].value;\r
1263     u->gain  += p[u->epVictim[0]].value;\r
1264     promoDelta += p[u->epVictim[0]].promoGain;\r
1265     promoDelta += p[u->epVictim[1]].promoGain;\r
1266     filling  -= p[u->epVictim[0]].bulk;\r
1267     filling  -= p[u->epVictim[1]].bulk;\r
1268     hashKeyL ^= p[u->epVictim[0]].pieceKey * squareKey[u->epSquare];\r
1269     hashKeyH ^= p[u->epVictim[0]].pieceKey * squareKey[u->epSquare+BH];\r
1270     hashKeyL ^= p[u->epVictim[1]].pieceKey * squareKey[u->ep2Square];\r
1271     hashKeyH ^= p[u->epVictim[1]].pieceKey * squareKey[u->ep2Square+BH];\r
1272     if(p[u->piece].value != LVAL && p[u->epVictim[0]].value == LVAL) deferred |= PROMOTE; // flag non-Lion x Lion\r
1273     cnt50 = 0; // double capture irreversible\r
1274   }\r
1275 \r
1276   if(u->fireMask & fireBoard[u->to]) { // we moved next to enemy Fire Demon (must be done after SPECIAL, to decode to-sqr)\r
1277     p[u->piece].pos = ABSENT;          // this is suicide: implement as promotion to EMPTY\r
1278     u->new = EMPTY;\r
1279     u->booty -= p[u->piece].value;\r
1280     cnt50 = 0;\r
1281   } else\r
1282   if(p[u->piece].value == FVAL) { // move with Fire Demon that survives: burn\r
1283     int i, f=fireFlags[u->piece-2];\r
1284     for(i=0; i<8; i++) {\r
1285         int x = u->to + kStep[i], burnVictim = board[x];\r
1286         fireBoard[x] |= f;  // mark new burn zone\r
1287         u->epVictim[i+1] = burnVictim; // remember all neighbors, just in case\r
1288         if(burnVictim != EMPTY && (burnVictim & TYPE) == xstm) { // opponent => actual burn\r
1289           board[x] = EMPTY; // remove it\r
1290           p[burnVictim].pos = ABSENT;\r
1291           u->booty += p[burnVictim].value + PST[p[burnVictim].pst + x];\r
1292           u->gain  += p[burnVictim].value;\r
1293           promoDelta += p[burnVictim].promoGain;\r
1294           filling  -= p[burnVictim].bulk;\r
1295           hashKeyL ^= p[burnVictim].pieceKey * squareKey[x];\r
1296           hashKeyH ^= p[burnVictim].pieceKey * squareKey[x + BH];\r
1297           cnt50 = 0; // actually burning something makes the move irreversible\r
1298         }\r
1299     }\r
1300     u->epVictim[0] = EDGE; // kludge to flag to UnMake this is special move\r
1301   }\r
1302 \r
1303   u->booty += PST[p[u->new].pst + u->to] - PST[p[u->piece].pst + u->from];\r
1304 \r
1305   u->victim = board[u->to];\r
1306   p[u->victim].pos = ABSENT;\r
1307   filling += p[u->new].bulk - p[u->piece].bulk - p[u->victim].bulk;\r
1308   promoDelta += p[u->new].promoGain - p[u->piece].promoGain + p[u->victim].promoGain;\r
1309   u->booty += p[u->victim].value + PST[p[u->victim].pst + u->to];\r
1310   u->gain  += p[u->victim].value;\r
1311   if(u->victim != EMPTY) {\r
1312     cnt50 = 0; // capture irreversible\r
1313     if(attacks[2*u->to + xstm]) u->loss = p[u->piece].value; // protected\r
1314   }\r
1315 \r
1316   p[u->new].pos = u->to;\r
1317   board[u->to] = u->new;\r
1318   promoDelta = -promoDelta;\r
1319 \r
1320   hashKeyL ^= p[u->new].pieceKey * squareKey[u->to]\r
1321            ^  p[u->piece].pieceKey * squareKey[u->from]\r
1322            ^  p[u->victim].pieceKey * squareKey[u->to];\r
1323   hashKeyH ^= p[u->new].pieceKey * squareKey[u->to+BH]\r
1324            ^  p[u->piece].pieceKey * squareKey[u->from+BH]\r
1325            ^  p[u->victim].pieceKey * squareKey[u->to+BH];\r
1326 \r
1327   return deferred;\r
1328 }\r
1329 \r
1330 void\r
1331 UnMake(UndoInfo *u)\r
1332 {\r
1333   if(u->epVictim[0]) { // move with side effects\r
1334     if(u->epVictim[0] == EDGE) { // fire-demon burn\r
1335       int i, f=~fireFlags[u->piece-2];\r
1336       for(i=0; i<8; i++) {\r
1337         int x = u->to + kStep[i];\r
1338         fireBoard[x] &= f;\r
1339         board[x] = u->epVictim[i+1];\r
1340         p[board[x]].pos = x; // even EDGE should have dummy entry in piece list\r
1341       }\r
1342     } else { // put Lion victim of first leg back\r
1343       p[u->epVictim[1]].pos = u->ep2Square;\r
1344       board[u->ep2Square] = u->epVictim[1];\r
1345       p[u->epVictim[0]].pos = u->epSquare;\r
1346       board[u->epSquare] = u->epVictim[0];\r
1347     }\r
1348   }\r
1349 \r
1350   if(p[u->piece].value == FVAL) {\r
1351     int i, f=fireFlags[u->piece-2];\r
1352     for(i=0; i<8; i++) fireBoard[u->from + kStep[i]] |= f; // restore old burn zone\r
1353   }\r
1354 \r
1355   p[u->victim].pos = u->to;\r
1356   board[u->to] = u->victim;  // can be EMPTY\r
1357 \r
1358   p[u->new].pos = ABSENT; \r
1359   p[u->piece].pos = u->from; // this can be the same as above\r
1360   board[u->from] = u->piece;\r
1361 \r
1362   cnt50 = u->revMoveCount;\r
1363   hashKeyL = u->savKeyL;\r
1364   hashKeyH = u->savKeyH;\r
1365   filling  = u->filling;\r
1366   promoDelta = u->saveDelta;\r
1367 }\r
1368         \r
1369 void\r
1370 GenCapts(int sqr, int victimValue)\r
1371 { // generate all moves that capture the piece on the given square\r
1372   int i, range, att = attacks[2*sqr + stm];\r
1373 //printf("GenCapts(%c%d,%d) %08x\n",sqr%BW+'a',sqr/BW,victimValue,att);\r
1374   if(!att) return; // no attackers at all!\r
1375   for(i=0; i<8; i++) {               // try all rays\r
1376     int x, v, jumper, jcapt=0;\r
1377     if(att & attackMask[i]) {        // attacked by move in this direction\r
1378       v = -kStep[i]; x = sqr;\r
1379       while( board[x+=v] == EMPTY ); // scan towards source until we encounter a 'stop'\r
1380 //printf("stop @ %c%d (dir %d)\n",x%BW+'a',x/BW,i);\r
1381       if((board[x] & TYPE) == stm) {               // stop is ours\r
1382         int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];\r
1383 //printf("attacker %d, range %d, dist %d\n", attacker, r, d);\r
1384         if(r >= d || r < L && (d > 3 && r == S || d == 3 && r >= S)) { // it has a plain move in our direction that hits us\r
1385           NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1386           att -= one[i];\r
1387           if(!(att & attackMask[i])) continue; // no more; next direction\r
1388           jcapt = p[board[x]].qval;   // jump-capturer hierarchy\r
1389           while(board[x+=v] == EMPTY);// one attack accounted for, but more to come, so skip to next stop\r
1390         }\r
1391       }\r
1392       // we get here when we are on a piece that dous not attack us through a (limited) ranging move,\r
1393       // it can be our own or an enemy with not (enough) range, or which is blocked\r
1394       do {\r
1395 //printf("scan %x-%x (%d) dir=%d d=%d r=%d att=%o jcapt=%d qval=%d\n", sqr, x, board[x], i, dist[x-sqr], p[board[x]].range[i], att, jcapt, p[board[x]].qval);\r
1396       if((board[x] & TYPE) == stm) {   // stop is ours\r
1397         int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];\r
1398         if(jcapt < p[attacker].qval) { // it is a range jumper that jumps over the barrier\r
1399           if(p[attacker].range[i] > 1) { // assumes all jump-captures are infinite range\r
1400             NewCapture(x, sqr, p[attacker].promoFlag);\r
1401             att -= one[i];\r
1402           }\r
1403 //if(board[x] == EDGE) { printf("edge hit %x-%x dir=%d att=%o\n", sqr, x, i, att); continue; }\r
1404         } else\r
1405         if(r < 0) { // stop has non-standard moves\r
1406           switch(p[attacker].range[i]) { // figure out what he can do (including multi-captures, which causes the complexity)\r
1407             case F: // Lion power + 3-step (as in FF)\r
1408             case S: // Lion power + ranging (as in BS)\r
1409             case L: // Lion\r
1410               if(d > 2) break;\r
1411               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1412               att -= one[i];\r
1413               // now the multi-captures of designated victim together with lower-valued piece\r
1414               if(d == 2) { // primary victim on second ring; look for victims to take in passing\r
1415                 if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr])\r
1416                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1417                 if((i&1) == 0) { // orthogonal: two extra bent paths\r
1418                   v = kStep[i-1];\r
1419                   if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1420                     NewCapture(x, SPECIAL + 8*(i-1&7) + (i+1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1421                   v = kStep[i+1];\r
1422                   if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1423                     NewCapture(x, SPECIAL + 8*(i+1&7) + (i-1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1424                 }\r
1425               } else { // primary victim on first ring\r
1426                 int j;\r
1427                 for(j=0; j<8; j++) { // we can go on in 8 directions after we captured it in passing\r
1428                   int v = kStep[j];\r
1429                   if(sqr + v == x || board[sqr+v] == EMPTY) // hit & run; make sure we include igui (attacker is still at x!)\r
1430                     NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag);\r
1431                   else if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr]) {    // double capture\r
1432                     NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag); // other victim after primary\r
1433                     if(dist[sqr+v-x] == 1) // other victim also on first ring; reverse order is possible\r
1434                       NewCapture(x, SPECIAL + reverse[8*i + j] + victimValue, p[attacker].promoFlag);\r
1435                   }\r
1436                 }\r
1437               }\r
1438               break;\r
1439             case D: // linear Lion move (as in HF, SE)\r
1440               if(d > 2) break;\r
1441               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1442               att -= one[i];\r
1443               if(d == 2) { // check if we can take intermediate with it\r
1444                 if((board[x-v] & TYPE) == xstm && board[x-v] > board[sqr])\r
1445                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // e.p.\r
1446               } else { // d=1; can move on to second, or move back for igui\r
1447                 NewCapture(x, SPECIAL + 8*i + (i^4) + victimValue, p[attacker].promoFlag); // igui\r
1448                 if(board[sqr-v] == EMPTY || (board[sqr-v] & TYPE) == xstm && board[sqr-v] > board[sqr])\r
1449                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // hit and run\r
1450               }\r
1451               break;\r
1452             case J: // plain jump (as in KY, PH)\r
1453               if(d != 2) break;\r
1454               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1455               att -= one[i];\r
1456               break;\r
1457             case C: // FIDE Pawn\r
1458               if(d != 1) break;\r
1459               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1460               att -= one[i];\r
1461           }\r
1462         }\r
1463 //printf("mask[%d] = %o\n", i, att);\r
1464         if((att & attackMask[i]) == 0) break;\r
1465       }\r
1466       // more attacks to come; san for next stop\r
1467       if(jcapt < p[board[x]].qval) jcapt = p[board[x]].qval; // raise barrier for range jumpers further upstream\r
1468       while(board[x+=v] == EMPTY); // this should never run off-board, if the attack map is not corrupted\r
1469       } while(1);\r
1470     }\r
1471   }\r
1472   // off-ray attacks\r
1473   if(att & 0700000000) { // Knight attack\r
1474     for(i=0; i<8; i++) {    // scan all knight jumps to locate source\r
1475       int x = sqr - nStep[i], attacker = board[x];\r
1476       if(attacker == EMPTY || (attacker & TYPE) != stm) continue;\r
1477       if(p[attacker].range[i] <= L && p[attacker].range[i] >= S || p[attacker].range[i] == N) { // has Knight jump in our direction\r
1478         NewCapture(x, sqr + victimValue, p[attacker].promoFlag);   // plain jump (as in N)\r
1479         if(p[attacker].range[i] < N) { // Lion power; generate double captures over two possible intermediates\r
1480           int v = kStep[i]; // leftish path\r
1481           if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1482             NewCapture(x, SPECIAL + 8*i + (i+1&7) + victimValue, p[attacker].promoFlag);\r
1483           v = kStep[i+1];  // rightish path\r
1484           if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1485             NewCapture(x, SPECIAL + 8*(i+1&7) + i + victimValue, p[attacker].promoFlag);\r
1486         }\r
1487       }\r
1488     }\r
1489   }\r
1490 }\r
1491 \r
1492 int\r
1493 Guard (int sqr)\r
1494 {\r
1495   int piece = board[sqr], val;\r
1496   if(piece == EDGE) return 0;\r
1497   val = p[piece].value;\r
1498   if(val == 201) return 3; // Elephant\r
1499   if(val == 152) return 2; // Tiger\r
1500   if(val == 151) return 1; // Gold\r
1501   return 0;\r
1502 }\r
1503 \r
1504 int\r
1505 Fortress (int forward, int king, int lion)\r
1506 { // penalty for lack of Lion-proof fortress\r
1507   int rank = PST[king], anchor, r, l, q;\r
1508   if(!rank) return -300;\r
1509   anchor = king + forward*(rank-1);\r
1510 \r
1511   if(Guard(anchor) == 3 || Guard(anchor+1) == 3 || Guard(anchor-1) == 3) return 0;\r
1512   if(rank == 2 && Guard(king+1) == 3 || Guard(king-1) == 3) return -50;\r
1513   if(Guard(r=anchor) == 2 || Guard(r=anchor+1) == 2 || Guard(r=anchor-1) == 2)\r
1514     return -100 + 50*(Guard(r + forward + 1) == 3 || Guard(r + forward - 1) == 3);\r
1515   return -300;\r
1516 \r
1517   for(r=anchor+1; Guard(r) > 1; r++);\r
1518   for(l=anchor-1; Guard(l) > 1; l--);\r
1519 //if(PATH) printf("# l=%d r=%d\n", l, r);\r
1520   if(Guard(anchor) < 2) {\r
1521     if(r - anchor  > anchor - l || // largest group, or if equal, group that contains elephant\r
1522        r - anchor == anchor - l && Guard(r-1) == 3) l = anchor; else r = anchor;\r
1523   }\r
1524   switch(r - l) {\r
1525     case 1: q = 15; break;                // no shelter at all, maximum penalty\r
1526     case 2: if(Guard(l+1) == 3) q = 10;   // single Elephant offers some shelter\r
1527             else if(Guard(l+forward) == 3 || Guard(l+forward+2) == 3) q = 8; // better if Tiger diagonally in front of it\r
1528             else q = 14;                  // singe tiger almost no help;\r
1529             break;\r
1530     case 3: q = 5 - (Guard(l+1) == 3 || Guard(l+3) == 3); break; // pair is better if it contains Elephant\r
1531     case 4: q = (Guard(l+2) != 3);        // 3 wide: perfect, or nearly so if Elephant not in middle\r
1532     default: ;\r
1533   }\r
1534 //if(PATH) printf("# fortress %d: q=%d l=%d r=%d\n", anchor, q, l, r);\r
1535   return (dist[lion - king] - 23)*q;      // reduce by ~half if Lion very far away\r
1536 }\r
1537 \r
1538 int\r
1539 Surround (int stm, int king, int start)\r
1540 {\r
1541   int i, s=0;\r
1542   for(i=start; i<9; i++) {\r
1543     int v, piece, sq = king + neighbors[i];\r
1544     if((piece = board[sq]) == EDGE || !piece || piece&1^stm) continue;\r
1545     if(p[piece].promoGain) continue;\r
1546     v = p[piece].value;\r
1547     s += -(v > 70) & v;\r
1548   }\r
1549   return (s > 512 ? 512 : s);\r
1550 }\r
1551 \r
1552 int\r
1553 Ftest (int side)\r
1554 {\r
1555   int lion = ABSENT, king;\r
1556   if(p[side+2].value == LVAL) lion = p[side+2].pos;\r
1557   if(lion == ABSENT && p[side+4].value == LVAL) lion = p[side+4].pos;\r
1558   king = p[royal[1-side]].pos; if(king == ABSENT) king = p[royal[1-side]+1].pos;\r
1559   return lion == ABSENT ? 0 : Fortress(side ? -BW : BW, king, lion);\r
1560 }\r
1561 \r
1562 int\r
1563 Evaluate (int difEval)\r
1564 {\r
1565   int wLion = ABSENT, bLion = ABSENT, wKing, bKing, score=mobilityScore, f, i, j;\r
1566 \r
1567   if(p[WHITE+2].value == LVAL) wLion = p[WHITE+2].pos;\r
1568   if(p[BLACK+2].value == LVAL) bLion = p[BLACK+2].pos;\r
1569   if(wLion == ABSENT && p[WHITE+4].value == LVAL) wLion = p[WHITE+4].pos;\r
1570   if(bLion == ABSENT && p[BLACK+4].value == LVAL) bLion = p[BLACK+4].pos;\r
1571 \r
1572 #ifdef LIONTRAP\r
1573 # define lionTrap (PST + 2*BH*BW)\r
1574   // penalty for Lion in enemy corner, when enemy Lion is nearby\r
1575   if(wLion != ABSENT && bLion != ABSENT) { // both have a Lion\r
1576       static int distFac[36] = { 0, 0, 10, 9, 8, 7, 5, 3, 1 };\r
1577       score -= ( (1+9*!attacks[2*wLion+WHITE]) * lionTrap[BW*(BH-1)+BH-1-wLion]\r
1578                - (1+9*!attacks[2*bLion+BLACK]) * lionTrap[bLion] ) * distFac[dist[wLion - bLion]];\r
1579   }\r
1580 \r
1581 # ifdef WINGS\r
1582   // bonus if corner lances are protected by Lion-proof setup (FL + C/S)\r
1583   if(bLion != ABSENT) {\r
1584     if((p[board[BW+lr]].value == 320 || p[board[BW+lr]].value == 220) && \r
1585         p[board[ll+1]].value == 150 && p[board[ll+BW+2]].value == 100) score += 20 + 20*!p[board[ll]].range[2];\r
1586     if((p[board[BW+lr]].value == 320 || p[board[BW+lr]].value == 220) &&\r
1587         p[board[lr-1]].value == 150 && p[board[lr+BW-2]].value == 100) score += 20 + 20*!p[board[lr]].range[2];\r
1588   }\r
1589   if(wLion != ABSENT) {\r
1590     if((p[board[ul-BW]].value == 320 || p[board[ul-BW]].value == 220) &&\r
1591         p[board[ul+1]].value == 150 && p[board[ul-BW+2]].value == 100) score -= 20 + 20*!p[board[ul]].range[2];\r
1592     if((p[board[ur-BW]].value == 320 || p[board[ur-BW]].value == 220) &&\r
1593         p[board[ur-1]].value == 150 && p[board[ur-BW-2]].value == 100) score -= 20 + 20*!p[board[ur]].range[2];\r
1594   }\r
1595 # endif\r
1596 #endif\r
1597 \r
1598 #ifdef KINGSAFETY\r
1599   // basic centralization in end-game (also facilitates bare-King mating)\r
1600   wKing = p[royal[WHITE]].pos; if(wKing == ABSENT) wKing = p[royal[WHITE]+1].pos;\r
1601   bKing = p[royal[BLACK]].pos; if(bKing == ABSENT) bKing = p[royal[BLACK]+1].pos;\r
1602   if(filling < 32) {\r
1603     int lead = (stm == WHITE ? difEval : -difEval);\r
1604     score += (PST[3*BW*BH+wKing] - PST[3*BW*BH+bKing])*(32 - filling) >> 7;\r
1605     if(lead  > 100) score -= PST[3*BW*BH+bKing]*(32 - filling) >> 3; // white leads, drive black K to corner\r
1606     if(lead < -100) score += PST[3*BW*BH+wKing]*(32 - filling) >> 3; // black leads, drive white K to corner\r
1607   }\r
1608 \r
1609 # ifdef FORTRESS\r
1610   f = 0;\r
1611   if(bLion != ABSENT) f += Fortress( BW, wKing, bLion);\r
1612   if(wLion != ABSENT) f -= Fortress(-BW, bKing, wLion);\r
1613   score += (filling < 96 ? f : f*(224 - filling) >> 7); // build up slowly\r
1614 # endif\r
1615 \r
1616 # ifdef KSHIELD\r
1617   score += Surround(WHITE, wKing, 1) - Surround(BLACK, bKing, 1) >> 3;\r
1618 # endif\r
1619 \r
1620 #endif\r
1621 \r
1622 #if KYLIN\r
1623   // bonus for having Kylin in end-game, where it could promote to Lion\r
1624   // depends on board population, defenders around zone entry and proximity to zone\r
1625   if(filling < 128) {\r
1626     int sq;\r
1627     if((wLion = kylin[WHITE]) && (sq = p[wLion].pos) != ABSENT) {\r
1628       int anchor = sq - PST[5*BW*BH - 1 - sq];\r
1629       score += (512 - Surround(BLACK, anchor, 0))*(128 - filling)*PST[p[wLion].pst + sq] >> 15;\r
1630     }\r
1631     if((bLion = kylin[BLACK]) && (sq = p[bLion].pos) != ABSENT) {\r
1632       int anchor = sq + PST[4*BW*BH + BH + sq];\r
1633       score -= (512 - Surround(WHITE, anchor, 0))*(128 - filling)*PST[p[bLion].pst + sq] >> 15;\r
1634     }\r
1635   }\r
1636 #endif\r
1637 \r
1638 #ifdef PAWNBLOCK\r
1639   // penalty for blocking own P or GB: 20 by slider, 10 by other, but 50 if only retreat mode is straight back\r
1640   for(i=last[WHITE]; i > 1 && p[i].value<=50; i-=2) {\r
1641     if((f = p[i].pos) != ABSENT) { // P present,\r
1642       if((j = board[f + BW])&1) // square before it white (odd) piece\r
1643         score -= 10 + 10*(p[j].promoGain > 0) + 30*!(p[j].range[3] || p[j].range[5] || p[j].value==50);\r
1644       if((j = board[f - BW])&1) // square behind it white (odd) piece\r
1645         score += 7*(p[j].promoGain == 0 & p[j].value<=151);\r
1646     }\r
1647   }\r
1648   for(i=last[BLACK]; i > 1 && p[i].value<=50; i-=2) {\r
1649     if((f = p[i].pos) != ABSENT) { // P present,\r
1650       if((j = board[f - BW]) && !(j&1)) // square before non-empty and even (black)\r
1651         score += 10 + 10*(p[j].promoGain > 0) + 30*!(p[j].range[1] || p[j].range[7] || p[j].value==50);\r
1652       if((j = board[f + BW]) && !(j&1)) // square behind non-empty and even (black)\r
1653         score -= 7*(p[j].promoGain == 0 & p[j].value<=151);\r
1654     }\r
1655   }\r
1656 #endif\r
1657 \r
1658   return difEval - (filling*filling*promoDelta >> 16) + (stm ? score : -score);\r
1659 }\r
1660 \r
1661 inline void\r
1662 FireSet (UndoInfo *tb)\r
1663 { // set fireFlags acording to remaining presene of Fire Demons\r
1664   int i;\r
1665   for(i=stm+2; p[i].value == FVAL; i++) // Fire Demons are always leading pieces in list\r
1666     if(p[i].pos != ABSENT) tb->fireMask |= fireFlags[i-2];\r
1667 }\r
1668 \r
1669 void TerminationCheck();\r
1670 \r
1671 #define QSdepth 4\r
1672 \r
1673 int\r
1674 Search (int alpha, int beta, int difEval, int depth, int lmr, int oldPromo, int promoSuppress, int threshold)\r
1675 {\r
1676   int i, j, k, phase, king, nextVictim, to, defer, autoFail=0, inCheck = 0, late=100000;\r
1677   int firstMove, oldMSP = msp, curMove, sorted, bad, dubious, bestMoveNr;\r
1678   int resDep, iterDep, ext;\r
1679   int myPV = pvPtr;\r
1680   int score, bestScore, oldBest, curEval, iterAlpha;\r
1681   Move move, nullMove;\r
1682   UndoInfo tb;\r
1683 #ifdef HASH\r
1684   Move hashMove; int index, nr, hit;\r
1685 #endif\r
1686 if(PATH) /*pboard(board),pmap(attacks, BLACK),*/printf("search(%d) {%d,%d} eval=%d, stm=%d (flag=%d)\n",depth,alpha,beta,difEval,stm,abortFlag),fflush(stdout);\r
1687   xstm = stm ^ WHITE;\r
1688 //printf("map made\n");fflush(stdout);\r
1689 \r
1690   // in-check test and TSUME filter\r
1691   {\r
1692     k = p[king=royal[stm]].pos;\r
1693     if( k == ABSENT) k = p[king + 2].pos;\r
1694     else if(p[king + 2].pos != ABSENT) k = ABSENT; // two kings is no king...\r
1695     if( k != ABSENT) { // check is possible\r
1696       if(!attacks[2*k + xstm]) {\r
1697         if(tsume && tsume & stm+1) {\r
1698           retDep = 60; return INF; // we win when not in check\r
1699         }\r
1700       }\r
1701 #ifdef CHECKEXT\r
1702       else { inCheck = 1; if(depth >= QSdepth) depth++; }\r
1703 #endif\r
1704     }\r
1705   }\r
1706 \r
1707 if(!level) {for(i=0; i<5; i++)printf("# %d %08x, %d\n", i, repStack[200-i], checkStack[200-i]);}\r
1708   // KING CAPTURE\r
1709   k = p[king=royal[xstm]].pos;\r
1710   if( k != ABSENT) {\r
1711     if(attacks[2*k + stm]) {\r
1712       if( p[king + 2].pos == ABSENT ) return INF; // we have an attack on his only King\r
1713     }\r
1714   } else { // he has no king! Test for attacks on Crown Prince\r
1715     k = p[king + 2].pos;\r
1716     if(attacks[2*k + stm]) return INF; // we have attack on Crown Prince\r
1717   }\r
1718 //printf("King safe\n");fflush(stdout);\r
1719   // EVALUATION & WINDOW SHIFT\r
1720   curEval = Evaluate(difEval) -20*inCheck;\r
1721   alpha -= (alpha < curEval);\r
1722   beta  -= (beta <= curEval);\r
1723 \r
1724   if(!(nodes++ & 4095)) TerminationCheck();\r
1725   pv[pvPtr++] = 0; // start empty PV, directly behind PV of parent\r
1726   if(inCheck) lmr = 0; else depth -= lmr; // no LMR of checking moves\r
1727 \r
1728   firstMove = curMove = sorted = msp += 50; // leave 50 empty slots in front of move list\r
1729   iterDep = -(depth == 0); tb.fireMask = phase = 0;\r
1730 \r
1731 #ifdef HASH\r
1732   index = hashKeyL ^ 327*stm ^ (oldPromo + 987981)*(63121 + promoSuppress);\r
1733   index = index + (index >> 16) & hashMask;\r
1734   nr = (hashKeyL >> 30) & 3; hit = -1;\r
1735   if(hashTable[index].lock[nr] == hashKeyH) hit = nr; else\r
1736   if(hashTable[index].lock[4]  == hashKeyH) hit = 4;\r
1737 if(PATH) printf("# probe hash index=%x hit=%d\n", index, hit),fflush(stdout);\r
1738   if(hit >= 0) {\r
1739     bestScore = hashTable[index].score[hit];\r
1740     hashMove = hashTable[index].move[hit];\r
1741     if((bestScore <= alpha || hashTable[index].flag[hit] & H_LOWER) &&\r
1742        (bestScore >= beta  || hashTable[index].flag[hit] & H_UPPER)   ) {\r
1743       iterDep = resDep = hashTable[index].depth[hit]; bestMoveNr = 0;\r
1744       if(!level) iterDep = 0; // no hash cutoff in root\r
1745       if(lmr && bestScore <= alpha && iterDep == depth) depth ++, lmr--; // self-deepening LMR\r
1746       if(pvCuts && iterDep >= depth && hashMove && bestScore < beta && bestScore > alpha)\r
1747         iterDep = depth - 1; // prevent hash cut in PV node\r
1748     }\r
1749   } else { // decide on replacement\r
1750     if(depth >= hashTable[index].depth[nr] ||\r
1751        depth+1 == hashTable[index].depth[nr] && !(nodes&3)) hit = nr; else hit = 4;\r
1752     hashMove = 0;\r
1753   }\r
1754 if(PATH) printf("# iterDep = %d score = %d move = %s\n",iterDep,bestScore,MoveToText(hashMove,0)),fflush(stdout);\r
1755 #endif\r
1756 \r
1757   if(depth > QSdepth && iterDep < QSdepth) iterDep = QSdepth; // full-width: start at least from 1-ply\r
1758 if(PATH)printf("iterDep=%d\n", iterDep);\r
1759   while(++iterDep <= depth) {\r
1760 if(flag && depth>= 0) printf("iter %d:%d\n", depth,iterDep),fflush(stdout);\r
1761     oldBest = bestScore;\r
1762     iterAlpha = alpha; bestScore = -INF; bestMoveNr = 0; resDep = 60;\r
1763 if(PATH)printf("new iter %d\n", iterDep);\r
1764     if(depth <= QSdepth) {\r
1765       bestScore = curEval; resDep = QSdepth;\r
1766       if(bestScore > alpha) {\r
1767         alpha = bestScore;\r
1768 if(PATH)printf("stand pat %d\n", bestScore);\r
1769         if(bestScore >= beta) goto cutoff;\r
1770       }\r
1771     }\r
1772     for(curMove = firstMove; ; curMove++) { // loop over moves\r
1773 if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase, firstMove, curMove, msp);fflush(stdout);\r
1774       // MOVE SOURCE\r
1775       if(curMove >= msp) { // we ran out of moves; generate some new\r
1776 if(PATH)printf("new moves, phase=%d\n", phase);\r
1777         switch(phase) {\r
1778           case 0: // null move\r
1779 #ifdef NULLMOVE\r
1780             if(depth > QSdepth && curEval >= beta && !inCheck && filling > 10) {\r
1781               int nullDep = depth - 3;\r
1782               stm ^= WHITE;\r
1783               score = -Search(-beta, 1-beta, -difEval, nullDep<QSdepth ? QSdepth : nullDep, 0, promoSuppress & SQUARE, ABSENT, INF);\r
1784               xstm = stm; stm ^= WHITE;\r
1785               if(score >= beta) { msp = oldMSP; retDep += 3; pvPtr = myPV; return score + (score < curEval); }\r
1786 //            else depth += lmr, lmr = 0;\r
1787             }\r
1788 #endif\r
1789             if(tenFlag) FireSet(&tb); // in tenjiku we must identify opposing Fire Demons to perform any moves\r
1790 //if(PATH) printf("mask=%x\n",tb.fireMask),pbytes(fireBoard);\r
1791             phase = 1;\r
1792           case 1: // hash move\r
1793             phase = 2;\r
1794 #ifdef HASH\r
1795             if(hashMove && (depth > QSdepth || // must be capture in QS\r
1796                  (hashMove & SQUARE) >= SPECIAL || board[hashMove & SQUARE] != EMPTY)) {\r
1797               moveStack[sorted = msp++] = hashMove;\r
1798               goto extractMove;\r
1799             }\r
1800 #endif\r
1801           case 2: // capture-gen init\r
1802             nextVictim = xstm; autoFail = (depth == 0);\r
1803             phase = 3;\r
1804           case 3: // generate captures\r
1805 if(PATH) printf("%d:%2d:%2d next victim %d/%d\n",level,depth,iterDep,curMove,msp);\r
1806             while(nextVictim < last[xstm]) {          // more victims exist\r
1807               int group, to = p[nextVictim += 2].pos; // take next\r
1808               if(to == ABSENT) continue;              // ignore if absent\r
1809               if(!attacks[2*to + stm]) continue;      // skip if not attacked\r
1810               group = p[nextVictim].value;            // remember value of this found victim\r
1811               if(iterDep <= QSdepth + 1 && 2*group + curEval + 30 < alpha) { resDep = QSdepth + 1; goto cutoff; }\r
1812 if(PATH) printf("%d:%2d:%2d group=%d, to=%c%d\n",level,depth,iterDep,group,to%BW+'a',to/BW+ONE);\r
1813               GenCapts(to, 0);\r
1814 if(PATH) printf("%d:%2d:%2d first=%d msp=%d\n",level,depth,iterDep,firstMove,msp);\r
1815               while(nextVictim < last[xstm] && p[nextVictim+2].value == group) { // more victims of same value exist\r
1816                 to = p[nextVictim += 2].pos;          // take next\r
1817                 if(to == ABSENT) continue;            // ignore if absent\r
1818                 if(!attacks[2*to + stm]) continue;    // skip if not attacked\r
1819 if(PATH) printf("%d:%2d:%2d p=%d, to=%c%d\n",level,depth,iterDep,nextVictim,to%BW+'a',to/BW+ONE);\r
1820                 GenCapts(to, 0);\r
1821 if(PATH) printf("%d:%2d:%2d msp=%d\n",level,depth,iterDep,msp);\r
1822               }\r
1823 if(PATH) printf("captures on %d generated, msp=%d, group=%d, threshold=%d\n", nextVictim, msp, group, threshold);\r
1824               goto extractMove; // in auto-fail phase, only search if they might auto-fail-hi\r
1825             }\r
1826 if(PATH) printf("# autofail=%d\n", autoFail);\r
1827             if(autoFail) { // non-captures cannot auto-fail; flush queued captures first\r
1828 if(PATH) printf("# autofail end (%d-%d)\n", firstMove, msp);\r
1829               autoFail = 0; curMove = firstMove - 1; continue; // release stashed moves for search\r
1830             }\r
1831 //          if(currentVariant == V_CHESS && promoSuppress != ABSENT) { // e.p.\r
1832 //              int n = board[promoSuppress-1];\r
1833 //              if( n != EMPTY && (n&TYPE) == xstm && p[n].value == 8 ) \r
1834 //          }\r
1835             phase = 4; // out of victims: all captures generated\r
1836           case 4: // dubious captures\r
1837 #if 0\r
1838             while( dubious < framePtr + 250 ) // add dubious captures back to move stack\r
1839               moveStack[msp++] = moveStack[dubious++];\r
1840             if(curMove != msp) break;\r
1841 #endif\r
1842             phase = 5;\r
1843           case 5: // killers\r
1844             if(depth <= QSdepth) { if(resDep > QSdepth) resDep = QSdepth; goto cutoff; }\r
1845             phase = 6;\r
1846           case 6: // non-captures\r
1847             nonCapts = msp;\r
1848             nullMove = GenNonCapts(oldPromo);\r
1849 #ifdef KILLERS\r
1850             { // swap killers to front\r
1851               Move h = killer[level][0]; int j = curMove;\r
1852               for(i=curMove; i<msp; i++) if(moveStack[i] == h) { moveStack[i] = moveStack[j]; moveStack[j++] = h; break; }\r
1853               h = killer[level][1];\r
1854               for(i=curMove; i<msp; i++) if(moveStack[i] == h) { moveStack[i] = moveStack[j]; moveStack[j++] = h; break; }\r
1855               late = j;\r
1856             }\r
1857 #else\r
1858             late = j;\r
1859 #endif\r
1860             phase = 7;\r
1861             sorted = msp; // do not sort noncapts\r
1862             break;\r
1863           case 7: // bad captures\r
1864           case 8: // PV null move\r
1865             phase = 9;\r
1866 if(PATH) printf("# null = %0x\n", nullMove);\r
1867             if(nullMove != ABSENT) {\r
1868               moveStack[msp++] = nullMove + (nullMove << SQLEN) | DEFER; // kludge: setting DEFER guarantees != 0, and has no effect\r
1869               break;\r
1870             }\r
1871 //printf("# %d. sqr = %08x null = %08x\n", msp, nullMove, moveStack[msp-1]);\r
1872           case 9:\r
1873             goto cutoff;\r
1874         }\r
1875       }\r
1876 \r
1877       // MOVE EXTRACTION\r
1878     extractMove:\r
1879 //if(flag & depth >= 0 || (PATH)) printf("%2d:%d extract %d/%d\n", depth, iterDep, curMove, msp);\r
1880       if(curMove > sorted) {\r
1881         move = moveStack[sorted=j=curMove];\r
1882         for(i=curMove+1; i<msp; i++)\r
1883           if(moveStack[i] > move) move = moveStack[j=i]; // search move with highest priority\r
1884         moveStack[j] = moveStack[curMove]; moveStack[curMove] = move; // swap highest-priority move to front of remaining\r
1885         if(move == 0) { msp = curMove--; continue; } // all remaining moves must be 0; clip off move list\r
1886       } else {\r
1887         move = moveStack[curMove];\r
1888         if(move == 0) continue; // skip invalidated move\r
1889       }\r
1890 if(flag & depth >= 0) printf("%2d:%d found %d/%d %08x %s\n", depth, iterDep, curMove, msp, moveStack[curMove], MoveToText(moveStack[curMove], 0));\r
1891 \r
1892       // RECURSION\r
1893       stm ^= WHITE;\r
1894       defer = MakeMove(move, &tb);\r
1895       ext = (depth == 0); // when out of depth we extend captures if there was no auto-fail-hi\r
1896 \r
1897 //      if(level == 1 && randomize) tb.booty += (hashKeyH * seed >> 24 & 31) - 20;\r
1898 \r
1899       if(autoFail) {\r
1900         UnMake(&tb); // never search moves during auto-fail phase\r
1901         xstm = stm; stm ^= WHITE;\r
1902         if(tb.gain <= threshold) { // we got to moves that cannot possibly auto-fail\r
1903           autoFail = 0; curMove = firstMove-1; continue; // release all for search\r
1904         }\r
1905         if(tb.gain - tb.loss > threshold) {\r
1906           bestScore = INF+1; resDep = 0; goto leave; // auto-fail-hi\r
1907         } else continue; // ignore for now if not obvious refutation\r
1908       }\r
1909 \r
1910 if(flag & depth >= 0) printf("%2d:%d made %d/%d %s\n", depth, iterDep, curMove, msp, MoveToText(moveStack[curMove], 0));\r
1911       for(i=2; i<=cnt50; i+=2) if(repStack[level-i+200] == hashKeyH) {\r
1912         if(repDraws) { score = 0; goto repetition; }\r
1913         if(!allowRep) {\r
1914           moveStack[curMove] = 0;         // erase forbidden move\r
1915           if(!level) repeatMove[repCnt++] = move & 0xFFFFFF; // remember outlawed move\r
1916         } else { // check for perpetuals\r
1917 //        int repKey = 1;\r
1918 //        for(i-=level; i>1; i-=2) {repKey &= checkStack[200-i]; if(!level)printf("# repkey[%d] = %d\n", 200-i, repKey);}\r
1919           if(inCheck) { score = INF-20; goto repetition; } // we might be subject to perpetual check: score as win\r
1920           if(i == 2 && repStack[level+199] == hashKeyH) { score = INF-20; goto repetition; } // consecutive passing\r
1921         }\r
1922         score = -INF + 8*allowRep; goto repetition;\r
1923       }\r
1924       repStack[level+200] = hashKeyH;\r
1925 \r
1926 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore),fflush(stdout);\r
1927 path[level++] = move;\r
1928 attacks += 2*bsize;\r
1929 MapFromScratch(attacks); // for as long as incremental update does not work.\r
1930 //if(flag & depth >= 0) printf("%2d:%d mapped %d/%d %s\n", depth, iterDep, curMove, msp, MoveToText(moveStack[curMove], 0));\r
1931 //if(PATH) pmap(attacks, stm);\r
1932       if(chuFlag && p[tb.victim].value == LVAL) {// verify legality of Lion capture in Chu Shogi\r
1933         score = 0;\r
1934         if(p[tb.piece].value == LVAL) {          // Ln x Ln: can make Ln 'vulnerable' (if distant and not through intemediate > GB)\r
1935           if(dist[tb.from-tb.to] != 1 && attacks[2*tb.to + stm] && p[tb.epVictim[0]].value <= 50)\r
1936             score = -INF;                           // our Lion is indeed made vulnerable and can be recaptured\r
1937         } else {                                    // other x Ln\r
1938           if(promoSuppress & PROMOTE) score = -INF; // non-Lion captures Lion after opponent did same\r
1939           defer |= PROMOTE;                         // if we started, flag  he cannot do it in reply\r
1940         }\r
1941         if(score == -INF) {\r
1942           if(level == 1) repeatMove[repCnt++] = move & 0xFFFFFF | (p[tb.piece].value == LVAL ? 3<<24 : 1 << 24);\r
1943           moveStack[curMove] = 0; // zap illegal moves\r
1944           goto abortMove;\r
1945         }\r
1946       }\r
1947 #if 1\r
1948       score = -Search(-beta, -iterAlpha, -difEval - tb.booty, iterDep-1+ext,\r
1949                        curMove >= late && iterDep > QSdepth + LMR,\r
1950                                                       promoSuppress & ~PROMOTE, defer, depth ? INF : tb.gain);\r
1951 #else\r
1952       score = 0;\r
1953 #endif\r
1954     abortMove:\r
1955 attacks -= 2*bsize;\r
1956 level--;\r
1957     repetition:\r
1958       UnMake(&tb);\r
1959       xstm = stm; stm ^= WHITE;\r
1960       if(abortFlag > 0) { // unwind search\r
1961 printf("# abort (%d) @ %d\n", abortFlag, level);\r
1962         if(curMove == firstMove) bestScore = oldBest, bestMoveNr = firstMove; // none searched yet\r
1963         goto leave;\r
1964       }\r
1965 #if 1\r
1966 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d  (%d)\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore, GetTickCount()),fflush(stdout);\r
1967 \r
1968       // ALPHA-BETA STUFF\r
1969       if(score > bestScore) {\r
1970         bestScore = score; bestMoveNr = curMove;\r
1971         if(score > iterAlpha) {\r
1972           iterAlpha = score;\r
1973           if(curMove < firstMove + 5) { // if not too much work, sort move to front\r
1974             int i;\r
1975             for(i=curMove; i>firstMove; i--) {\r
1976               moveStack[i] = moveStack[i-1];\r
1977             }\r
1978             moveStack[firstMove] = move;\r
1979           } else { // late move appended in front of list, and leaves hole in list\r
1980             moveStack[--firstMove] = move;\r
1981             moveStack[curMove] = 0;\r
1982           }\r
1983           bestMoveNr = firstMove;\r
1984           if(score >= beta) { // beta cutoff\r
1985 #ifdef KILLERS\r
1986             if(iterDep == depth && move != killer[level][0]\r
1987                  && (tb.victim == EMPTY && (move & SQUARE) < SPECIAL)) {\r
1988               // update killer\r
1989               killer[level][1] = killer[level][0]; killer[level][0] = move;\r
1990             }\r
1991 #endif\r
1992             resDep = retDep+1-ext;\r
1993             goto cutoff;\r
1994           }\r
1995           { int i=pvPtr;\r
1996             for(pvPtr = myPV+1; pv[pvPtr++] = pv[i++]; ); // copy daughter PV\r
1997             pv[myPV] = move;                              // behind our move (pvPtr left at end of copy)\r
1998           }\r
1999         }\r
2000 \r
2001       }\r
2002       if(retDep+1-ext < resDep) resDep = retDep+1-ext;\r
2003 #endif\r
2004     } // next move\r
2005   cutoff:\r
2006     if(!level) { // root node\r
2007       lastRootIter = GetTickCount() - startTime;\r
2008       if(postThinking > 0) {\r
2009         int i;   // WB thinking output\r
2010         printf("%d %d %d %d", iterDep-QSdepth, bestScore, lastRootIter/10, nodes);\r
2011         if(ponderMove) printf(" (%s)", MoveToText(ponderMove, 0));\r
2012         for(i=0; pv[i]; i++) printf(" %s", MoveToText(pv[i], 0));\r
2013         if(iterDep == QSdepth+1) printf(" { root eval = %4.2f dif = %4.2f; abs = %4.2f f=%d D=%4.2f %d/%d}", curEval/100., difEval/100., PSTest()/100., filling, promoDelta/100., Ftest(0), Ftest(1));\r
2014         printf("\n");\r
2015         fflush(stdout);\r
2016       }\r
2017       if(!(abortFlag & 1) && GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish\r
2018     }\r
2019     if(resDep > iterDep) iterDep = resDep; // skip iterations if we got them for free\r
2020 #ifdef LMR\r
2021     if(lmr && bestScore <= alpha && iterDep == depth)\r
2022       depth++, lmr--; // self-deepen on fail-low reply to late move by lowering reduction\r
2023 #endif\r
2024 #ifdef HASH\r
2025     // hash store\r
2026     hashTable[index].lock[hit]  = hashKeyH;\r
2027     hashTable[index].depth[hit] = iterDep;\r
2028     hashTable[index].score[hit] = bestScore;\r
2029     hashTable[index].flag[hit]  = (bestScore < beta) * H_UPPER;\r
2030     if(bestScore > alpha) {\r
2031       hashTable[index].flag[hit] |= H_LOWER;\r
2032       hashTable[index].move[hit]  = bestMoveNr ? moveStack[bestMoveNr] : 0;\r
2033     } else hashTable[index].move[hit] = 0;\r
2034 #endif\r
2035   } // next depth\r
2036 leave:\r
2037   retMSP = msp;\r
2038   retFirst = firstMove;\r
2039   msp = oldMSP; // pop move list\r
2040   pvPtr = myPV; // pop PV\r
2041   retMove = bestMoveNr ? moveStack[bestMoveNr] : 0;\r
2042   retDep = resDep - (inCheck & depth >= QSdepth) + lmr;\r
2043 if(PATH) printf("return %d: %d %d (t=%d s=%d lim=%d)\n", depth, bestScore, curEval, GetTickCount(), startTime, tlim1),fflush(stdout);\r
2044   return bestScore + (bestScore < curEval);\r
2045 }\r
2046 \r
2047 void\r
2048 pplist()\r
2049 {\r
2050   int i, j;\r
2051   for(i=0; i<182; i++) {\r
2052         printf("%3d. %3d %3d %4d   %02x %d %d %x %3d ", i, p[i].value, p[i].promo, p[i].pos, p[i].promoFlag&255, p[i].mobWeight, p[i].qval, p[i].bulk, p[i].promoGain);\r
2053         for(j=0; j<8; j++) printf("  %2d", p[i].range[j]);\r
2054         if(i<2 || i>11) printf("\n"); else printf("  %02x\n", fireFlags[i-2]&255);\r
2055   }\r
2056   printf("last: %d / %d\nroyal %d / %d\n", last[WHITE], last[BLACK], royal[WHITE], royal[BLACK]);\r
2057 }\r
2058 \r
2059 void\r
2060 pboard (int *b)\r
2061 {\r
2062   int i, j;\r
2063   for(i=BH+2; i>-4; i--) {\r
2064     printf("#");\r
2065     for(j=-3; j<BH+3; j++) printf("%4d", b[BW*i+j]);\r
2066     printf("\n");\r
2067   }\r
2068 }\r
2069 \r
2070 void\r
2071 pbytes (unsigned char *b)\r
2072 {\r
2073   int i, j;\r
2074   for(i=BH-1; i>=0; i--) {\r
2075     for(j=0; j<BH; j++) printf("%3x", b[BW*i+j]);\r
2076     printf("\n");\r
2077   }\r
2078 }\r
2079 \r
2080 void\r
2081 pmap (int *m, int col)\r
2082 {\r
2083   int i, j;\r
2084   for(i=BH-1; i>=0; i--) {\r
2085     printf("#");\r
2086     for(j=0; j<BH; j++) printf("%10o", m[2*(BW*i+j)+col]);\r
2087     printf("\n");\r
2088   }\r
2089 }\r
2090 \r
2091 void\r
2092 pmoves(int start, int end)\r
2093 {\r
2094   int i, m, f, t;\r
2095   printf("# move stack from %d to %d\n", start, end);\r
2096   for(i=start; i<end; i++) {\r
2097     m = moveStack[i];\r
2098     f = m>>SQLEN & SQUARE;\r
2099     t = m & SQUARE;\r
2100     printf("# %3d. %08x %3d-%3d %s\n", i, m, f, t, MoveToText(m, 0));\r
2101   }\r
2102 }\r
2103 \r
2104     /********************************************************/\r
2105     /* Example of a WinBoard-protocol driver, by H.G.Muller */\r
2106     /********************************************************/\r
2107 \r
2108     #include <stdio.h>\r
2109 \r
2110     // four different constants, with values for WHITE and BLACK that suit your engine\r
2111     #define NONE    3\r
2112     #define ANALYZE 4\r
2113 \r
2114     // some value that cannot occur as a valid move\r
2115     #define INVALID 0\r
2116 \r
2117     // some parameter of your engine\r
2118     #define MAXMOVES 2000 /* maximum game length  */\r
2119     #define MAXPLY   30   /* maximum search depth */\r
2120 \r
2121     #define OFF 0\r
2122     #define ON  1\r
2123 \r
2124 typedef Move MOVE;\r
2125 \r
2126     int moveNr;              // part of game state; incremented by MakeMove\r
2127     MOVE gameMove[MAXMOVES]; // holds the game history\r
2128 \r
2129     // Some routines your engine should have to do the various essential things\r
2130     int  MakeMove2(int stm, MOVE move);      // performs move, and returns new side to move\r
2131     void UnMake2(MOVE move);                 // unmakes the move;\r
2132     int  Setup2(char *fen);                  // sets up the position from the given FEN, and returns the new side to move\r
2133     void SetMemorySize(int n);              // if n is different from last time, resize all tables to make memory usage below n MB\r
2134     char *MoveToText(MOVE move, int m);     // converts the move from your internal format to text like e2e2, e1g1, a7a8q.\r
2135     MOVE ParseMove(char *moveText);         // converts a long-algebraic text move to your internal move format\r
2136     int  SearchBestMove(MOVE *move, MOVE *ponderMove);\r
2137     void PonderUntilInput(int stm);         // Search current position for stm, deepening forever until there is input.\r
2138 \r
2139 UndoInfo undoInfo;\r
2140 int sup0, sup1, sup2; // promo suppression squares\r
2141 int lastLift, lastPut;\r
2142 \r
2143 int\r
2144 InCheck ()\r
2145 {\r
2146   int k = p[royal[stm]].pos;\r
2147   if( k == ABSENT) k = p[royal[stm] + 2].pos;\r
2148   else if(p[royal[stm] + 2].pos != ABSENT) k = ABSENT; // two kings is no king...\r
2149   if( k != ABSENT) {\r
2150     MapFromScratch(attacks);\r
2151     if(attacks[2*k + 1 - stm]) return 1;\r
2152   }\r
2153   return 0;\r
2154 }\r
2155 \r
2156 int\r
2157 MakeMove2 (int stm, MOVE move)\r
2158 {\r
2159   int i, inCheck = InCheck();\r
2160   FireSet(&undoInfo);\r
2161   sup0 = sup1; sup1 = sup2;\r
2162   sup2 = MakeMove(move, &undoInfo);\r
2163   if(chuFlag && p[undoInfo.victim].value == LVAL && p[undoInfo.piece].value != LVAL) sup2 |= PROMOTE;\r
2164   rootEval = -rootEval - undoInfo.booty;\r
2165   for(i=0; i<200; i++) repStack[i] = repStack[i+1], checkStack[i] = checkStack[i+1];\r
2166   repStack[199] = hashKeyH, checkStack[199] = inCheck;\r
2167 printf("# makemove %08x %c%d %c%d\n", move, sup1%BW+'a', sup1/BW, sup2%BW+'a', sup2/BW);\r
2168   return stm ^ WHITE;\r
2169 }\r
2170 \r
2171 void\r
2172 UnMake2 (MOVE move)\r
2173 {\r
2174   int i;\r
2175   rootEval = -rootEval - undoInfo.booty;\r
2176   UnMake(&undoInfo);\r
2177   for(i=200; i>0; i--) repStack[i] = repStack[i-1], checkStack[i] = checkStack[i-1];\r
2178   sup2 = sup1; sup1 = sup0;\r
2179 }\r
2180 \r
2181 char fenNames[] = "RV....DKDEFL..DHGB......SMLNKN..FK....BT..VM..PH...."; // pairs of char\r
2182 char fenPromo[] = "WLDHSMSECPB R HFDE....WHFB..LNG ..DKVMFS..FO..FK...."; // pairs of char\r
2183 \r
2184 char *\r
2185 Convert (char *fen)\r
2186 {\r
2187   char *p = fenArray, *q, *rows[36], tmp[4000];\r
2188   int n=0;\r
2189   printf("# convert FEN '%s'\n", fen);\r
2190   q = strchr(fen, ' '); if(q) *q = 0; q = fen;\r
2191   do { rows[n++] = q; q = strchr(q, '/'); if(!q) break; *q++ = 0; } while(1);\r
2192   *tmp = 0;\r
2193   while(--n >= 0) { strcat(tmp, rows[n]); if(n) strcat(tmp, "/"); }\r
2194   fen = tmp;\r
2195   printf("# flipped FEN '%s'\n", fen);\r
2196   while(*fen) {\r
2197     if(*fen == ' ') { *p = 0; break; }\r
2198     if(n=atoi(fen)) fen++; // digits read\r
2199     if(n > 9) fen++; // double digit\r
2200     while(n-- > 0) *p++ = '.'; // expand to empty squares\r
2201     if(isalpha(*fen)) {\r
2202       char *table = fenNames;\r
2203       n = *fen > 'Z' ? 'a' - 'A' : 0;\r
2204       if((currentVariant == V_CHESS || currentVariant == V_SHATRANJ ||\r
2205           currentVariant == V_MAKRUK || currentVariant == V_SHO) && *fen - n == 'N' // In Chess N is Knight, not Lion\r
2206            || table[2* (*fen - 'A' - n)] == '.') *p++ = *fen; else {\r
2207         *p++ = ':';\r
2208         *p++ = table[2* (*fen - 'A' - n)] + n;\r
2209         *p++ = table[2* (*fen - 'A' - n)+1] + n;\r
2210       }\r
2211     } else *p++ = *fen;\r
2212     fen++;\r
2213   }\r
2214   printf("# converted FEN '%s'\n", fenArray);\r
2215   return fenArray;\r
2216 }\r
2217 \r
2218 int\r
2219 Setup2 (char *fen)\r
2220 {\r
2221   int stm = WHITE;\r
2222   if(fen) {\r
2223     char *q = strchr(fen, '\n');\r
2224     if(q) *q = 0;\r
2225     if(q = strchr(fen, ' ')) stm = (q[1] == 'b' ? BLACK : WHITE); // fen contains color field\r
2226     if(strchr(fen, '.') || strchr(fen, ':')) array = fen; else array = Convert(fen);\r
2227   }\r
2228   rootEval = promoDelta = filling = cnt50 = moveNr = 0;\r
2229   SetUp(array, currentVariant);\r
2230   strcpy(startPos, array);\r
2231   sup0 = sup1 = sup2 = ABSENT;\r
2232   hashKeyH = hashKeyL = 87620895*currentVariant;\r
2233   return stm;\r
2234 }\r
2235 \r
2236 void\r
2237 SetMemorySize (int n)\r
2238 {\r
2239 #ifdef HASH\r
2240   static HashBucket *realHash;\r
2241   static intptr_t oldSize;\r
2242   intptr_t l, m = 1;\r
2243   while(m*sizeof(HashBucket) <= n*512UL) m <<= 1; // take largest power-of-2 that fits\r
2244   if(m != oldSize) {\r
2245     if(oldSize) free(realHash);\r
2246     hashMask = m*1024 - 1; oldSize = m;\r
2247     realHash = malloc(m*1024*sizeof(HashBucket) + 64);\r
2248     l = (intptr_t) realHash; hashTable = (HashBucket*) (l & ~63UL); // align with cache line\r
2249   }\r
2250 #endif\r
2251 }\r
2252 \r
2253 char *\r
2254 MoveToText (MOVE move, int multiLine)\r
2255 {\r
2256   static char buf[50];\r
2257   int f = move>>SQLEN & SQUARE, g = f, t = move & SQUARE;\r
2258   char *promoChar = "";\r
2259   if(f == t) { sprintf(buf, "@@@@"); return buf; } // null-move notation in WB protocol\r
2260   buf[0] = '\0';\r
2261   if(t >= SPECIAL) { // kludgy! Print as side effect non-standard WB command to remove victims from double-capture (breaks hint command!)\r
2262     int e = f + epList[t - SPECIAL];\r
2263 //    printf("take %c%d\n", e%BW+'a', e/BW+ONE);\r
2264     sprintf(buf, "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;\r
2265     if(multiLine) printf("move %s\n", buf), buf[0] = '\0';\r
2266     if(ep2List[t - SPECIAL]) {\r
2267       e = g + ep2List[t - SPECIAL];\r
2268 //      printf("take %c%d\n", e%BW+'a', e/BW+ONE);\r
2269       sprintf(buf+strlen(buf), "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;\r
2270     if(multiLine) printf("move %s\n", buf), buf[0] = '\0';\r
2271     }\r
2272     t = g + toList[t - SPECIAL];\r
2273   }\r
2274   if(move & PROMOTE) promoChar = currentVariant == V_MAKRUK ? "m" : repDraws ? "q" : "+";\r
2275   sprintf(buf+strlen(buf), "%c%d%c%d%s", f%BW+'a', f/BW+ONE, t%BW+'a', t/BW+ONE,  promoChar);\r
2276   return buf;\r
2277 }\r
2278 \r
2279 int\r
2280 ReadSquare (char *p, int *sqr)\r
2281 {\r
2282   int i=0, f, r;\r
2283   f = p[0] - 'a';\r
2284   r = atoi(p + 1) - ONE;\r
2285   *sqr = r*BW + f;\r
2286   return 2 + (r + ONE > 9);\r
2287 }\r
2288 \r
2289 int listStart, listEnd;\r
2290 char boardCopy[BSIZE];\r
2291 \r
2292 void\r
2293 ListMoves ()\r
2294 { // create move list on move stack\r
2295   int i;\r
2296   for(i=0; i< BSIZE; i++) boardCopy[i] = !!board[i];\r
2297 MapFromScratch(attacks);\r
2298   postThinking--; repCnt = 0; tlim1 = tlim2 = tlim3 = 1e8; abortFlag = msp = 0;\r
2299   Search(-INF-1, INF+1, 0, QSdepth+1, 0, sup1 & ~PROMOTE, sup2, INF);\r
2300   postThinking++;\r
2301 \r
2302   listStart = retFirst; listEnd = msp = retMSP;\r
2303 }\r
2304 \r
2305 MOVE\r
2306 ParseMove (char *moveText)\r
2307 {\r
2308   int i, j, f, t, t2, e, ret, deferred=0;\r
2309   char c = moveText[0];\r
2310   moveText += ReadSquare(moveText, &f);\r
2311   moveText += ReadSquare(moveText, &t); t2 = t;\r
2312   if(*moveText == ',') {\r
2313     moveText++;\r
2314     moveText += ReadSquare(moveText, &e);\r
2315     if(e != t) return INVALID; // must continue with same piece\r
2316     e = t;\r
2317     moveText += ReadSquare(moveText, &t);\r
2318     for(i=0; i<8; i++) if(f + kStep[i] == e) break;\r
2319     if(i >= 8) return INVALID; // this rejects Lion Dog 2+1 and 2-1 moves!\r
2320     for(j=0; j<8; j++) if(e + kStep[j] == t) break;\r
2321     if(j >= 8) return INVALID; // this rejects Lion Dog 1+2 moves!\r
2322     t2 = SPECIAL + 8*i + j;\r
2323   }\r
2324   ret = f<<SQLEN | t2;\r
2325   if(*moveText != '\n' && *moveText != '=') ret |= PROMOTE;\r
2326 printf("# suppress = %c%d\n", sup1%BW+'a', sup1/BW);\r
2327 //  ListMoves();\r
2328   for(i=listStart; i<listEnd; i++) {\r
2329     if(moveStack[i] == INVALID) continue;\r
2330     if(c == '@' && (moveStack[i] & SQUARE) == (moveStack[i] >> SQLEN & SQUARE)) break; // any null move matches @@@@\r
2331     if((moveStack[i] & (PROMOTE | DEFER-1)) == ret) break;\r
2332     if((moveStack[i] & DEFER-1) == ret) deferred = i; // promoted version of entered non-promotion is legal\r
2333   }\r
2334 printf("# moveNr = %d in {%d,%d}\n", i, listStart, listEnd);\r
2335   if(i>=listEnd) { // no exact match\r
2336     if(deferred) { // but maybe non-sensical deferral\r
2337       int flags = p[board[f]].promoFlag;\r
2338 printf("# deferral of %d\n", deferred);\r
2339       i = deferred; // in any case we take that move\r
2340       if(!(flags & promoBoard[t] & (CANT_DEFER | LAST_RANK))) { // but change it into a deferral if that is allowed\r
2341         moveStack[i] &= ~PROMOTE;\r
2342         if(p[board[f]].value == 40) p[board[f]].promoFlag &= LAST_RANK; else\r
2343         if(!(flags & promoBoard[f])) moveStack[i] |= DEFER; // came from outside zone, so essential deferral\r
2344       }\r
2345     }\r
2346     if(i >= listEnd) {\r
2347       for(i=listStart; i<listEnd; i++) printf("# %d. %08x %08x %s\n", i-50, moveStack[i], ret, MoveToText(moveStack[i], 0));\r
2348       reason = NULL;\r
2349       for(i=0; i<repCnt; i++) {if((repeatMove[i] & 0xFFFFFF) == ret) {\r
2350         if(repeatMove[i] & 1<<24) reason = (repeatMove[i] & 1<<25 ? "Distant capture of protected Lion" : "Counterstrike against Lion");\r
2351         else reason = "Repeats earlier position";\r
2352         break;\r
2353       }\r
2354  printf("# %d. %08x %08x %s\n", i, repeatMove[i], ret, MoveToText(repeatMove[i], 0));\r
2355 }\r
2356     }\r
2357   }\r
2358   return (i >= listEnd ? INVALID : moveStack[i]);\r
2359 }\r
2360 \r
2361 void\r
2362 Highlight(char *coords)\r
2363 {\r
2364   int i, j, n, sqr, cnt=0;\r
2365   char b[BSIZE], buf[2000], *q;\r
2366   for(i=0; i<bsize; i++) b[i] = 0;\r
2367   ReadSquare(coords, &sqr);\r
2368 //  ListMoves();\r
2369   for(i=listStart; i<listEnd; i++) {\r
2370     if(sqr == (moveStack[i]>>SQLEN & SQUARE)) {\r
2371       int t = moveStack[i] & SQUARE;\r
2372       if(t >= SPECIAL) {\r
2373         int e = sqr + epList[t - SPECIAL]; // decode\r
2374         b[e] = 'C';\r
2375         continue;\r
2376       }\r
2377       if(!b[t]) b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++;\r
2378       if(moveStack[i] & PROMOTE) b[t] = 'M';\r
2379     }\r
2380   }\r
2381   if(!cnt) { // no moves from given square\r
2382     if(sqr != lastPut) return; // refrain from sending empty FEN\r
2383     // we lifted a piece for second leg of move\r
2384     for(i=listStart; i<listEnd; i++) {\r
2385       if(lastLift == (moveStack[i]>>SQLEN & SQUARE)) {\r
2386         int e, t = moveStack[i] & SQUARE;\r
2387         if(t < SPECIAL) continue; // only special moves\r
2388         e = lastLift + epList[t - SPECIAL]; // decode\r
2389         t = lastLift + toList[t - SPECIAL];\r
2390         if(e != sqr) continue;\r
2391         b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++;\r
2392       }\r
2393     }\r
2394     if(!cnt) return;\r
2395   } else lastLift = sqr; // remember\r
2396   lastPut = ABSENT;\r
2397   q = buf;\r
2398   for(i=BH-1; i>=0; i--) {\r
2399     for(j=0; j<BH; j++) {\r
2400       n = BW*i + j;\r
2401       if(b[n]) *q++ = b[n]; else {\r
2402         if(q > buf && q[-1] <= '9' && q[-1] >= '0') {\r
2403           q[-1]++;\r
2404           if(q[-1] > '9') {\r
2405             if(q > buf+1 && q[-2] <= '9' && q[-2] >= '0') q[-2]++; else q[-1] = '1', *q++ = '0';\r
2406           }\r
2407         } else *q++ = '1';\r
2408       }\r
2409     }\r
2410     *q++ = '/';\r
2411   }\r
2412   q[-1] = 0;\r
2413   printf("highlight %s\n", buf);\r
2414 }\r
2415 \r
2416 int timeLeft;                            // timeleft on engine's clock\r
2417 int mps, timeControl, inc, timePerMove;  // time-control parameters, to be used by Search\r
2418 char inBuf[8000], command[80], ponderMoveText[20];\r
2419 \r
2420 void\r
2421 SetSearchTimes (int timeLeft)\r
2422 {\r
2423   int targetTime, movesLeft = BW*BH/4 + 20;\r
2424   if(mps) movesLeft = mps - (moveNr>>1)%mps;\r
2425   targetTime = (timeLeft - 1000*inc) / (movesLeft + 2) + 1000 * inc;\r
2426   if(moveNr < 30) targetTime *= 0.5 + moveNr/60.; // speedup in opening\r
2427   if(timePerMove > 0) targetTime = 0.4*timeLeft, movesLeft = 1;\r
2428   tlim1 = 0.4*targetTime;\r
2429   tlim2 = 2.4*targetTime;\r
2430   tlim3 = 5*timeLeft / (movesLeft + 4.1);\r
2431 printf("# limits %d, %d, %d mode = %d\n", tlim1, tlim2, tlim3, abortFlag);\r
2432 }\r
2433 \r
2434 int\r
2435 SearchBestMove (MOVE *move, MOVE *ponderMove)\r
2436 {\r
2437   int score, i;\r
2438 printf("# SearchBestMove\n");\r
2439   startTime = GetTickCount();\r
2440   nodes = 0;\r
2441 printf("# s=%d\n", startTime);fflush(stdout);\r
2442 MapFromScratch(attacks);\r
2443   retMove = INVALID; repCnt = 0;\r
2444   score = Search(-INF-1, INF+1, rootEval, maxDepth, 0, sup1, sup2, INF);\r
2445   *move = retMove;\r
2446   *ponderMove = pv[1];\r
2447 printf("# best=%s\n", MoveToText(pv[0],0));\r
2448 printf("# ponder=%s\n", MoveToText(pv[1],0));\r
2449   return score;\r
2450 }\r
2451 \r
2452 \r
2453     int TakeBack(int n)\r
2454     { // reset the game and then replay it to the desired point\r
2455       int last, stm;\r
2456       last = moveNr - n; if(last < 0) last = 0;\r
2457       Init(currentVariant); stm = Setup2(startPos);\r
2458 printf("# setup done");fflush(stdout);\r
2459       for(moveNr=0; moveNr<last; moveNr++) stm = MakeMove2(stm, gameMove[moveNr]),printf("make %2d: %x\n", moveNr, gameMove[moveNr]);\r
2460       return stm;\r
2461     }\r
2462 \r
2463     void PrintResult(int stm, int score)\r
2464     {\r
2465       char tail[100];\r
2466       if(reason) sprintf(tail, " {%s}", reason); else *tail = 0;\r
2467       if(score == 0) printf("1/2-1/2%s\n", tail);\r
2468       if(score > 0 && stm == WHITE || score < 0 && stm == BLACK) printf("1-0%s\n", tail);\r
2469       else printf("0-1%s\n", tail);\r
2470     }\r
2471 \r
2472     void GetLine(int root)\r
2473     {\r
2474       int i, c;\r
2475       while(1) {\r
2476         // wait for input, and read it until we have collected a complete line\r
2477         for(i = 0; (inBuf[i] = c = getchar()) != '\n'; i++) if(c == EOF || i>7997) exit(0);\r
2478         inBuf[i+1] = 0;\r
2479 \r
2480         // extract the first word\r
2481         sscanf(inBuf, "%s", command);\r
2482 printf("# in (mode = %d,%d): %s\n", root, abortFlag, command);\r
2483         if(!strcmp(command, "otim"))    { continue; } // do not start pondering after receiving time commands, as move will follow immediately\r
2484         if(!strcmp(command, "time"))    { sscanf(inBuf, "time %d", &timeLeft); continue; }\r
2485         if(!strcmp(command, "put"))     { ReadSquare(inBuf+4, &lastPut); continue; }  // ditto\r
2486         if(!strcmp(command, "."))       { inBuf[0] = 0; return; } // ignore for now\r
2487         if(!strcmp(command, "hover"))   { inBuf[0] = 0; return; } // ignore for now\r
2488         if(!strcmp(command, "lift"))    { inBuf[0] = 0; Highlight(inBuf+5); return; } // treat here\r
2489         if(!root && !strcmp(command, "usermove")) {\r
2490 printf("# move = %s#ponder = %s", inBuf+9, ponderMoveText);\r
2491           abortFlag = !!strcmp(inBuf+9, ponderMoveText);\r
2492           if(!abortFlag) { // ponder hit, continue as time-based search\r
2493 printf("# ponder hit\n");\r
2494             SetSearchTimes(10*timeLeft + GetTickCount() - startTime); // add time we already have been pondering to total\r
2495             if(lastRootIter > tlim1) abortFlag = 2; // abort instantly if we are in iteration we should not have started\r
2496             inBuf[0] = 0; ponderMove = INVALID;\r
2497             return;\r
2498           }\r
2499         }\r
2500         abortFlag = 1;\r
2501         return;\r
2502       }\r
2503     }\r
2504 \r
2505     void\r
2506     TerminationCheck()\r
2507     {\r
2508       if(abortFlag < 0) { // check for input\r
2509         if(InputWaiting()) GetLine(0); // read & examine input command\r
2510       } else {        // check for time\r
2511         if(GetTickCount() - startTime > tlim3) abortFlag = 2;\r
2512       }\r
2513     }\r
2514 \r
2515     main()\r
2516     {\r
2517       int engineSide=NONE;                     // side played by engine\r
2518       MOVE move;\r
2519       int i, score, curVarNr;\r
2520 \r
2521   Init(V_CHU); // Chu\r
2522       seed = startTime = GetTickCount(); moveNr = 0; // initialize random\r
2523 \r
2524       while(1) { // infinite loop\r
2525 \r
2526         fflush(stdout);                 // make sure everything is printed before we do something that might take time\r
2527         *inBuf = 0; if(moveNr >= 20) randomize = OFF;\r
2528 //if(moveNr >20) printf("resign\n");\r
2529 \r
2530 #ifdef HASH\r
2531         if(hashMask)\r
2532 #endif\r
2533         if(listEnd == 0) ListMoves();   // always maintain a list of legal moves in root position\r
2534         abortFlag = -(ponder && WHITE+BLACK-stm == engineSide && moveNr); // pondering and opponent on move\r
2535         if(stm == engineSide || abortFlag && ponderMove) {      // if it is the engine's turn to move, set it thinking, and let it move\r
2536 printf("# start search: stm=%d engine=%d (flag=%d)\n", stm, engineSide, abortFlag);\r
2537           if(abortFlag) {\r
2538             stm = MakeMove2(stm, ponderMove);                           // for pondering, play speculative move\r
2539             gameMove[moveNr++] = ponderMove;                            // remember in game\r
2540             sprintf(ponderMoveText, "%s\n", MoveToText(ponderMove, 0)); // for detecting ponder hits\r
2541 printf("# ponder move = %s", ponderMoveText);\r
2542           } else SetSearchTimes(10*timeLeft);                           // for thinking, schedule end time\r
2543 pboard(board);\r
2544           score = SearchBestMove(&move, &ponderMove);\r
2545           if(abortFlag == 1) { // ponder search was interrupted (and no hit)\r
2546             UnMake2(INVALID); moveNr--; stm ^= WHITE;    // take ponder move back if we made one\r
2547             abortFlag = 0;\r
2548           } else\r
2549           if(move == INVALID) {         // game apparently ended\r
2550             int kcapt = 0, xstm = stm ^ WHITE, king, k = p[king=royal[xstm]].pos;\r
2551             if( k != ABSENT) { // test if King capture possible\r
2552               if(attacks[2*k + stm]) {\r
2553                 if( p[king + 2].pos == ABSENT ) kcapt = 1; // we have an attack on his only King\r
2554               }\r
2555             } else { // he has no king! Test for attacks on Crown Prince\r
2556               k = p[king + 2].pos;\r
2557               if(attacks[2*k + stm]) kcapt = 1; // we have attack on Crown Prince\r
2558             }\r
2559             if(kcapt) { // print King capture before claiming\r
2560               GenCapts(k, 0);\r
2561               printf("move %s\n", MoveToText(moveStack[msp-1], 1));\r
2562               reason = "king capture";\r
2563             } else reason = "resign";\r
2564             engineSide = NONE;          // so stop playing\r
2565             PrintResult(stm, score);\r
2566           } else {\r
2567             stm = MakeMove2(stm, move);  // assumes MakeMove returns new side to move\r
2568             gameMove[moveNr++] = move;   // remember game\r
2569             printf("move %s\n", MoveToText(move, 1));\r
2570             listEnd = 0;\r
2571             continue;                    // go check if we should ponder\r
2572           }\r
2573         } else\r
2574         if(engineSide == ANALYZE || abortFlag) { // in analysis, we always ponder the position\r
2575             Move dummy;\r
2576             *ponderMoveText = 0; // forces miss on any move\r
2577             abortFlag = -1;      // set pondering\r
2578             pvCuts = noCut;\r
2579             SearchBestMove(&dummy, &dummy);\r
2580             abortFlag = pvCuts = 0;\r
2581         }\r
2582 \r
2583         fflush(stdout);         // make sure everything is printed before we do something that might take time\r
2584         if(!*inBuf) GetLine(1); // takes care of time and otim commands\r
2585 \r
2586         // recognize the command,and execute it\r
2587         if(!strcmp(command, "quit"))    { break; } // breaks out of infinite loop\r
2588         if(!strcmp(command, "force"))   { engineSide = NONE;    continue; }\r
2589         if(!strcmp(command, "analyze")) { engineSide = ANALYZE; continue; }\r
2590         if(!strcmp(command, "exit"))    { engineSide = NONE;    continue; }\r
2591         if(!strcmp(command, "level"))   {\r
2592           int min, sec=0;\r
2593           sscanf(inBuf, "level %d %d %d", &mps, &min, &inc) == 3 ||  // if this does not work, it must be min:sec format\r
2594           sscanf(inBuf, "level %d %d:%d %d", &mps, &min, &sec, &inc);\r
2595           timeControl = 60*min + sec; timePerMove = -1;\r
2596           continue;\r
2597         }\r
2598         if(!strcmp(command, "protover")){\r
2599           printf("feature ping=1 setboard=1 colors=0 usermove=1 memory=1 debug=1 sigint=0 sigterm=0\n");\r
2600           printf("feature variants=\"normal,shatranj,makruk,chu,dai,tenjiku,12x12+0_fairy,9x9+0_shogi\"\n");\r
2601           printf("feature myname=\"HaChu " VERSION "\" highlight=1\n");\r
2602           printf("feature option=\"Full analysis PV -check 1\"\n"); // example of an engine-defined option\r
2603           printf("feature option=\"Allow repeats -check 0\"\n");\r
2604           printf("feature option=\"Promote on entry -check 0\"\n");\r
2605           printf("feature option=\"Resign -check 0\"\n");           // \r
2606           printf("feature option=\"Contempt -spin 0 -200 200\"\n"); // and another one\r
2607           printf("feature option=\"Tsume -combo no /// Sente mates /// Gote mates\"\n");\r
2608           printf("feature done=1\n");\r
2609           continue;\r
2610         }\r
2611         if(!strcmp(command, "option")) { // setting of engine-define option; find out which\r
2612           if(sscanf(inBuf+7, "Full analysis PV=%d", &noCut)  == 1) continue;\r
2613           if(sscanf(inBuf+7, "Allow repeats=%d", &allowRep)  == 1) continue;\r
2614           if(sscanf(inBuf+7, "Resign=%d",   &resign)         == 1) continue;\r
2615           if(sscanf(inBuf+7, "Contempt=%d", &contemptFactor) == 1) continue;\r
2616           if(sscanf(inBuf+7, "Promote on entry=%d", &entryProm) == 1) continue;\r
2617           if(sscanf(inBuf+7, "Tsume=%s", command) == 1) {\r
2618             if(!strcmp(command, "no"))    tsume = 0; else\r
2619             if(!strcmp(command, "Sente")) tsume = 1; else\r
2620             if(!strcmp(command, "Gote"))  tsume = 2;\r
2621             continue;\r
2622           }\r
2623           continue;\r
2624         }\r
2625         if(!strcmp(command, "sd"))      { sscanf(inBuf, "sd %d", &maxDepth);    continue; }\r
2626         if(!strcmp(command, "st"))      { sscanf(inBuf, "st %d", &timePerMove); continue; }\r
2627         if(!strcmp(command, "memory"))  { SetMemorySize(atoi(inBuf+7)); continue; }\r
2628         if(!strcmp(command, "ping"))    { printf("pong%s", inBuf+4); continue; }\r
2629     //  if(!strcmp(command, ""))        { sscanf(inBuf, " %d", &); continue; }\r
2630         if(!strcmp(command, "easy"))    { ponder = OFF; continue; }\r
2631         if(!strcmp(command, "hard"))    { ponder = ON;  continue; }\r
2632         if(!strcmp(command, "go"))      { engineSide = stm;  continue; }\r
2633         if(!strcmp(command, "post"))    { postThinking = ON; continue; }\r
2634         if(!strcmp(command, "nopost"))  { postThinking = OFF;continue; }\r
2635         if(!strcmp(command, "random"))  { randomize = ON;    continue; }\r
2636         if(!strcmp(command, "hint"))    { if(ponderMove != INVALID) printf("Hint: %s\n", MoveToText(ponderMove, 0)); continue; }\r
2637         if(!strcmp(command, "book"))    {  continue; }\r
2638         // non-standard commands\r
2639         if(!strcmp(command, "p"))       { pboard(board); continue; }\r
2640         if(!strcmp(command, "f"))       { pbytes(fireBoard); continue; }\r
2641         if(!strcmp(command, "w"))       { MapOneColor(WHITE, last[WHITE], attacks); pmap(attacks, WHITE); continue; }\r
2642         if(!strcmp(command, "b"))       { MapOneColor(BLACK, last[BLACK], attacks); pmap(attacks, BLACK); continue; }\r
2643         if(!strcmp(command, "l"))       { pplist(); continue; }\r
2644         // ignored commands:\r
2645         if(!strcmp(command, "xboard"))  { continue; }\r
2646         if(!strcmp(command, "computer")){ comp = 1; continue; }\r
2647         if(!strcmp(command, "name"))    { continue; }\r
2648         if(!strcmp(command, "ics"))     { continue; }\r
2649         if(!strcmp(command, "accepted")){ continue; }\r
2650         if(!strcmp(command, "rejected")){ continue; }\r
2651         if(!strcmp(command, "result"))  { engineSide = NONE; continue; }\r
2652         if(!strcmp(command, "hover"))   { continue; }\r
2653         if(!strcmp(command, ""))  {  continue; }\r
2654         if(!strcmp(command, "usermove")){\r
2655           int move = ParseMove(inBuf+9);\r
2656 pboard(board);\r
2657           if(move == INVALID) {\r
2658             if(reason) printf("Illegal move {%s}\n", reason); else printf("%s\n", reason="Illegal move");\r
2659             if(comp) PrintResult(stm, -INF); // against computer: claim\r
2660           } else {\r
2661             stm = MakeMove2(stm, move);\r
2662             ponderMove = INVALID; listEnd = 0;\r
2663             gameMove[moveNr++] = move;  // remember game\r
2664           }\r
2665           continue;\r
2666         }\r
2667         ponderMove = INVALID; // the following commands change the position, invalidating ponder move\r
2668         listEnd = 0;\r
2669         if(!strcmp(command, "new"))     {\r
2670           engineSide = BLACK; Init(V_CHESS); stm = Setup2(NULL); maxDepth = MAXPLY; randomize = OFF; curVarNr = comp = 0;\r
2671           continue;\r
2672         }\r
2673         if(!strcmp(command, "variant")) {\r
2674           for(i=0; i<7; i++) {\r
2675             sscanf(inBuf+8, "%s", command);\r
2676             if(!strcmp(variants[i].name, command)) {\r
2677               Init(curVarNr = i); stm = Setup2(NULL); break;\r
2678             }\r
2679           }\r
2680           repStack[199] = hashKeyH, checkStack[199] = 0;\r
2681           continue;\r
2682         }\r
2683         if(!strcmp(command, "setboard")){ engineSide = NONE;  Init(curVarNr); stm = Setup2(inBuf+9); continue; }\r
2684         if(!strcmp(command, "undo"))    { stm = TakeBack(1); continue; }\r
2685         if(!strcmp(command, "remove"))  { stm = TakeBack(2); continue; }\r
2686         printf("Error: unknown command\n");\r
2687       }\r
2688     }\r
2689 \r