Implement repetition detection
[hachu.git] / hachu.c
1 /***********************************************************************/\r
2 /*                               HaChu                                 */\r
3 /* A WinBoard engine for large (dropless) Shogi variants by H.G.Muller */\r
4 /* The engine is based on incremental updating of an attack map and    */\r
5 /* mobility scores, since the effort in this only grows proportional   */\r
6 /* to board edge length, rather than board area.                       */\r
7 /***********************************************************************/\r
8 \r
9 // TODO:\r
10 // in GenCapts we do not generate jumps of more than two squares yet\r
11 // Chu rules for Lion capture\r
12 // promotions by pieces with Lion power stepping in & out the zone in same turn\r
13 // promotion on capture\r
14 \r
15 #define VERSION 0.0\r
16 \r
17 //define PATH level==0 || level==1 && path[0] == 0x55893\r
18 #define PATH 0\r
19 \r
20 #include <stdio.h>\r
21 #include <stdlib.h>\r
22 #include <string.h>\r
23 #include <signal.h>\r
24 #include <time.h>\r
25 \r
26 #ifdef WIN32 \r
27 #    include <windows.h>\r
28 #else\r
29 #    include <sys/time.h>\r
30      int GetTickCount() // with thanks to Tord\r
31      {  struct timeval t;\r
32         gettimeofday(&t, NULL);\r
33         return t.tv_sec*1000 + t.tv_usec/1000;\r
34      }\r
35 #endif\r
36 \r
37 #define BW 24\r
38 #define BH 12\r
39 #define BSIZE BW*BH*2\r
40 #define ZONE 4\r
41 \r
42 #define ONE 0\r
43 \r
44 #define BLACK      0\r
45 #define WHITE      1\r
46 #define EMPTY      0\r
47 #define EDGE   (1<<11)\r
48 #define TYPE   (WHITE|BLACK|EDGE)\r
49 #define ABSENT  4095\r
50 #define INF     8000\r
51 #define NPIECES 2000               /* length of piece list    */\r
52 \r
53 #define SQLEN    11                /* bits in square number   */\r
54 #define SQUARE  ((1<<SQLEN) - 1)   /* mask for square in move */\r
55 #define DEFER   (1<<2*SQLEN)       /* deferral on zone entry  */\r
56 #define PROMOTE (1<<2*SQLEN+1)     /* promotion bit in move   */\r
57 #define SPECIAL  1500              /* start of special moves  */\r
58 #define STEP(X,Y) (BW*(X)+ (Y))\r
59 #define SORTKEY(X) 0\r
60 \r
61 #define UPDATE_MOBILITY(X,Y)\r
62 #define ADDMOVE(X,Y)\r
63 \r
64 // promotion codes\r
65 #define CAN_PROMOTE 0x11\r
66 #define DONT_DEFER  0x22\r
67 #define CANT_DEFER  0x44\r
68 #define LAST_RANK   0x88\r
69 #define P_WHITE     0x0F\r
70 #define P_BLACK     0xF0\r
71 \r
72 typedef unsigned int Move;\r
73 \r
74 char *MoveToText(Move move, int m);     // from WB driver\r
75 void pmap (int *m, int col);\r
76 \r
77 typedef struct {\r
78   char *name, *promoted;\r
79   int value;\r
80   signed char range[8];\r
81   int whiteKey, blackKey;\r
82 } PieceDesc;\r
83 \r
84 typedef struct {\r
85   int from, to, piece, victim, new, booty, epSquare, epVictim, ep2Square, ep2Victim, revMoveCount, savKeyL, savKeyH;\r
86 } UndoInfo;\r
87 \r
88 int stm, xstm, hashKeyH, hashKeyL, framePtr, msp, nonCapts, rootEval, retMSP, retFirst, pvPtr, level, cnt50, chuFlag=1;\r
89 int nodes, startTime, tlim1, tlim2;\r
90 Move retMove, moveStack[10000], path[100], repStack[300], pv[1000];\r
91 \r
92 #define X 36 /* slider              */\r
93 #define J -1 /* jump                */\r
94 #define N -2 /* Knight              */\r
95 #define D -3 /* linear double move  */\r
96 #define T -4 /* linear triple move  */\r
97 #define L -5 /* true Lion move      */\r
98 #define F -6 /* Lion + 3-step       */\r
99 #define S -7 /* Lion + range        */\r
100 #define H -9 /* hook move           */\r
101 \r
102 PieceDesc chuPieces[] = {\r
103   {"LN", "",  100, { L,L,L,L,L,L,L,L } }, // lion\r
104   {"FK", "",   60, { X,X,X,X,X,X,X,X } }, // free king\r
105   {"SE", "",   55, { X,D,X,X,X,X,X,D } }, // soaring eagle\r
106   {"HF", "",   50, { D,X,X,X,X,X,X,X } }, // horned falcon\r
107   {"FO", "",   40, { X,X,0,X,X,X,0,X } }, // flying ox\r
108   {"FB", "",   40, { 0,X,X,X,0,X,X,X } }, // free boar\r
109   {"DK", "SE", 40, { X,1,X,1,X,1,X,1 } }, // dragon king\r
110   {"DH", "HF", 35, { 1,X,1,X,1,X,1,X } }, // dragon horse\r
111   {"WH", "",   35, { X,X,0,0,X,0,0,X } }, // white horse\r
112   {"R",  "DK", 30, { X,0,X,0,X,0,X,0 } }, // rook\r
113   {"FS", "",   30, { X,1,1,1,X,1,1,1 } }, // flying stag\r
114   {"WL", "",   25, { X,0,0,X,X,X,0,0 } }, // whale\r
115   {"K",  "",   28, { 1,1,1,1,1,1,1,1 } }, // king\r
116   {"CP", "",   27, { 1,1,1,1,1,1,1,1 } }, // king\r
117   {"B",  "DH", 25, { 0,X,0,X,0,X,0,X } }, // bishop\r
118   {"VM", "FO", 20, { X,0,1,0,X,0,1,0 } }, // vertical mover\r
119   {"SM", "FB", 20, { 1,0,X,0,1,0,X,0 } }, // side mover\r
120   {"DE", "CP", 20, { 1,1,1,1,0,1,1,1 } }, // drunk elephant\r
121   {"BT", "FS", 15, { 0,1,1,1,1,1,1,1 } }, // blind tiger\r
122   {"G",  "R",  15, { 1,1,1,0,1,0,1,1 } }, // gold\r
123   {"FL", "B",  15, { 1,1,0,1,1,1,0,1 } }, // ferocious leopard\r
124   {"KN", "LN", 15, { J,1,J,1,J,1,J,1 } }, // kirin\r
125   {"PH", "FK", 15, { 1,J,1,J,1,J,1,J } }, // phoenix\r
126   {"RV", "WL", 15, { X,0,0,0,X,0,0,0 } }, // reverse chariot\r
127   {"L",  "WH", 15, { X,0,0,0,0,0,0,0 } }, // lance\r
128   {"S",  "VM", 10, { 1,1,0,1,0,1,0,1 } }, // silver\r
129   {"C",  "SM", 10, { 1,1,0,0,1,0,0,1 } }, // copper\r
130   {"GB", "DE", 5,  { 1,0,0,0,1,0,0,0 } }, // go between\r
131   {"P",  "G",  4,  { 1,0,0,0,0,0,0,0 } }, // pawn\r
132   { NULL }  // sentinel\r
133 };\r
134 \r
135 PieceDesc daiPieces[] = {\r
136   {"FD", "G", 15, { 0,2,0,2,0,2,0,2 } }, // Flying Dragon\r
137   {"VO", "G", 20, { 2,0,2,0,2,0,2,0 } }, // Violent Ox\r
138   {"EW", "G",  8, { 1,1,1,0,0,0,1,1 } }, // Evil Wolf\r
139   {"CS", "G",  7, { 0,1,0,1,0,1,0,1 } }, // Cat Sword\r
140   {"AB", "G",  6, { 1,0,1,0,1,0,1,0 } }, // Angry Boar\r
141   {"I",  "G",  8, { 1,1,0,0,0,0,0,1 } }, // Iron\r
142   {"N",  "G",  6, { N,0,0,0,0,0,0,N } }, // Knight\r
143   {"ST", "G",  5, { 0,1,0,0,0,0,0,1 } }, // Stone\r
144   { NULL }  // sentinel\r
145 };\r
146 \r
147 PieceDesc ddPieces[] = {\r
148   {"LO", "",   1, { 1,H,1,H,1,H,1,H } }, // Long-Nosed Goblin\r
149   {"OK", "LO", 1, { 2,1,2,0,2,0,2,1 } }, // Old Kite\r
150   {"PS", "HM", 1, { J,0,1,J,0,J,1,0 } }, // Poisonous Snake\r
151   {"GE", "",   1, { 3,3,5,5,3,5,5,3 } }, // Great Elephant\r
152   {"WB", "LD", 1, { 1,1,2,0,1,0,2,1 } }, // Western Barbarian\r
153   {"EA", "LN", 1, { 2,1,1,0,2,0,1,1 } }, // Eastern Barbarian\r
154   {"NO", "FE", 1, { 0,2,1,1,0,1,1,2 } }, // Northern Barbarian\r
155   {"S)", "WE", 1, { 0,1,1,2,0,2,1,1 } }, // Southern Barbarian\r
156   {"FE", "",   1, { 2,X,2,2,2,2,2,X } }, // Fragrant Elephant\r
157   {"WE", "",   1, { 2,2,2,X,2,X,2,2 } }, // White Elephant\r
158   {"FT", "",   1, { X,X,5,0,X,0,5,X } }, // Free Dream-Eater\r
159   {"FR", "",   1, { 5,X,X,0,5,0,X,X } }, // Free Demon\r
160   {"WB", "FT", 1, { 2,X,X,X,2,X,X,X } }, // Water Buffalo\r
161   {"RB", "FR", 1, { X,X,X,X,0,X,X,X } }, // Rushing Bird\r
162   {"SB", "",   1, { X,X,2,2,2,2,2,X } }, // Standard Bearer\r
163   {"FH", "FK", 1, { 1,2,1,0,1,0,1,2 } }, // Flying Horse\r
164   {"NK", "SB", 1, { 1,1,1,1,1,1,1,1 } }, // Neighbor King\r
165   {"BM", "MW", 1, { 0,1,1,1,0,1,1,1 } }, // Blind Monkey\r
166   {"DO", "",   1, { 2,X,2,X,2,X,2,X } }, // Dove\r
167   {"EB", "DO", 1, { 2,0,2,0,0,0,2,0 } }, // Enchanted Badger\r
168   {"EF", "SD", 1, { 0,2,0,0,2,0,0,2 } }, // Enchanted Fox\r
169   {"RA", "",   1, { X,0,X,1,X,1,X,0 } }, // Racing Chariot\r
170   {"SQ", "",   1, { X,1,X,0,X,0,X,1 } }, // Square Mover\r
171   {"PR", "SQ", 1, { 1,1,2,1,0,1,2,1 } }, // Prancing Stag\r
172   {"WT", "",   1, { X,1,2,0,X,0,2,X } }, // White Tiger\r
173   {"BD", "",   1, { 2,X,X,0,2,0,X,1 } }, // Blue Dragon\r
174   {"HD", "",   1, { X,0,0,0,1,0,0,0 } }, // Howling Dog\r
175   {"VB", "",   1, { 0,2,1,0,0,0,1,2 } }, // Violent Bear\r
176   {"SA", "",   1, { 2,1,0,0,2,0,0,1 } }, // Savage Tiger\r
177   {"W",  "",   1, { 0,2,0,0,0,0,0,2 } }, // Wood\r
178   {"CS", "DH",  7, { 0,1,0,1,0,1,0,1 } }, // cat sword\r
179   {"FD", "DK", 15, { 0,2,0,2,0,2,0,2 } }, // flying dragon\r
180   {"KN", "GD", 15, { J,1,J,1,J,1,J,1 } }, // kirin\r
181   {"PH", "GB", 15, { 1,J,1,J,1,J,1,J } }, // phoenix\r
182   {"LN", "FF",  100, { L,L,L,L,L,L,L,L } }, // lion\r
183   {"LD", "GE", 1, { T,T,T,T,T,T,T,T } }, // Lion Dog\r
184   {"AB", "", 1, { 1,0,1,0,1,0,1,0 } }, // Angry Boar\r
185   {"B",  "", 1, { 0,X,0,X,0,X,0,X } }, // Bishop\r
186   {"C",  "", 1, { 1,1,0,0,1,0,0,1 } }, // Copper\r
187   {"DH", "", 1, { 1,X,1,X,1,X,1,X } }, // Dragon Horse\r
188   {"DK", "", 1, { X,1,X,1,X,1,X,1 } }, // Dragon King\r
189   {"FK", "", 1, {  } }, // \r
190   {"EW", "", 1, { 1,1,1,0,0,0,1,1 } }, // Evil Wolf\r
191   {"FL", "", 1, {  } }, // \r
192   {"", "", 1, {  } }, // \r
193   {"", "", 1, {  } }, // \r
194   {"", "", 1, {  } }, // \r
195   {"", "", 1, {  } }, // \r
196   { NULL }  // sentinel\r
197 };\r
198 \r
199 PieceDesc makaPieces[] = {\r
200   {"DV", "", 1, { 0,1,0,1,0,0,1,1 } }, // Deva\r
201   {"DS", "", 1, { 0,1,1,0,0,1,0,1 } }, // Dark Spirit\r
202   {"T",  "", 1, { 0,1,0,0,1,0,0,1 } }, // Tile\r
203   {"CS", "", 1, { 1,0,0,1,1,1,0,0 } }, // Coiled Serpent\r
204   {"RD", "", 1, { 1,0,1,1,1,1,1,0 } }, // Reclining Dragon\r
205   {"CC", "", 1, { 0,1,1,0,1,0,1,1 } }, // Chinese Cock\r
206   {"OM", "", 1, { 0,1,0,1,1,1,0,1 } }, // Old Monkey\r
207   {"BB", "", 1, { 0,1,0,1,X,1,0,1 } }, // Blind Bear\r
208   {"OR", "", 1, { 0,2,0,0,2,0,0,2 } }, // Old Rat\r
209   {"LD", "WS", 1, { T,T,T,T,T,T,T,T } }, // Lion Dog\r
210   {"WR", "", 1, { 0,3,1,3,0,3,1,3 } }, // Wrestler\r
211   {"GG", "", 1, { 3,1,3,0,3,0,3,1 } }, // Guardian of the Gods\r
212   {"BD", "", 1, { 0,3,1,0,1,0,1,3 } }, // Budhist Devil\r
213   {"SD", "", 1, { 5,2,5,2,5,2,5,2 } }, // She-Devil\r
214   {"DY", "", 1, { J,0,1,0,J,0,1,0 } }, // Donkey\r
215   {"CP", "", 1, { 0,H,0,2,0,2,0,H } }, // Capricorn\r
216   {"HM", "", 1, { H,0,H,0,H,0,H,0 } }, // Hook Mover\r
217   {"SF", "", 1, { 0,1,X,1,0,1,0,1 } }, // Side Flier\r
218   {"LC", "", 1, { X,0,0,X,1,0,0,X } }, // Left Chariot\r
219   {"RC", "", 1, { X,X,0,0,1,X,0,0 } }, // Right Chariot\r
220   {"FG", "", 1, { X,X,X,0,X,0,X,X } }, // Free Gold\r
221   {"FS", "", 1, { X,X,0,X,0,X,0,X } }, // Free Silver\r
222   {"FC", "", 1, { X,X,0,0,X,0,0,X } }, // Free Copper\r
223   {"FI", "", 1, { X,X,0,0,0,0,0,X } }, // Free Iron\r
224   {"FT", "", 1, { 0,X,0,0,X,0,0,X } }, // Free Tile\r
225   {"FN", "", 1, { 0,X,0,0,0,0,0,X } }, // Free Stone\r
226   {"FTg", "", 1, { 0,X,X,X,X,X,X,X } }, // Free Tiger\r
227   {"FLp", "", 1, { X,X,0,X,X,X,0,X } }, // Free Leopard (Free Boar?)\r
228   {"FSp", "", 1, { X,0,0,X,X,X,0,0 } }, // Free Serpent (Whale?)\r
229   {"FrD", "", 1, { X,0,X,X,X,X,X,0 } }, // Free Dragon\r
230   {"FC", "", 1, { 0,X,0,X,0,X,0,X } }, // Free Cat (Bishop?)\r
231   {"EM", "", 1, {  } }, // Emperor\r
232   {"TK", "", 1, {  } }, // Teaching King\r
233   {"BS", "", 1, {  } }, // Budhist Spirit\r
234   {"WS", "", 1, { X,X,0,X,1,X,0,X } }, // Wizard Stork\r
235   {"MW", "", 1, { 1,X,0,X,X,X,0,X } }, // Mountain Witch\r
236   {"FF", "", 1, {  } }, // Furious Fiend\r
237   {"GD", "", 1, { 2,3,X,3,2,3,X,3 } }, // Great Dragon\r
238   {"GB", "", 1, { X,3,2,3,X,3,2,3 } }, // Golden Bird\r
239   {"FrW", "", 1, {  } }, // Free Wolf\r
240   {"FrB", "", 1, {  } }, // Free Bear\r
241   {"BT", "", 1, { X,0,0,X,0,X,0,0 } }, // Bat\r
242   {"", "", 1, {  } }, // \r
243   { NULL }  // sentinel\r
244 };\r
245 \r
246 PieceDesc taiPieces[] = {\r
247   {"", "", 1, {  } }, // Peacock\r
248   {"", "", 1, {  } }, // Vermillion Sparrow\r
249   {"", "", 1, {  } }, // Turtle Snake\r
250   {"", "", 1, {  } }, // Silver Hare\r
251   {"", "", 1, {  } }, // Golden Deer\r
252   {"", "", 1, {  } }, // \r
253   {"", "", 1, {  } }, // \r
254   {"", "", 1, {  } }, // \r
255   { NULL }  // sentinel\r
256 };\r
257 \r
258 PieceDesc taikyokuPieces[] = {\r
259   {"", "", 1, {  } }, // \r
260   { NULL }  // sentinel\r
261 };\r
262 \r
263 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
264                   "/............/............/"\r
265                   "...: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
266 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
267                   "/PPPPPPPPPPPPPPP/....:GB.....:GB..../.............../.............../.............../....:gb.....:gb..../ppppppppppppppp/"\r
268                   "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
269 \r
270 typedef struct {\r
271   int boardWidth, boardFiles, zoneDepth, boardRanks; // board sizes\r
272   char *name;  // WinBoard name\r
273   char *array; // initial position\r
274 } VariantDesc;\r
275 \r
276 VariantDesc variants[] = {\r
277   { 24, 12, 12, 4, "chu",     chuArray }, // Chu\r
278   { 30, 15, 15, 5, "dai",     daiArray }, // Dai\r
279   { 32, 16, 16, 5, "tenjiku", chuArray }, // Tenjiku\r
280   { 34, 17, 17, 0, "dada",    chuArray }, // Dai Dai\r
281   { 38, 19, 19, 0, "maka",    chuArray }, // Maka Dai Dai\r
282   { 50, 25, 25, 0, "tai",     chuArray }, // Tai\r
283   { 40, 36, 36, 0, "kyoku",   chuArray }  // Taikyoku\r
284 };\r
285 \r
286 typedef struct {\r
287   int x, y;\r
288 } Vector;\r
289 \r
290 Vector direction[] = { // clockwise!\r
291   {1,  0},\r
292   {1,  1},\r
293   {0,  1},\r
294   {-1, 1},\r
295   {-1, 0},\r
296   {-1,-1},\r
297   {0, -1},\r
298   {1, -1},\r
299 \r
300   { 2, 1}, // Knight jumps\r
301   { 1, 2},\r
302   {-1, 2},\r
303   {-2, 1},\r
304   {-2,-1},\r
305   {-1,-2},\r
306   { 1,-2},\r
307   { 2,-1}\r
308 };\r
309 \r
310 int epList[96], ep2List[96], toList[96], reverse[96];  // decoding tables for double and triple moves\r
311 int kingStep[10], knightStep[10];         // raw tables for step vectors (indexed as -1 .. 8)\r
312 #define kStep (kingStep+1)\r
313 #define nStep (knightStep+1)\r
314 \r
315 int attackMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction\r
316   000000007,\r
317   000000070,\r
318   000000700,\r
319   000007000,\r
320   000070000,\r
321   000700000,\r
322   007000000,\r
323   070000000\r
324 };\r
325 \r
326 int rayMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction\r
327   000000077,\r
328   000000077,\r
329   000007700,\r
330   000007700,\r
331   000770000,\r
332   000770000,\r
333   077000000,\r
334   077000000\r
335 };\r
336 \r
337 int one[] = { // 1 in the bit fields for the various directions\r
338   000000001,\r
339   000000010,\r
340   000000100,\r
341   000001000,\r
342   000010000,\r
343   000100000,\r
344   001000000,\r
345   010000000,\r
346  0100000000  // marks knight jumps\r
347 };\r
348 \r
349 //                                           Main Data structures\r
350 //\r
351 // Piece List: \r
352 //   Interleaved lists for black and white, white taking the odd slots\r
353 //   Pieces in general have two entries: one for the basic, and one for the promoted version\r
354 //   The unused one gets its position set to the invalid square number ABSENT\r
355 //   The list is sorted by piece value, most valuable pieces first\r
356 //   When a piece is captured in the search, both its versions are marked ABSENT\r
357 //   In the root the list is packed to eliminate all captured pieces\r
358 //   The list contains a table for how far the piece moves in each direction\r
359 //   Range encoding: -3 = full Lion, -2 = on-ray Lion, -1 = plain jump, 0 = none, 1 = step, >1 = (limited) range\r
360 // Attack table:\r
361 //   A table in board format, containing pairs of consecutive integers for each square (indexed as 2*sqr and 2*sqr+1)\r
362 //   The first integer contains info on black attacks to the square, the second similarly for white attacks\r
363 //   Each integer contains eight 3-bit fields, which count the number of attacks on it with moves in a particular direction\r
364 //   (If there are attacks by range-jumpers, the 3-bit count is increased by 2 over the actual value)\r
365 // Board:\r
366 //   The board has twice as many files as actually used, in 0x88 fashion\r
367 //   The used squares hold the piece numbers (for use as index in the piece list)\r
368 //   Unused squares are set to the invalid piece number EDGE\r
369 //   There are also 3 guard ranks of EDGE on each side\r
370 // Moves:\r
371 //   Moves are encoded as 11-bit from-square and to-square numbers packed in the low bits of an int\r
372 //   Special moves (like Lion double moves) are encoded by off-board to-squares above a certain value\r
373 //   Promotions are indicated by bit 22\r
374 // Hash table:\r
375 //   Entries of 16 bytes, holding a 32-bit signature, 16-bit lower- and upper-bound scores,\r
376 //   8-bit draft of each of those scores, an age counter that stores the search number of the last access.\r
377 //   The hash key is derived as the XOR of the products pieceKey[piece]*squareKey[square].\r
378 // Promotion zones\r
379 //   the promoBoard contains one byte with flags for each square, to indicate for each side whether the square\r
380 //   is in the promotion zone (twice), on the last two ranks, or on the last rank\r
381 //   the promoFlag field in the piece list can select which bits of this are tested, to see if it\r
382 //   (1) can promote (2) can defer when the to-square is on last rank, last two ranks, or anywhere.\r
383 //   Pawns normally can't defer anywhere, but if the user defers with them, their promoFlag is set to promote on last rank only\r
384 \r
385 typedef struct {\r
386   int pos;\r
387   int pieceKey;\r
388   int promo;\r
389   int value;\r
390   int pst;\r
391   signed char range[8];\r
392   char promoFlag;\r
393   char qval;\r
394   char mobility;\r
395   char mobWeight;\r
396 } PieceInfo; // piece-list entry\r
397 \r
398 int last[2], royal[2];\r
399 PieceInfo p[NPIECES]; // piece list\r
400 \r
401 typedef struct {\r
402   int lock;\r
403   Move move;\r
404   short int upper;\r
405   short int lower;\r
406   char depthU;\r
407   char depthL;\r
408   char flags;\r
409   char age;\r
410 } HashEntry; // hash-table entry\r
411 \r
412 int squareKey[BSIZE];\r
413 \r
414 int rawBoard[BSIZE + 11*BW + 6];\r
415 //int attacks[2*BSIZE];   // attack map\r
416 int attackMaps[200*BSIZE], *attacks = attackMaps;\r
417 char distance[2*BSIZE]; // distance table\r
418 char promoBoard[BSIZE];\r
419 signed char PST[2*BSIZE];\r
420 \r
421 #define board (rawBoard + 6*BW + 3)\r
422 #define dist  (distance + BSIZE)\r
423 \r
424 PieceDesc *\r
425 LookUp (char *name, PieceDesc *list)\r
426 { // find piece of given name in list of descriptors\r
427   int i=0;\r
428   while(list->name && strcmp(name, list->name)) i++, list++;\r
429   return (list->name == NULL ? NULL : list);\r
430 }\r
431 \r
432 void\r
433 SqueezeOut (int n)\r
434 { // remove piece number n from the mentioned side's piece list (and adapt the reference to the displaced pieces!)\r
435   int i;\r
436   for(i=stm+2; i<last[stm]; i+=2)\r
437     if(p[i].promo > n) p[i].promo -= 2;\r
438   for(i=n; i<last[stm]; i+=2) {\r
439     p[i] = p[i+2];\r
440     if(i+2 == royal[stm]) royal[stm] -= 2; // NB: squeezing out the King moves up Crown Prince to royal[stm]\r
441   }\r
442   last[stm] -= 2;\r
443 }\r
444 \r
445 int\r
446 Worse (int a, int b)\r
447 { // determine if range a not upward compatible with b\r
448   if(a == b) return 0;\r
449   if(a >= 0 && b >= 0) return a < b;\r
450   if(a >= 0) return 1; // a (limited) range can never do the same as a special move\r
451   switch(a) {\r
452     case J: return b < J; // any special move is better than a plain jump\r
453     case D: return b > 2 || b < D;\r
454     case T: return b > 3 || b < T;\r
455     case L: return b > 2 || b < D;\r
456     case F: return b > 3 || b < F || b == T;\r
457     case S: return b == H || b == T;\r
458     case H: return b < 0;\r
459     default: return 1; // a >= 0, so b must be < 0 and can always do something a ranging move cannot do\r
460   }\r
461   return 0;\r
462 }\r
463 \r
464 int\r
465 IsUpwardCompatible (signed char *r, signed char *s)\r
466 {\r
467   int i;\r
468   for(i=0; i<8; i++) {\r
469     if(Worse(r[i], s[i])) return 0;\r
470   }\r
471   return 1;\r
472 }\r
473 \r
474 int\r
475 Forward (signed char *r)\r
476 {\r
477   int i;\r
478   for(i=2; i<7; i++) if(r[i]) return 0;\r
479   return 1;\r
480 }\r
481 \r
482 int\r
483 Range (signed char *r)\r
484 {\r
485   int i, m=0;\r
486   for(i=0; i<8; i++) {\r
487     int d = r[i];\r
488     if(r[i] < 0) d == r[i] >= L ? 2 : 36;\r
489     if(d > m) m = d;\r
490   }\r
491   return m;\r
492 }\r
493 \r
494 void\r
495 Compactify (int stm)\r
496 { // remove pieces that are permanently gone (captured or promoted) from one side's piece list\r
497   int i, j, k;\r
498   for(i=stm+2; i<last[stm]; i+=2) { // first pass: unpromoted pieces\r
499     if((k = p[i].promo) >= 0 && p[i].pos == ABSENT) { // unpromoted piece no longer there\r
500       p[k].promo = -2; // orphan promoted version\r
501       SqueezeOut(i);\r
502     }\r
503   }\r
504   for(i=stm+2; i<last[stm]; i+=2) { // second pass: promoted pieces\r
505     if((k = p[i].promo) == -2 && p[i].pos == ABSENT) { // orphaned promoted piece not present\r
506       SqueezeOut(i);\r
507     }\r
508   }\r
509 }\r
510 \r
511 int\r
512 AddPiece (int stm, PieceDesc *list)\r
513 {\r
514   int i, j, *key;\r
515   for(i=stm+2; i<=last[stm]; i += 2) {\r
516     if(p[i].value < 10*list->value || p[i].value == 10*list->value && (p[i].promo < 0)) break;\r
517   }\r
518   last[stm] += 2;\r
519   for(j=last[stm]; j>i; j-= 2) p[j] = p[j-2];\r
520   p[i].value = 10*list->value;\r
521   for(j=0; j<8; j++) p[i].range[j] = list->range[j^4*(WHITE-stm)];\r
522   switch(Range(p[i].range)) {\r
523     case 1:  p[i].pst = BH; break;\r
524     case 2:  p[i].pst = BSIZE; break;\r
525     default: p[i].pst = BSIZE + BH; break;\r
526   }\r
527   key = (stm == WHITE ? &list->whiteKey : &list->blackKey);\r
528   if(!*key) *key = ~(myRandom()*myRandom());\r
529   p[i].pieceKey = *key;\r
530   p[i].promoFlag = 0;\r
531   for(j=stm+2; j<= last[stm]; j+=2) {\r
532     if(p[j].promo >= i) p[j].promo += 2;\r
533   }\r
534   if(royal[stm] >= i) royal[stm] += 2;\r
535   if(p[i].value == 280) royal[stm] = i;\r
536   return i;\r
537 }\r
538 \r
539 void\r
540 SetUp(char *array, PieceDesc *list)\r
541 {\r
542   int i, j, n, m, nr, color;\r
543   char c, *q, name[3];\r
544   PieceDesc *p1, *p2;\r
545   last[WHITE] = 1; last[BLACK] = 0;\r
546   for(i=0; ; i++) {\r
547 //printf("next rank: %s\n", array);\r
548     for(j = BW*i; ; j++) {\r
549       c = name[0] = *array++;\r
550       if(!c) goto eos;\r
551       if(c == '.') continue;\r
552       if(c == '/') break;\r
553       name[1] = name[2] = 0;\r
554       if(c == ':') name[0] = *array++, name[1] = *array++;\r
555       if(name[0] >= 'a') {\r
556         color = BLACK;\r
557         name[0] += 'A' - 'a';\r
558         if(name[1]) name[1] += 'A' - 'a';\r
559       } else color = WHITE;\r
560       p1 = LookUp(name, list);\r
561       n = AddPiece(color, p1);\r
562       p[n].pos = j;\r
563       if(p1->promoted[0]) {\r
564         p2 = LookUp(p1->promoted, list);\r
565         m = AddPiece(color, p2);\r
566         if(m <= n) n += 2;\r
567         p[n].promo = m;\r
568         p[n].promoFlag = IsUpwardCompatible(p2->range, p1->range) * DONT_DEFER + CAN_PROMOTE;\r
569         if(Forward(p1->range)) p[n].promoFlag |= LAST_RANK; // Pieces that only move forward can't defer on last rank\r
570         if(!strcmp(p1->name, "N")) p[n].promoFlag |= CANT_DEFER; // Knights can't defer on last 2 ranks\r
571         p[n].promoFlag &= n&1 ? P_WHITE : P_BLACK;\r
572         p[m].promo = -1;\r
573         p[m].pos = ABSENT;\r
574       } else p[n].promo = -1; // unpromotable piece\r
575 //printf("piece = %c%-2s %d(%d) %d/%d\n", color ? 'w' : 'b', name, n, m, last[color], last[!color]);\r
576     }\r
577   }\r
578  eos:\r
579   for(i=0; i<BH; i++) for(j=0; j<BH; j++) board[BW*i+j] = EMPTY;\r
580   for(i=WHITE+2; i<=last[WHITE]; i+=2) board[p[i].pos] = i;\r
581   for(i=BLACK+2; i<=last[BLACK]; i+=2) board[p[i].pos] = i;\r
582   stm = WHITE; xstm = BLACK;\r
583 }\r
584 \r
585 int myRandom()\r
586 {\r
587   return rand() ^ rand()>>10 ^ rand() << 10 ^ rand() << 20;\r
588 }\r
589 \r
590 void\r
591 Init()\r
592 {\r
593   int i, j, k;\r
594 \r
595   for(i= -1; i<9; i++) { // board steps in linear coordinates\r
596     kStep[i] = STEP(direction[i&7].x,   direction[i&7].y);       // King\r
597     nStep[i] = STEP(direction[(i&7)+8].x, direction[(i&7)+8].y); // Knight\r
598   }\r
599 \r
600   for(i=0; i<8; i++) { // Lion double-move decoding tables\r
601     for(j=0; j<8; j++) {\r
602       epList[8*i+j] = kStep[i];\r
603       toList[8*i+j] = kStep[j] + kStep[i];\r
604       for(k=0; k<8*i+j; k++)\r
605         if(epList[k] == toList[8*i+j] && toList[k] == epList[8*i+j])\r
606           reverse[k] = 8*i+j, reverse[8*i+j] = k;\r
607     }\r
608     // Lion-Dog triple moves\r
609     toList[64+i] = 3*kStep[i]; epList[64+i] =   kStep[i];\r
610     toList[72+i] = 3*kStep[i]; epList[72+i] = 2*kStep[i];\r
611     toList[80+i] = 3*kStep[i]; epList[80+i] =   kStep[i]; ep2List[80+i] = 2*kStep[i];\r
612     toList[88+i] =   kStep[i]; epList[88+i] = 2*kStep[i];\r
613   }\r
614 \r
615   // fill distance table\r
616   for(i=0; i<BSIZE; i++) {\r
617     distance[i] = 0;\r
618   }\r
619   for(i=0; i<8; i++)\r
620     for(j=1; j<BH; j++)\r
621       dist[j * kStep[i]] = j;\r
622 \r
623   // hash key tables\r
624   for(i=0; i<BSIZE; i++) squareKey[i] = ~(myRandom()*myRandom());\r
625 \r
626   // board edge\r
627   for(i=0; i<BSIZE + 11*BW + 6; i++) rawBoard[i] = EDGE;\r
628 \r
629   // promotion zones\r
630   for(i=0; i<BH; i++) for(j=0; j<BH; j++) {\r
631     char v = 0;\r
632     if(i == 0)       v |= LAST_RANK & P_BLACK;\r
633     if(i < 2)        v |= CANT_DEFER & P_BLACK;\r
634     if(i < ZONE)     v |= (CAN_PROMOTE | DONT_DEFER) & P_BLACK;\r
635     if(i >= BH-ZONE) v |= (CAN_PROMOTE | DONT_DEFER) & P_WHITE;\r
636     if(i >= BH-2)    v |= CANT_DEFER & P_WHITE;\r
637     if(i == BH-1)    v |= LAST_RANK & P_WHITE;\r
638     promoBoard[BW*i + j] = v;\r
639   }\r
640 \r
641   // piece-square tables\r
642   for(i=0; i<BH; i++) for(j=0; j<BH; j++) {\r
643     int s = BW*i + j, d = BH*(BH-2) - (2*i - BH + 1)*(2*i - BH + 1) - (2*j - BH + 1)*(2*j - BH + 1);\r
644     PST[BH+s] = d/4 - (i == 0 || i == BH-1 ? 15 : 0) - (j == 0 || j == BH-1 ? 15 : 0);\r
645     PST[BSIZE+s] = d/6;\r
646     PST[BSIZE+BH+s] = d/12;\r
647   }  \r
648 }\r
649 \r
650 #if 0\r
651 inline int\r
652 AddMove (int i, int x, int y)\r
653 {\r
654   if(board[y] == EDGE) return 1;\r
655         if(board[y] == EMPTY) {           // non-capt\r
656           if((flagBoard[x] | flagBoard[y]) & p[i].flags) { // promotion possible\r
657             moveStack[msp++] = moveStack[nonCapts];\r
658             moveStack[nonCapts++] |= PROMOTE | p[i].flags << 24;\r
659             if(!(p[i].flags & ALWAYS_PROMOTE))\r
660                moveStack[msp++] = x << SQLEN | y; // push deferral as well\r
661           else moveStack[msp++] = x << SQLEN | y; // normal move\r
662           }\r
663         } else { // capture\r
664           if(((board[y] ^ i) & 1) return 1; // own\r
665           moveStack[msp++] = moveStack[nonCapts];\r
666           moveStack[nonCapts++] = moveStack[promotions];\r
667           moveStack[promotions++] = x << SQLEN | y;\r
668           if((flagBoard[x] | flagBoard[y]) & p[i].flags) { // promotion possible\r
669             int p = promotions;\r
670             if(!(p[i].flags & ALWAYS_PROMOTE)) {\r
671               moveStack[msp++] = moveStack[nonCapts];\r
672               moveStack[nonCapts++] = moveStack[promotions];\r
673               moveStack[promotions++] = moveStack[p-1];\r
674             }\r
675             moveStack[p-1] += PROMOTE | p[i].flags<<24;\r
676           }\r
677           return 1; // capture ends ray scan\r
678         }\r
679         return 0;\r
680 }\r
681 #endif\r
682 \r
683 int flag;\r
684 \r
685 inline int\r
686 NewNonCapture (int x, int y, int promoFlags)\r
687 {\r
688   if(board[y] != EMPTY) return 1; // edge, capture or own piece\r
689 //if(flag) printf("# add %c%d%c%d, pf=%d\n", x%BW+'a',x/BW,y%BW+'a',y/BW, promoFlags);\r
690   if( (promoBoard[x] | promoBoard[y]) & promoFlags) { // piece can promote with this move\r
691     moveStack[msp++] = moveStack[nonCapts];           // create space for promotion\r
692     moveStack[nonCapts++] = x<<SQLEN | y | PROMOTE;   // push promotion\r
693     if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative\r
694       moveStack[msp++] = x<<SQLEN | y;                // push deferral\r
695       if( (promoBoard[x] & CAN_PROMOTE) == 0 ) {      // enters zone\r
696         moveStack[msp-1] |= DEFER;                    // flag that promo-suppression takes place after this move\r
697       }\r
698     }\r
699   } else\r
700     moveStack[msp++] = x<<SQLEN | y; // push normal move\r
701 //if(flag) printf("msp=%d nc=%d\n", msp, nonCapts);     \r
702   return 0;\r
703 }\r
704 \r
705 inline int\r
706 NewCapture (int x, int y, int promoFlags)\r
707 {\r
708   if( (promoBoard[x] | promoBoard[y]) & promoFlags) { // piece can promote with this move\r
709     moveStack[msp++] = x<<SQLEN | y | PROMOTE;        // push promotion\r
710     if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative\r
711       moveStack[msp++] = x<<SQLEN | y;                // push deferral\r
712       if( (promoBoard[x] & CAN_PROMOTE) == 0 ) {      // enters zone\r
713         moveStack[msp-1] |= DEFER;                    // flag that promo-suppression takes place after this move\r
714       }\r
715     }\r
716   } else\r
717     moveStack[msp++] = x<<SQLEN | y; // push normal move\r
718   return 0;\r
719 }\r
720 \r
721 #if 0\r
722 void\r
723 GenAllMoves ()\r
724 {\r
725   int i, j, k;\r
726   promotions = nonCapts = msp;\r
727   for(i=stm+2; i<=last[stm]; i+=2) {\r
728     int x = p[i].pos;\r
729     if(x == ABSENT) continue;\r
730     for(j=0; j<8; j++) {\r
731       int y, v = kStep[j], r = p[i].range[j];\r
732       if(r < 0) { // jumping piece, special treatment\r
733         if(r >= -3) { // in any case, do a jump of 2\r
734           if(board[x + 2*v] == EMPTY)\r
735             ADDMOVE(x, x+2*v);\r
736           if(r < -1) { // Lion power, also single step\r
737             if(board[x + v] == EMPTY)\r
738               ADDMOVE(x, x+v);\r
739             if(r == -3) { // true Lion, also Knight jump\r
740               v = nStep[j];\r
741               if(board[x + v] == EMPTY)\r
742                 ADDMOVE(x, x+v);\r
743             }\r
744           }\r
745         }\r
746         continue;\r
747       }\r
748       y = x;\r
749       while(r-- > 0) {\r
750         if(board[y+=v] == GUARD) break;    // off board\r
751         if((board[y] + i & 1) == 0) break; // same color\r
752     }\r
753   }\r
754 }\r
755 #endif\r
756 \r
757 int\r
758 GenNonCapts (int promoSuppress)\r
759 {\r
760   int i, j, nullMove = ABSENT;\r
761   for(i=stm+2; i<=last[stm]; i+=2) {\r
762     int x = p[i].pos, pFlag = p[i].promoFlag;\r
763     if(x == ABSENT) continue;\r
764     if(x == promoSuppress) pFlag = 0;\r
765     for(j=0; j<8; j++) {\r
766       int y, v = kStep[j], r = p[i].range[j];\r
767       if(r < 0) { // jumping piece, special treatment\r
768         if(r >= S) { // in any case, do a jump of 2\r
769           NewNonCapture(x, x + 2*v, pFlag);\r
770           if(r < N) { // Lion power, also single step\r
771             if(!NewNonCapture(x, x + v, pFlag)) nullMove = x;\r
772             if(r == L) { // true Lion, also Knight jump\r
773               v = nStep[j];\r
774               NewNonCapture(x, x + v, pFlag);\r
775             }\r
776           }\r
777         }\r
778         continue;\r
779       }\r
780       y = x;\r
781       while(r-- > 0)\r
782         if(NewNonCapture(x, y+=v, pFlag)) break;\r
783     }\r
784   }\r
785   return nullMove;\r
786 }\r
787 \r
788 void\r
789 report (int x, int y, int i)\r
790 {\r
791 }\r
792 \r
793 void\r
794 MapOneColor (int start, int last, int *map)\r
795 {\r
796   int i, j, k;\r
797   for(i=start+2; i<=last; i+=2) {\r
798     if(p[i].pos == ABSENT) continue;\r
799     for(j=0; j<8; j++) {\r
800       int x = p[i].pos, v = kStep[j], r = p[i].range[j];\r
801       if(r < 0) { // jumping piece, special treatment\r
802         if(r >= S) { // in any case, do a jump of 2\r
803           if(board[x + 2*v] != EMPTY && board[x + 2*v] != EDGE)\r
804             map[2*(x + 2*v) + start] += one[j];\r
805           if(r < J) { // Lion power, also single step\r
806             if(board[x + v] != EMPTY && board[x + v] != EDGE)\r
807               map[2*(x + v) + start] += one[j];\r
808             if(r == T) { // Lion Dog, also jump of 3\r
809               if(board[x + 3*v] != EMPTY && board[x + 3*v] != EDGE)\r
810                 map[2*(x + 3*v) + start] += one[j];\r
811             } else\r
812             if(r <= L) {  // true Lion, also Knight jump\r
813               if(r < L) { // Lion plus (limited) range\r
814                 int y = x, n = 0;\r
815                 r = (r == S ? 36 : 3);\r
816                 while(n++ <= r) {\r
817                   if(board[y+=v] == EDGE) break;\r
818                   if(board[y] != EMPTY) {\r
819                     if(n > 2) map[2*y + start] += one[j]; // outside Lion range\r
820                     break;\r
821                   }\r
822                 }\r
823               }\r
824               v = nStep[j];\r
825               if(board[x + v] != EMPTY && board[x + v] != EDGE)\r
826                 map[2*(x + v) + start] += one[8];\r
827             }\r
828           }\r
829         }\r
830         continue;\r
831       }\r
832       while(r-- > 0) {\r
833         if(board[x+=v] != EMPTY) {\r
834           if(board[x] != EDGE) map[2*x + start] += one[j];\r
835           break;\r
836         }\r
837       }\r
838     }\r
839   }\r
840 }\r
841 \r
842 void\r
843 MapFromScratch (int *map)\r
844 {\r
845   int i;\r
846   for(i=0; i<2*BSIZE; i++) map[i] = 0;\r
847   MapOneColor(0, last[BLACK], map);\r
848   MapOneColor(1, last[WHITE], map);\r
849 }\r
850 \r
851 void\r
852 Connect (int sqr, int piece, int dir)\r
853 {\r
854   int x, step = kStep[dir], r1 = p[piece].range[dir], r2 = p[piece].range[dir+1], piece1, piece2;\r
855   int d1, d2, r, y, c;\r
856 \r
857   if((attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir]) {         // there are incoming attack(s) from 'behind'\r
858     x = sqr;\r
859     while(board[x-=step] == EMPTY);                                   // in any case, scan to attacker, to see where / what it is\r
860     d1 = dist[x-sqr]; piece1 = board[x];\r
861     attacks[2*x + stm] -= -(d1 <= r2) & one[dir+4];                   // remove our attack on it if in-range\r
862     if((attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir+4]) {     // there are also incoming attack(s) from 'ahead'\r
863 \r
864       y = sqr;\r
865       while(board[y+=step] == EMPTY);                                 // also always scan to that one to see what it is\r
866       d2 = dist[y-sqr]; piece2 = board[y];\r
867       attacks[2*y+stm] -= -(d2 <= r1) & one[dir];                     // remove our attack on it if in-range\r
868       // we have two pieces now shooting at each other. See how far they get.\r
869       if(d1 + d2 <= (r1 = p[piece1].range[dir])) {                    // 1 hits 2\r
870         attacks[2*y + (piece1 & WHITE)] += one[dir];                  // count attack\r
871         UPDATE_MOBILITY(piece1, d2);\r
872       } else UPDATE_MOBILITY(piece1, r1 - d1);                        // does not connect, but could still gain mobility\r
873       if(d1 + d2 <= (r2 = p[piece2].range[dir])) {                    // 2 hits 1\r
874         attacks[2*x + (piece2 & WHITE)] += one[dir+4];                // count attack\r
875         UPDATE_MOBILITY(piece2, d1);\r
876       } else UPDATE_MOBILITY(piece2, r2 - d2);                        // does not connect, but could still gain mobility\r
877 \r
878     } else { // we were only attacked from behind\r
879 \r
880       r = (r2 = p[piece1].range[dir]) - d1;\r
881       if(r < 0 || c > one[dir+1]) { // Oops! This was not our attacker, or not the only one. There must be a jump attack from even further behind!\r
882         // for now, forget jumpers\r
883       }\r
884       y = sqr; \r
885       while(r--)\r
886         if(board[y+=step] != EMPTY) {\r
887           d2 = dist[y-sqr]; piece2 = board[y];\r
888           if(piece2 != EDGE) {                                // extended move hits a piece\r
889             attacks[2*y + (piece1 & WHITE)] += one[dir];      // count attack\r
890             attacks[2*y + stm] -= -(d2 <= r1) & one[dir];     // remove our own attack on it, if in-range\r
891           }\r
892           UPDATE_MOBILITY(piece1, d2);                        // count extra mobility even if we hit edge\r
893           return;\r
894         }\r
895       // we hit nothing with the extended move of the attacker behind us.\r
896       UPDATE_MOBILITY(piece1, r2 - d1);\r
897       r = r1 - r2;                                            // extra squares covered by mover\r
898       while(r-- > 0)\r
899         if(board[y+=step] != EMPTY) {\r
900           d2 = dist[y-sqr]; piece2 = board[y];\r
901           if(piece2 != EDGE) {                                // extended move hits a piece\r
902             attacks[2*y + stm] -= one[dir];                   // count attack\r
903           }\r
904           return;\r
905         }\r
906     }\r
907 \r
908   } else // no incoming attack from behind\r
909   if(c = (attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir+4]) { // but incoming attack(s) from 'ahead'\r
910 \r
911       y = sqr; while(board[y+=step]);                               // locate attacker\r
912       d2 = dist[y-sqr]; piece2 = board[y];\r
913       attacks[2*y + stm] -= -(d2 <= r1) & one[dir];                 // remove our attack on it if in-range\r
914       r = (r1 = p[piece1].range[dir]) - d2;\r
915       if(r < 0 || c > one[dir]) { // Oops! This was not our attacker, or not the only one. There must be a jump attack from even further behind!\r
916         // for now, forget jumpers\r
917       }\r
918       x = sqr;\r
919       while(r--)\r
920         if(board[x-=step] != EMPTY) {\r
921           d1 = dist[x-sqr]; piece1 = board[x];\r
922           if(piece1 != EDGE) {                                      // extended move hits a piece\r
923             attacks[2*x + (piece2 & WHITE)] += one[dir+4];          // count attack\r
924             attacks[2*x + stm] -= -(d1 <= r2) & one[dir+4];         // remove our own attack on it, if in-range\r
925           }\r
926           UPDATE_MOBILITY(piece2, d1);                              // count extra mobility even if we hit edge\r
927           return;\r
928         }\r
929       // we hit nothing with the extended move of the attacker behind us.\r
930       UPDATE_MOBILITY(piece2, r2 - d1);\r
931       r = r2 - r1;                                                  // extra squares covered by mover\r
932       while(r-- > 0)\r
933         if(board[x-=step] != EMPTY) {\r
934           d1 = dist[x-sqr]; piece1 = board[x];\r
935           if(piece1 != EDGE) {                                      // extended move hits a piece\r
936             attacks[2*x + stm] -= one[dir+4];                       // count attack\r
937           }\r
938           return;\r
939         }\r
940 \r
941   } else { // no incoming attacks from either side. Only delete attacks of mover on others\r
942 \r
943     x = sqr;\r
944     while(r1--)\r
945       if(board[x+=step] != EMPTY) {       // piece found that we attacked\r
946         attacks[2*x + stm] -= one[dir];   // decrement attacks along that direction\r
947         break;\r
948       }\r
949 \r
950     x = sqr;\r
951     while(r2--)\r
952       if(board[x-=step] != EMPTY) {       // piece found that we attacked\r
953         attacks[2*x + stm] -= one[dir+4]; // decrement attacks along opposite direction\r
954         break;\r
955       }\r
956 \r
957   }\r
958 }\r
959 \r
960 void\r
961 Disconnect (int sqr, int dir)\r
962 {\r
963   int x = sqr, step = kStep[dir], piece1, piece2, y;\r
964   while( board[x+=step] == EMPTY );\r
965   if(board[x] != EDGE) { // x has hit a piece\r
966     piece1 = board[x];\r
967     y = sqr; while( board[y-=step] == EMPTY );\r
968     if(board[y] != EDGE) { // both ends of the ray hit a piece\r
969       piece2 = board[y];\r
970       \r
971       return;\r
972     }\r
973   } else {\r
974     x = sqr; while( board[x-=step] == EMPTY );\r
975     if(board[x] == EDGE) return; // ray empty on both sides\r
976   }\r
977   // we only get here if one side hits a \r
978   \r
979 }\r
980 \r
981 void\r
982 Occupy (int sqr)\r
983 { // determines attacks on square and blocking when a piece lands on an empty square\r
984   int i;\r
985   for(i=0; i<4; i++) {\r
986     Disconnect(sqr, i);\r
987   }\r
988 }\r
989 \r
990 void\r
991 Evacuate (int sqr, int piece)\r
992 { // determines change in attacks on neighbors due to unblocking and mover when the mentioned piece vacates the given square\r
993   int i;\r
994   for(i=0; i<4; i++) Connect(sqr, piece, i);\r
995 }\r
996 \r
997 int\r
998 MakeMove(Move m, UndoInfo *u)\r
999 {\r
1000   int deferred = ABSENT;\r
1001   // first execute move on board\r
1002   u->from = m>>SQLEN & SQUARE;\r
1003   u->to = m & SQUARE;\r
1004   u->piece = board[u->from];\r
1005   board[u->from] = EMPTY;\r
1006   u->booty = 0;\r
1007   u->revMoveCount = cnt50++;\r
1008   u->savKeyL = hashKeyL;\r
1009   u->savKeyH = hashKeyH;\r
1010 \r
1011   if(m & (PROMOTE | DEFER)) {\r
1012     if(m & DEFER) {\r
1013       deferred = u->to;\r
1014       u->new = u->piece;\r
1015     } else {\r
1016       p[u->piece].pos = ABSENT;\r
1017       u->new = p[u->piece].promo;\r
1018       u->booty = p[u->new].value - p[u->piece].value;\r
1019       cnt50 = 0; // promotion irreversible\r
1020     }\r
1021   } else u->new = u->piece;\r
1022 \r
1023   u->booty += PST[p[u->new].pst + u->to] - PST[p[u->piece].pst + u->from];\r
1024 \r
1025   if(u->to >= SPECIAL) { // two-step Lion move\r
1026     // take care of first e.p. victim\r
1027     u->epSquare = u->from + epList[u->to - SPECIAL]; // decode\r
1028     u->epVictim = board[u->epSquare]; // remember for takeback\r
1029     board[u->epSquare] = EMPTY;       // and remove\r
1030     p[u->epVictim].pos = ABSENT;\r
1031     // now take care of (optional) second e.p. victim\r
1032     u->ep2Square = u->from + ep2List[u->to - SPECIAL]; // This is the (already evacuated) from-square when there is none!\r
1033     u->ep2Victim = board[u->ep2Square]; // remember\r
1034     board[u->ep2Square] = EMPTY;        // and remove\r
1035     p[u->ep2Victim].pos = ABSENT;\r
1036     // decode the true to-square, and correct difEval and hash key for the e.p. captures\r
1037     u->to       = u->from + toList[u->to - SPECIAL];\r
1038     u->booty += p[u->ep2Victim].value + PST[p[u->ep2Victim].pst + u->ep2Square];\r
1039     u->booty += p[u->epVictim].value + PST[p[u->epVictim].pst + u->epSquare];\r
1040     hashKeyL ^= p[u->epVictim].pieceKey * squareKey[u->epSquare];\r
1041     hashKeyH ^= p[u->epVictim].pieceKey * squareKey[u->epSquare+BH];\r
1042     hashKeyL ^= p[u->ep2Victim].pieceKey * squareKey[u->ep2Square];\r
1043     hashKeyH ^= p[u->ep2Victim].pieceKey * squareKey[u->ep2Square+BH];\r
1044     if(p[u->piece].value != 1000 && p[u->epVictim].value == 1000) deferred |= PROMOTE; // flag non-Lion x Lion\r
1045     cnt50 = 0; // double capture irreversible\r
1046   } else u->epVictim = EMPTY;\r
1047 \r
1048   u->victim = board[u->to];\r
1049   p[u->victim].pos = ABSENT;\r
1050   u->booty += p[u->victim].value + PST[p[u->victim].pst + u->to];\r
1051   if(u->victim != EMPTY) cnt50 = 0; // capture irreversible\r
1052 \r
1053   p[u->new].pos = u->to;\r
1054   board[u->to] = u->new;\r
1055 \r
1056   hashKeyL ^= p[u->new].pieceKey * squareKey[u->to]\r
1057            ^  p[u->piece].pieceKey * squareKey[u->from]\r
1058            ^  p[u->victim].pieceKey * squareKey[u->to];\r
1059   hashKeyH ^= p[u->new].pieceKey * squareKey[u->to+BH]\r
1060            ^  p[u->piece].pieceKey * squareKey[u->from+BH]\r
1061            ^  p[u->victim].pieceKey * squareKey[u->to+BH];\r
1062 \r
1063   return deferred;\r
1064 }\r
1065 \r
1066 void\r
1067 UnMake(UndoInfo *u)\r
1068 {\r
1069   if(u->epVictim) { // put Lion victim of first leg back\r
1070     p[u->ep2Victim].pos = u->ep2Square;\r
1071     board[u->ep2Square] = u->ep2Victim;\r
1072     p[u->epVictim].pos = u->epSquare;\r
1073     board[u->epSquare] = u->epVictim;\r
1074   }\r
1075 \r
1076   p[u->victim].pos = u->to;\r
1077   board[u->to] = u->victim;  // can be EMPTY\r
1078 \r
1079   p[u->new].pos = ABSENT; \r
1080   p[u->piece].pos = u->from; // this can be the same as above\r
1081   board[u->from] = u->piece;\r
1082 \r
1083   cnt50 = u->revMoveCount;\r
1084   hashKeyL = u->savKeyL;\r
1085   hashKeyH = u->savKeyH;\r
1086 }\r
1087         \r
1088 void\r
1089 GenCapts(int sqr, int victimValue)\r
1090 { // generate all moves that capture the piece on the given square\r
1091   int i, range, att = attacks[2*sqr + stm];\r
1092 //printf("GenCapts(%d,%d)\n",sqr,victimValue);\r
1093   for(i=0; i<8; i++) {                             // try all rays\r
1094     int x, v, jumper;\r
1095     if(att & attackMask[i]) {                      // attacked by move in this direction\r
1096       v = -kStep[i]; x = sqr;\r
1097       while( board[x+=v] == EMPTY );               // scan towards source until we encounter a 'stop'\r
1098 //printf("stop @ %c%d (dir %d)\n",x%BW+'a',x/BW,i);\r
1099       if((board[x] & TYPE) == stm) {               // stop is ours\r
1100         int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];\r
1101 //printf("attacker %d, range %d, dist %d\n", attacker, r, d);\r
1102         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
1103           NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1104           att -= one[i];\r
1105           if(!(att & attackMask[i])) continue;\r
1106         } else if(r < 0) goto lions; // test for special-move attacks by thiis stop\r
1107       }\r
1108       // we get here when the first stop on the ray is an opponent, or a normal mover which did not range fare enough\r
1109       while(board[x+=v] == EMPTY);   // next stop\r
1110     lions:\r
1111       if((board[x] & TYPE) == stm) {     // second stop is ours\r
1112         int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];\r
1113         if(r < 0) { // stop has non-standard moves\r
1114           switch(p[attacker].range[i]) { // figure out what he can do (including multi-captures, which causes the complexity)\r
1115             case F: // Lion power + 3-step (as in FF)\r
1116             case S: // Lion power + ranging (as in BS)\r
1117             case L: // Lion\r
1118               if(d > 2) break;\r
1119               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1120               att -= one[i];\r
1121               // now the multi-captures of designated victim together with lower-valued piece\r
1122               if(d == 2) { // primary victim on second ring; look for victims to take in passing\r
1123                 if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr])\r
1124                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1125                 if((i&1) == 0) { // orthogonal: two extra bent paths\r
1126                   v = kStep[i-1];\r
1127                   if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1128                     NewCapture(x, SPECIAL + 8*(i-1&7) + (i+1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1129                   v = kStep[i+1];\r
1130                   if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1131                     NewCapture(x, SPECIAL + 8*(i+1&7) + (i-1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1132                 }\r
1133               } else { // primary victim on first ring\r
1134                 int j;\r
1135                 for(j=0; j<8; j++) { // we can go on in 8 directions after we captured it in passing\r
1136                   int v = kStep[j];\r
1137                   if(sqr + v == x || board[sqr+v] == EMPTY) // hit & run; make sure we include igui (attacker is still at x!)\r
1138                     NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag);\r
1139                   else if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr]) {    // double capture\r
1140                     NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag); // other victim after primary\r
1141                     if(dist[sqr+v-x] == 1) // other victim also on first ring; reverse order is possible\r
1142                       NewCapture(x, SPECIAL + reverse[8*i + j] + victimValue, p[attacker].promoFlag);\r
1143                   }\r
1144                 }\r
1145               }\r
1146               break;\r
1147             case D: // linear Lion move (as in HF, SE)\r
1148               if(d > 2) break;\r
1149               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1150               att -= one[i];\r
1151               if(d == 2) { // check if we can take intermediate with it\r
1152                 if((board[x-v] & TYPE) == xstm && board[x-v] > board[sqr])\r
1153                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // e.p.\r
1154               } else { // d=1; can move on to second, or move back for igui\r
1155                 NewCapture(x, SPECIAL + 8*i + (i^4) + victimValue, p[attacker].promoFlag); // igui\r
1156                 if(board[sqr-v] == EMPTY || (board[sqr-v] & TYPE) == xstm && board[sqr-v] > board[sqr])\r
1157                   NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // hit and run\r
1158               }\r
1159               break;\r
1160             case J: // plain jump (as in KY, PH)\r
1161               if(d != 2) break;\r
1162               NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);\r
1163               att -= one[i];\r
1164           }\r
1165         }\r
1166 //printf("mask[%d] = %o\n", i, att);\r
1167         if((att & attackMask[i]) == 0) continue; // no other attackers, so done with this direction\r
1168       }\r
1169       // now we get to the hairy part: there are other attackers than the stop, apparently jumping over it\r
1170     }\r
1171   }\r
1172   // off-ray attacks\r
1173   if(att & 0700000000) { // Knight attack\r
1174     for(i=0; i<8; i++) {    // scan all knight jumps to locate source\r
1175       int x = sqr - nStep[i], attacker = board[x];\r
1176       if(attacker == EMPTY || (attacker & TYPE) != stm) continue;\r
1177       if(p[attacker].range[i] <= N && p[attacker].range[i] >= S) { // has Knight jump in our direction\r
1178         NewCapture(x, sqr + victimValue, p[attacker].promoFlag);   // plain jump (as in N)\r
1179         if(p[attacker].range[i] < N) { // Lion power; generate double captures over two possible intermediates\r
1180           int v = kStep[i]; // leftish path\r
1181           if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1182             NewCapture(x, SPECIAL + 8*i + (i+1&7) + victimValue, p[attacker].promoFlag);\r
1183           v = kStep[i+1];  // rightish path\r
1184           if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])\r
1185             NewCapture(x, SPECIAL + 8*(i+1&7) + i + victimValue, p[attacker].promoFlag);\r
1186         }\r
1187       }\r
1188     }\r
1189   }\r
1190 }\r
1191 \r
1192 int\r
1193 Evaluate ()\r
1194 {\r
1195   return 0;\r
1196 }\r
1197 \r
1198 int\r
1199 Search (int alpha, int beta, int difEval, int depth, int oldPromo, int promoSuppress)\r
1200 {\r
1201   int i, j, k, firstMove, oldMSP = msp, curMove, sorted, bad, phase, king, iterDep, replyDep, nextVictim, to, defer, dubious, bestMoveNr;\r
1202   int myPV = pvPtr;\r
1203   int score, bestScore, curEval, iterAlpha;\r
1204   Move move, nullMove;\r
1205   UndoInfo tb;\r
1206 if(PATH) printf("search(%d) %d-%d eval=%d, stm=%d\n",depth,alpha,beta,difEval,stm),fflush(stdout);\r
1207   xstm = stm ^ WHITE;\r
1208 //printf("map made\n");fflush(stdout);\r
1209   // KING CAPTURE\r
1210   k = p[king=royal[xstm]].pos;\r
1211   if( k != ABSENT) {\r
1212     if(attacks[2*k + stm]) {\r
1213       if( p[king + 2].pos == ABSENT ) return INF; // we have an attack on his only King\r
1214     }\r
1215   } else { // he has no king! Test for attacks on Crown Prince\r
1216     k = p[king + 2].pos;\r
1217     if(attacks[2*k + stm]) return INF; // we have attack on Crown Prince\r
1218   }\r
1219 //printf("King safe\n");fflush(stdout);\r
1220   // EVALUATION & WINDOW SHIFT\r
1221   curEval = difEval + Evaluate();\r
1222   alpha -= (alpha < curEval);\r
1223   beta  -= (beta <= curEval);\r
1224 \r
1225   nodes++;\r
1226   pv[pvPtr++] = 0; // start empty PV, directly behind PV of parent\r
1227 \r
1228   firstMove = curMove = sorted = msp += 20; // leave 20 empty slots in front of move list\r
1229   phase = 0; iterDep=1; replyDep = (depth < 1 ? depth : 1) - 1;\r
1230   do {\r
1231 if(flag && depth>= 0) printf("iter %d:%d\n", depth,iterDep),fflush(stdout);\r
1232     iterAlpha = alpha; bestScore = -INF; bestMoveNr = 0;\r
1233     for(curMove = firstMove; ; curMove++) { // loop over moves\r
1234 if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase, firstMove, curMove, msp);fflush(stdout);\r
1235       // MOVE SOURCE\r
1236       if(curMove >= msp) { // we ran out of moves; generate some new\r
1237         switch(phase) {\r
1238           case 0: // null move\r
1239             if(depth <= 0) {\r
1240               bestScore = curEval;\r
1241               if(bestScore >= beta || depth < -1) goto cutoff;\r
1242             }\r
1243 #if 0\r
1244             if(curEval >= beta) {\r
1245               stm ^= WHITE;\r
1246               score = -Search(-beta, -iterAlpha, difEval, depth-3, promoSuppress & SQUARE, ABSENT);\r
1247               stm ^= WHITE;\r
1248               if(score >= beta) { msp = oldMSP; return score + (score < curEval); }\r
1249             }\r
1250 #endif\r
1251             phase = 1;\r
1252           case 1: // hash move\r
1253             phase = 2;\r
1254           case 2: // capture-gen init\r
1255             nextVictim = xstm;\r
1256             phase = 3;\r
1257           case 3: // generate captures\r
1258             while(nextVictim < last[xstm]) {           // more victims exist\r
1259               int group, to = p[nextVictim += 2].pos; // take next\r
1260               if(to == ABSENT) continue;              // ignore if absent\r
1261               if(!attacks[2*to + stm]) continue;      // skip if not attacked\r
1262               group = p[nextVictim].value;            // remember value of this found victim\r
1263               GenCapts(to, 0);\r
1264               while(nextVictim < last[xstm] && p[nextVictim+2].value == group) { // more victims of same value exist\r
1265                 to = p[nextVictim += 2].pos;          // take next\r
1266                 if(to == ABSENT) continue;            // ignore if absent\r
1267                 if(!attacks[2*to + stm]) continue;    // skip if not attacked\r
1268                 GenCapts(to, 0);\r
1269               }\r
1270 //printf("captures on %d generated, msp=%d\n", nextVictim, msp);\r
1271               goto extractMove;\r
1272             }\r
1273             phase = 4; // out of victims: all captures generated\r
1274           case 4: // dubious captures\r
1275 #if 0\r
1276             while( dubious < framePtr + 250 ) // add dubious captures back to move stack\r
1277               moveStack[msp++] = moveStack[dubious++];\r
1278             if(curMove != msp) break;\r
1279 #endif\r
1280             phase = 5;\r
1281           case 5: // killers\r
1282             if(depth <= 0) goto cutoff;\r
1283             phase = 6;\r
1284           case 6: // non-captures\r
1285             nonCapts = msp;\r
1286             nullMove = GenNonCapts(oldPromo);\r
1287             phase = 7;\r
1288             sorted = msp; // do not sort noncapts\r
1289             break;\r
1290           case 7: // bad captures\r
1291           case 8: // PV null move\r
1292           case 9:\r
1293             goto cutoff;\r
1294         }\r
1295       }\r
1296 \r
1297       // MOVE EXTRACTION\r
1298     extractMove:\r
1299 if(flag & depth >= 0) printf("%2d:%d extract %d/%d\n", depth, iterDep, curMove, msp);\r
1300       if(curMove < sorted) {\r
1301         move = moveStack[sorted=j=curMove];\r
1302         for(i=curMove+1; i<msp; i++)\r
1303           if(moveStack[i] > move) move = moveStack[j=i]; // search move with highest priority\r
1304         moveStack[j] = moveStack[curMove]; moveStack[curMove] = move; // swap highest-priority move to front of remaining\r
1305         if(move == 0) { msp = curMove--; continue; } // all remaining moves must be 0; clip off move list\r
1306       } else {\r
1307         move = moveStack[curMove];\r
1308         if(move == 0) continue; // skip invalidated move\r
1309       }\r
1310 if(flag & depth >= 0) printf("%2d:%d found %d/%d\n", depth, iterDep, curMove, msp);\r
1311 \r
1312       // RECURSION\r
1313       stm ^= WHITE;\r
1314       defer = MakeMove(move, &tb);\r
1315 \r
1316       for(i=2; i<=cnt50; i+=2) if(repStack[level-i+200] == hashKeyH) {\r
1317         moveStack[curMove] = 0; // erase forbidden move\r
1318         score = -INF; goto repetition;\r
1319       }\r
1320       repStack[level+200] = hashKeyH;\r
1321 \r
1322 path[level++] = move;\r
1323 attacks += 2*BSIZE;\r
1324 MapFromScratch(attacks); // for as long as incremental update does not work.\r
1325 if(PATH) pmap(attacks, stm);\r
1326       if(chuFlag && p[tb.victim].value == 1000) {    // verify legality of Lion capture in Chu Shogi\r
1327         score = 0;\r
1328         if(p[tb.piece].value == 1000) {              // Ln x Ln: can make Ln 'vulnarable' (if distant and not through intemediate > GB)\r
1329           if(dist[tb.from-tb.to] != 1 && attacks[2*tb.to + stm] && p[tb.epVictim].value <= 50)\r
1330             score = -INF;                           // our Lion is indeed made vulnerable and can be recaptured\r
1331         } else {                                    // other x Ln\r
1332           if(promoSuppress & PROMOTE) score = -INF; // non-Lion captures Lion after opponent did same\r
1333           defer |= PROMOTE;                         // if we started, flag  he cannot do it in reply\r
1334         }\r
1335         if(score == -INF) { moveStack[curMove] = 0; goto abortMove; } // zap illegal moves\r
1336       }\r
1337 #if 1\r
1338       score = -Search(-beta, -iterAlpha, -difEval - tb.booty, replyDep, promoSuppress & ~PROMOTE, defer);\r
1339 #else\r
1340       score = 0;\r
1341 #endif\r
1342     abortMove:\r
1343 attacks -= 2*BSIZE;\r
1344 level--;\r
1345     repetition:\r
1346       UnMake(&tb);\r
1347       xstm = stm; stm ^= WHITE;\r
1348 #if 1\r
1349 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore);\r
1350 \r
1351       // ALPHA-BETA STUFF\r
1352       if(score > bestScore) {\r
1353         bestScore = score; bestMoveNr = curMove;\r
1354         if(score > iterAlpha) {\r
1355           iterAlpha = score;\r
1356           if(curMove < firstMove + 5) { // if not too much work, sort move to front\r
1357             int i;\r
1358             for(i=curMove; i>firstMove; i--) {\r
1359               moveStack[i] = moveStack[i-1];\r
1360             }\r
1361             moveStack[firstMove] = move;\r
1362           } else { // late move appended in front of list, and leaves hole in list\r
1363             moveStack[--firstMove] = move;\r
1364             moveStack[curMove] = 0;\r
1365           }\r
1366           bestMoveNr = firstMove;\r
1367           if(score >= beta) { // beta cutoff\r
1368             // update killer\r
1369             goto cutoff;\r
1370           }\r
1371           { int i=pvPtr;\r
1372             for(pvPtr = myPV+1; pv[pvPtr++] = pv[i++]; ); // copy daughter PV\r
1373             pv[myPV] = move;                              // behind our move (pvPtr left at end of copy)\r
1374           }\r
1375         }\r
1376 \r
1377       }\r
1378 #endif\r
1379     } // next move\r
1380   cutoff:\r
1381     if(!level) { // root node\r
1382       if(GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish\r
1383     }\r
1384     replyDep = iterDep;\r
1385   } while(++iterDep <= depth); // next depth\r
1386   retMSP = msp;\r
1387   retFirst = firstMove;\r
1388   msp = oldMSP; // pop move list\r
1389   pvPtr = myPV; // pop PV\r
1390   retMove = bestMoveNr ? moveStack[bestMoveNr] : 0;\r
1391 if(flag && depth >= 0) printf("return %d: %d %d\n", depth, bestScore, curEval);\r
1392   return bestScore + (bestScore < curEval);\r
1393 }\r
1394 \r
1395 void\r
1396 pplist()\r
1397 {\r
1398   int i, j;\r
1399   for(i=0; i<182; i++) {\r
1400         printf("%3d. %3d %3d %4d   %02x   ", i, p[i].value, p[i].promo, p[i].pos, p[i].promoFlag&255);\r
1401         for(j=0; j<8; j++) printf("  %2d", p[i].range[j]);\r
1402         printf("\n");\r
1403   }\r
1404   printf("last: %d / %d\nroyal %d / %d\n", last[WHITE], last[BLACK], royal[WHITE], royal[BLACK]);\r
1405 }\r
1406 \r
1407 void\r
1408 pboard (int *b)\r
1409 {\r
1410   int i, j;\r
1411   for(i=BH+2; i>-4; i--) {\r
1412     printf("#");\r
1413     for(j=-3; j<BH+3; j++) printf("%4d", b[BW*i+j]);\r
1414     printf("\n");\r
1415   }\r
1416 }\r
1417 \r
1418 void\r
1419 pbytes (unsigned char *b)\r
1420 {\r
1421   int i, j;\r
1422   for(i=BH-1; i>=0; i--) {\r
1423     for(j=0; j<BH; j++) printf("%3x", b[BW*i+j]);\r
1424     printf("\n");\r
1425   }\r
1426 }\r
1427 \r
1428 void\r
1429 pmap (int *m, int col)\r
1430 {\r
1431   int i, j;\r
1432   for(i=BH-1; i>=0; i--) {\r
1433     printf("#");\r
1434     for(j=0; j<BH; j++) printf("%10o", m[2*(BW*i+j)+col]);\r
1435     printf("\n");\r
1436   }\r
1437 }\r
1438 \r
1439 void\r
1440 pmoves(int start, int end)\r
1441 {\r
1442   int i, m, f, t;\r
1443   printf("# move stack from %d to %d\n", start, end);\r
1444   for(i=start; i<end; i++) {\r
1445     m = moveStack[i];\r
1446     f = m>>SQLEN & SQUARE;\r
1447     t = m & SQUARE;\r
1448     printf("# %3d. %08x %3d-%3d %s\n", i, m, f, t, MoveToText(m, 0));\r
1449   }\r
1450 }\r
1451 \r
1452     /********************************************************/\r
1453     /* Example of a WinBoard-protocol driver, by H.G.Muller */\r
1454     /********************************************************/\r
1455 \r
1456     #include <stdio.h>\r
1457 \r
1458     // four different constants, with values for WHITE and BLACK that suit your engine\r
1459     #define NONE    3\r
1460     #define ANALYZE 4\r
1461 \r
1462     // some value that cannot occur as a valid move\r
1463     #define INVALID 0\r
1464 \r
1465     // some parameter of your engine\r
1466     #define MAXMOVES 500  /* maximum game length  */\r
1467     #define MAXPLY   60   /* maximum search depth */\r
1468 \r
1469     #define OFF 0\r
1470     #define ON  1\r
1471 \r
1472 #define ONE 0\r
1473 #define DEFAULT_FEN ""\r
1474 \r
1475 typedef Move MOVE;\r
1476 \r
1477     int moveNr;              // part of game state; incremented by MakeMove\r
1478     MOVE gameMove[MAXMOVES]; // holds the game history\r
1479 \r
1480     // Some routines your engine should have to do the various essential things\r
1481     int  MakeMove2(int stm, MOVE move);      // performs move, and returns new side to move\r
1482     void UnMake2(MOVE move);                 // unmakes the move;\r
1483     int  Setup2(char *fen);                  // sets up the position from the given FEN, and returns the new side to move\r
1484     void SetMemorySize(int n);              // if n is different from last time, resize all tables to make memory usage below n MB\r
1485     char *MoveToText(MOVE move, int m);     // converts the move from your internal format to text like e2e2, e1g1, a7a8q.\r
1486     MOVE ParseMove(char *moveText);         // converts a long-algebraic text move to your internal move format\r
1487     int  SearchBestMove(int stm, int timeLeft, int mps, int timeControl, int inc, int timePerMove, MOVE *move, MOVE *ponderMove);\r
1488     void PonderUntilInput(int stm);         // Search current position for stm, deepening forever until there is input.\r
1489 \r
1490 UndoInfo undoInfo;\r
1491 int sup0, sup1, sup2; // promo suppression squares\r
1492 int lastLift, lastPut;\r
1493 \r
1494 int\r
1495 MakeMove2 (int stm, MOVE move)\r
1496 {\r
1497   int i;\r
1498   sup0 = sup1; sup1 = sup2;\r
1499   sup2 = MakeMove(move, &undoInfo);\r
1500   rootEval = -rootEval - undoInfo.booty;\r
1501   for(i=0; i<200; i++) repStack[i] = repStack[i+1];\r
1502   repStack[199] = hashKeyH;\r
1503 printf("# makemove %08x %c%d %c%d\n", move, sup1%BW+'a', sup1/BW, sup2%BW+'a', sup2/BW);\r
1504   return stm ^ WHITE;\r
1505 }\r
1506 \r
1507 void\r
1508 UnMake2 (MOVE move)\r
1509 {\r
1510   int i;\r
1511   rootEval = -rootEval - undoInfo.booty;\r
1512   UnMake(&undoInfo);\r
1513   for(i=200; i>0; i--) repStack[i] = repStack[i-1];\r
1514   sup2 = sup1; sup1 = sup0;\r
1515 }\r
1516 \r
1517 int\r
1518 Setup2 (char *fen)\r
1519 {\r
1520   SetUp(chuArray, chuPieces);\r
1521   sup0 = sup1 = sup2 = ABSENT;\r
1522   rootEval = cnt50 = hashKeyH = hashKeyL = 0;\r
1523   return WHITE;\r
1524 }\r
1525 \r
1526 void\r
1527 SetMemorySize (int n)\r
1528 {\r
1529 }\r
1530 \r
1531 char *\r
1532 MoveToText (MOVE move, int multiLine)\r
1533 {\r
1534   static char buf[50];\r
1535   int f = move>>SQLEN & SQUARE, g = f, t = move & SQUARE;\r
1536   buf[0] = '\0';\r
1537   if(t >= SPECIAL) { // kludgy! Print as side effect non-standard WB command to remove victims from double-capture (breaks hint command!)\r
1538     int e = f + epList[t - SPECIAL];\r
1539 //    printf("take %c%d\n", e%BW+'a', e/BW+ONE);\r
1540     sprintf(buf, "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;\r
1541     if(multiLine) printf("move %s\n", buf), buf[0] = '\0';\r
1542     if(ep2List[t - SPECIAL]) {\r
1543       e = g + ep2List[t - SPECIAL];\r
1544 //      printf("take %c%d\n", e%BW+'a', e/BW+ONE);\r
1545       sprintf(buf+strlen(buf), "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;\r
1546     if(multiLine) printf("move %s\n", buf), buf[0] = '\0';\r
1547     }\r
1548     t = g + toList[t - SPECIAL];\r
1549   }\r
1550   sprintf(buf+strlen(buf), "%c%d%c%d%s", f%BW+'a', f/BW+ONE, t%BW+'a', t/BW+ONE, move & PROMOTE ? "+" : "");\r
1551   return buf;\r
1552 }\r
1553 \r
1554 int\r
1555 ReadSquare (char *p, int *sqr)\r
1556 {\r
1557   int i=0, f, r;\r
1558   f = p[0] - 'a';\r
1559   r = atoi(p + 1) - ONE;\r
1560   *sqr = r*BW + f;\r
1561   return 2 + (r > 9);\r
1562 }\r
1563 \r
1564 MOVE\r
1565 ParseMove (char *moveText)\r
1566 {\r
1567   int i, j, f, t, t2, e, ret, deferred=0;\r
1568   moveText += ReadSquare(moveText, &f);\r
1569   moveText += ReadSquare(moveText, &t); t2 = t;\r
1570   if(*moveText == ',') {\r
1571     moveText++;\r
1572     moveText += ReadSquare(moveText, &e);\r
1573     if(e != t) return INVALID; // must continue with same piece\r
1574     e = t;\r
1575     moveText += ReadSquare(moveText, &t);\r
1576     for(i=0; i<8; i++) if(f + kStep[i] == e) break;\r
1577     if(i >= 8) return INVALID; // this rejects Lion Dog 2+1 and 2-1 moves!\r
1578     for(j=0; j<8; j++) if(e + kStep[j] == t) break;\r
1579     if(j >= 8) return INVALID; // this rejects Lion Dog 1+2 moves!\r
1580     t2 = SPECIAL + 8*i + j;\r
1581   }\r
1582   ret = f<<SQLEN | t2;\r
1583   if(*moveText == '+') ret |= PROMOTE;\r
1584 MapFromScratch(attacks);\r
1585   Search(-INF-1, INF+1, 0, 1, sup1, sup2);\r
1586   for(i=retFirst; i<retMSP; i++) {\r
1587     if((moveStack[i] & (PROMOTE | DEFER-1)) == ret) break;\r
1588     if((moveStack[i] & DEFER-1) == ret) deferred = i; // promoted version of entered non-promotion is legal\r
1589   }\r
1590   if(i>=retMSP) {  // no exact match\r
1591     if(deferred) { // but maybe non-sensical deferral\r
1592       int flags = p[board[f]].promoFlag;\r
1593 printf("# deferral of %d\n", deferred);\r
1594       i = deferred; // in any case we take that move\r
1595       if(!(flags & promoBoard[t] & (CANT_DEFER | LAST_RANK))) { // but change it into a deferral if that is allowed\r
1596         moveStack[i] &= ~PROMOTE;\r
1597         if(p[board[f]].value == 40) p[board[f]].promoFlag &= LAST_RANK; else\r
1598         if(!(flags & promoBoard[f])) moveStack[i] |= DEFER; // came from outside zone, so essential deferral\r
1599       }\r
1600     }\r
1601     if(i >= retMSP)\r
1602       for(i=retFirst; i<retMSP; i++) printf("# %d. %08x %08x %s\n", i-20, moveStack[i], ret, MoveToText(moveStack[i], 0));\r
1603   }\r
1604   return (i >= retMSP ? INVALID : moveStack[i]);\r
1605 }\r
1606 \r
1607 void\r
1608 Highlight(char *coords)\r
1609 {\r
1610   int i, j, n, sqr, cnt=0;\r
1611   char b[BSIZE], buf[2000], *q;\r
1612   for(i=0; i<BSIZE; i++) b[i] = 0;\r
1613   ReadSquare(coords, &sqr);\r
1614 MapFromScratch(attacks);\r
1615 flag=1;\r
1616   Search(-INF-1, INF+1, 0, 1, sup1, sup2);\r
1617 flag=0;\r
1618   for(i=retFirst; i<retMSP; i++) {\r
1619     if(sqr == (moveStack[i]>>SQLEN & SQUARE)) {\r
1620       int t = moveStack[i] & SQUARE;\r
1621       if(t >= SPECIAL) continue;\r
1622       b[t] = (board[t] == EMPTY ? 'Y' : 'R'); cnt++;\r
1623     }\r
1624   }\r
1625   if(!cnt) { // no moves from given square\r
1626     if(sqr != lastPut) return; // refrain from sending empty FEN\r
1627     // we lifted a piece for second leg of move\r
1628     for(i=retFirst; i<retMSP; i++) {\r
1629       if(lastLift == (moveStack[i]>>SQLEN & SQUARE)) {\r
1630         int e, t = moveStack[i] & SQUARE;\r
1631         if(t < SPECIAL) continue; // only special moves\r
1632         e = lastLift + epList[t - SPECIAL]; // decode\r
1633         t = lastLift + toList[t - SPECIAL];\r
1634         if(e != sqr) continue;\r
1635         b[t] = (board[t] == EMPTY ? 'Y' : 'R'); cnt++;\r
1636       }\r
1637     }\r
1638     if(!cnt) return;\r
1639   } else lastLift = sqr; // remember\r
1640   lastPut = ABSENT;\r
1641   q = buf;\r
1642   for(i=BH-1; i>=0; i--) {\r
1643     for(j=0; j<BH; j++) {\r
1644       n = BW*i + j;\r
1645       if(b[n]) *q++ = b[n]; else {\r
1646         if(q > buf && q[-1] <= '9' && q[-1] >= '0') {\r
1647           q[-1]++;\r
1648           if(q[-1] > '9') {\r
1649             if(q > buf+1 && q[-2] <= '9' && q[-2] >= '0') q[-2]++; else q[-1] = '1', *q++ = '0';\r
1650           }\r
1651         } else *q++ = '1';\r
1652       }\r
1653     }\r
1654     *q++ = '/';\r
1655   }\r
1656   q[-1] = 0;\r
1657   printf("highlight %s\n", buf);\r
1658 }\r
1659 \r
1660 int\r
1661 SearchBestMove (int stm, int timeLeft, int mps, int timeControl, int inc, int timePerMove, MOVE *move, MOVE *ponderMove)\r
1662 {\r
1663   int score, targetTime, movesLeft = 50;\r
1664   if(mps) movesLeft = mps - (moveNr>>1)%mps;\r
1665   targetTime = timeLeft*10 / (movesLeft + 1) + 1000 * inc;\r
1666   if(timePerMove > 0) targetTime = timeLeft * 5;\r
1667   startTime = GetTickCount();\r
1668   tlim1 = 0.3*targetTime;\r
1669   tlim2 = 1.9*targetTime;\r
1670   nodes = 0;\r
1671 MapFromScratch(attacks);\r
1672   score = Search(-INF-1, INF+1, rootEval, 20, sup1, sup2);\r
1673   *move = retMove;\r
1674   *ponderMove = INVALID;\r
1675   return score;\r
1676 }\r
1677 \r
1678 void\r
1679 PonderUntilInput (int stm)\r
1680 {\r
1681 }\r
1682 \r
1683     // Some global variables that control your engine's behavior\r
1684     int ponder;\r
1685     int randomize;\r
1686     int postThinking;\r
1687     int resign;         // engine-defined option\r
1688     int contemptFactor; // likewise\r
1689 \r
1690     int TakeBack(int n)\r
1691     { // reset the game and then replay it to the desired point\r
1692       int last, stm;\r
1693       stm = Setup2(NULL);\r
1694 printf("# setup done");fflush(stdout);\r
1695       last = moveNr - n; if(last < 0) last = 0;\r
1696       for(moveNr=0; moveNr<last; moveNr++) stm = MakeMove2(stm, gameMove[moveNr]),printf("make %2d: %x\n", moveNr, gameMove[moveNr]);\r
1697       return stm;\r
1698     }\r
1699 \r
1700     void PrintResult(int stm, int score)\r
1701     {\r
1702       if(score == 0) printf("1/2-1/2\n");\r
1703       if(score > 0 && stm == WHITE || score < 0 && stm == BLACK) printf("1-0\n");\r
1704       else printf("0-1\n");\r
1705     }\r
1706 \r
1707     main()\r
1708     {\r
1709       int engineSide=NONE;                     // side played by engine\r
1710       int timeLeft;                            // timeleft on engine's clock\r
1711       int mps, timeControl, inc, timePerMove;  // time-control parameters, to be used by Search\r
1712       int maxDepth;                            // used by search\r
1713       MOVE move, ponderMove;\r
1714       int i, score;\r
1715       char inBuf[8000], command[80];\r
1716 \r
1717   Init();\r
1718   SetUp(chuArray, chuPieces);\r
1719 //  pplist();\r
1720 //  pboard(board);\r
1721 //  pbytes(promoBoard);\r
1722 //  Search(-INF, INF, 0, 1, ABSENT, ABSENT);\r
1723 //  pmoves(20, retMSP);\r
1724 //MapFromScratch(attacks);\r
1725 //  MapOneColor(1, last[WHITE], attacks);\r
1726 \r
1727       while(1) { // infinite loop\r
1728 \r
1729         fflush(stdout);                 // make sure everything is printed before we do something that might take time\r
1730 \r
1731         if(stm == engineSide) {         // if it is the engine's turn to move, set it thinking, and let it move\r
1732      \r
1733           score = SearchBestMove(stm, timeLeft, mps, timeControl, inc, timePerMove, &move, &ponderMove);\r
1734 \r
1735           if(move == INVALID) {         // game apparently ended\r
1736             engineSide = NONE;          // so stop playing\r
1737             PrintResult(stm, score);\r
1738           } else {\r
1739             stm = MakeMove2(stm, move);  // assumes MakeMove returns new side to move\r
1740             gameMove[moveNr++] = move;  // remember game\r
1741             printf("move %s\n", MoveToText(move, 1));\r
1742           }\r
1743         }\r
1744 \r
1745         fflush(stdout); // make sure everything is printed before we do something that might take time\r
1746 \r
1747         // now it is not our turn (anymore)\r
1748         if(engineSide == ANALYZE) {       // in analysis, we always ponder the position\r
1749             PonderUntilInput(stm);\r
1750         } else\r
1751         if(engineSide != NONE && ponder == ON && moveNr != 0) { // ponder while waiting for input\r
1752           if(ponderMove == INVALID) {     // if we have no move to ponder on, ponder the position\r
1753             PonderUntilInput(stm);\r
1754           } else {\r
1755             int newStm = MakeMove2(stm, ponderMove);\r
1756             PonderUntilInput(newStm);\r
1757             UnMake2(ponderMove);\r
1758           }\r
1759         }\r
1760 \r
1761       noPonder:\r
1762         // wait for input, and read it until we have collected a complete line\r
1763         for(i = 0; (inBuf[i] = getchar()) != '\n'; i++);\r
1764         inBuf[i+1] = 0;\r
1765 pboard(board);\r
1766 pmoves(retFirst, retMSP);\r
1767 \r
1768         // extract the first word\r
1769         sscanf(inBuf, "%s", command);\r
1770 printf("in: %s\n", command);\r
1771 \r
1772         // recognize the command,and execute it\r
1773         if(!strcmp(command, "quit"))    { break; } // breaks out of infinite loop\r
1774         if(!strcmp(command, "force"))   { engineSide = NONE;    continue; }\r
1775         if(!strcmp(command, "analyze")) { engineSide = ANALYZE; continue; }\r
1776         if(!strcmp(command, "exit"))    { engineSide = NONE;    continue; }\r
1777         if(!strcmp(command, "otim"))    { goto noPonder; } // do not start pondering after receiving time commands, as move will follow immediately\r
1778         if(!strcmp(command, "time"))    { sscanf(inBuf, "time %d", &timeLeft); goto noPonder; }\r
1779         if(!strcmp(command, "level"))   {\r
1780           int min, sec=0;\r
1781           sscanf(inBuf, "level %d %d %d", &mps, &min, &inc) == 3 ||  // if this does not work, it must be min:sec format\r
1782           sscanf(inBuf, "level %d %d:%d %d", &mps, &min, &sec, &inc);\r
1783           timeControl = 60*min + sec; timePerMove = -1;\r
1784           continue;\r
1785         }\r
1786         if(!strcmp(command, "protover")){\r
1787           printf("feature ping=1 setboard=1 colors=0 usermove=1 memory=1 debug=1 sigint=0 sigterm=0\n");\r
1788           printf("feature variants=\"chu,12x12+0_fairy\"\n");\r
1789           printf("feature highlight=1\n");\r
1790           printf("feature option=\"Resign -check 0\"\n");           // example of an engine-defined option\r
1791           printf("feature option=\"Contempt -spin 0 -200 200\"\n"); // and another one\r
1792           printf("feature done=1\n");\r
1793           continue;\r
1794         }\r
1795         if(!strcmp(command, "option")) { // setting of engine-define option; find out which\r
1796           if(sscanf(inBuf+7, "Resign=%d",   &resign)         == 1) continue;\r
1797           if(sscanf(inBuf+7, "Contempt=%d", &contemptFactor) == 1) continue;\r
1798           continue;\r
1799         }\r
1800         if(!strcmp(command, "sd"))      { sscanf(inBuf, "sd %d", &maxDepth);    continue; }\r
1801         if(!strcmp(command, "st"))      { sscanf(inBuf, "st %d", &timePerMove); continue; }\r
1802         if(!strcmp(command, "memory"))  { SetMemorySize(atoi(inBuf+7)); continue; }\r
1803         if(!strcmp(command, "ping"))    { printf("pong%s", inBuf+4); continue; }\r
1804     //  if(!strcmp(command, ""))        { sscanf(inBuf, " %d", &); continue; }\r
1805         if(!strcmp(command, "new"))     { engineSide = BLACK; stm = Setup2(DEFAULT_FEN); maxDepth = MAXPLY; randomize = OFF; continue; }\r
1806         if(!strcmp(command, "setboard")){ engineSide = NONE;  stm = Setup2(inBuf+9); continue; }\r
1807         if(!strcmp(command, "easy"))    { ponder = OFF; continue; }\r
1808         if(!strcmp(command, "hard"))    { ponder = ON;  continue; }\r
1809         if(!strcmp(command, "undo"))    { stm = TakeBack(1); continue; }\r
1810         if(!strcmp(command, "remove"))  { stm = TakeBack(2); continue; }\r
1811         if(!strcmp(command, "go"))      { engineSide = stm;  continue; }\r
1812         if(!strcmp(command, "post"))    { postThinking = ON; continue; }\r
1813         if(!strcmp(command, "nopost"))  { postThinking = OFF;continue; }\r
1814         if(!strcmp(command, "random"))  { randomize = ON;    continue; }\r
1815         if(!strcmp(command, "hint"))    { if(ponderMove != INVALID) printf("Hint: %s\n", MoveToText(ponderMove, 0)); continue; }\r
1816         if(!strcmp(command, "lift"))    { Highlight(inBuf+5); continue; }\r
1817         if(!strcmp(command, "put"))     { ReadSquare(inBuf+4, &lastPut); continue; }\r
1818         if(!strcmp(command, "book"))    {  continue; }\r
1819         if(!strcmp(command, "variant")) { continue; }\r
1820         // non-standard commands\r
1821         if(!strcmp(command, "p"))       { pboard(board); continue; }\r
1822         if(!strcmp(command, "w"))       { pmap(attacks, WHITE); continue; }\r
1823         if(!strcmp(command, "b"))       { pmap(attacks, BLACK); continue; }\r
1824         // ignored commands:\r
1825         if(!strcmp(command, "xboard"))  { continue; }\r
1826         if(!strcmp(command, "computer")){ continue; }\r
1827         if(!strcmp(command, "name"))    { continue; }\r
1828         if(!strcmp(command, "ics"))     { continue; }\r
1829         if(!strcmp(command, "accepted")){ continue; }\r
1830         if(!strcmp(command, "rejected")){ continue; }\r
1831         if(!strcmp(command, "hover"))   {  continue; }\r
1832         if(!strcmp(command, ""))  {  continue; }\r
1833         if(!strcmp(command, "usermove")){\r
1834           int move = ParseMove(inBuf+9);\r
1835           if(move == INVALID) printf("Illegal move\n");\r
1836           else {\r
1837             stm = MakeMove2(stm, move);\r
1838             ponderMove = INVALID;\r
1839             gameMove[moveNr++] = move;  // remember game\r
1840           }\r
1841           continue;\r
1842         }\r
1843         printf("Error: unknown command\n");\r
1844       }\r
1845     }\r
1846 \r