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