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