1 /***********************************************************************/
\r
3 /* A WinBoard engine for large (dropless) Shogi variants by H.G.Muller */
\r
4 /* The engine is based on incremental updating of an attack map and */
\r
5 /* mobility scores, since the effort in this only grows proportional */
\r
6 /* to board edge length, rather than board area. */
\r
7 /***********************************************************************/
\r
10 // in GenCapts we do not generate jumps of more than two squares yet
\r
11 // promotions by pieces with Lion power stepping in & out the zone in same turn
\r
12 // promotion on capture
\r
14 #define VERSION "0.7beta"
\r
16 #define PATH level==0 || path[0] == 0xc4028 && (level==1 /*|| path[1] == 0x75967 && (level == 2 || path[2] == 0x3400b && (level == 3))*/)
\r
31 # include <windows.h>
\r
33 { // checks for waiting input in pipe
\r
34 static int pipe, init;
\r
38 if(!init) inp = GetStdHandle(STD_INPUT_HANDLE);
\r
39 if(!PeekNamedPipe(inp, NULL, 0, NULL, &cnt, NULL)) return 1;
\r
43 # include <sys/time.h>
\r
44 # include <sys/ioctl.h>
\r
48 if(ioctl(0, FIONREAD, &cnt)) return 1;
\r
51 int GetTickCount() // with thanks to Tord
\r
53 gettimeofday(&t, NULL);
\r
54 return t.tv_sec*1000 + t.tv_usec/1000;
\r
61 #define BWMAX (2*BHMAX)
\r
62 #define BSIZE BWMAX*BHMAX
\r
65 #define ONE (currentVariant == V_SHO || currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK)
\r
70 #define EDGE (1<<11)
\r
71 #define TYPE (WHITE|BLACK|EDGE)
\r
74 #define NPIECES EDGE+1 /* length of piece list */
\r
76 #define SQLEN 11 /* bits in square number */
\r
77 #define SQUARE ((1<<SQLEN) - 1) /* mask for square in move */
\r
78 #define DEFER (1<<2*SQLEN) /* deferral on zone entry */
\r
79 #define PROMOTE (1<<2*SQLEN+1) /* promotion bit in move */
\r
80 #define SPECIAL 1400 /* start of special moves */
\r
81 #define BURN (SPECIAL + 96) /* start of burn encodings */
\r
82 #define STEP(X,Y) (BW*(X)+ (Y))
\r
83 #define SORTKEY(X) 0
\r
85 #define UPDATE_MOBILITY(X,Y)
\r
86 #define ADDMOVE(X,Y)
\r
89 #define CAN_PROMOTE 0x11
\r
90 #define DONT_DEFER 0x22
\r
91 #define CANT_DEFER 0x44
\r
92 #define LAST_RANK 0x88
\r
93 #define P_WHITE 0x0F
\r
94 #define P_BLACK 0xF0
\r
96 typedef unsigned int Move;
\r
98 char *MoveToText(Move move, int m); // from WB driver
\r
99 void pmap(int *m, int col);
\r
100 void pboard(int *b);
\r
101 void pbytes(unsigned char *b);
\r
106 short int score[5];
\r
112 HashBucket *hashTable;
\r
119 char *name, *promoted;
\r
121 signed char range[8];
\r
123 int whiteKey, blackKey;
\r
127 int from, to, piece, victim, new, booty, epSquare, epVictim[8], ep2Square, revMoveCount, savKeyL, savKeyH;
\r
131 char *array, fenArray[4000], *reason;
\r
132 int bWidth, bHeight, bsize, zone, currentVariant, chuFlag, tenFlag, chessFlag, repDraws;
\r
133 int stm, xstm, hashKeyH, hashKeyL, framePtr, msp, nonCapts, rootEval, retMSP, retFirst, retDep, pvPtr, level, cnt50, mobilityScore;
\r
134 int nodes, startTime, lastRootMove, lastRootIter, tlim1, tlim2, tlim3, repCnt, comp, abortFlag;
\r
136 Move retMove, moveStack[10000], path[100], repStack[300], pv[1000], repeatMove[300], killer[100][2];
\r
138 int maxDepth; // used by search
\r
140 #define X 36 /* slider */
\r
141 #define R 37 /* jump capture */
\r
142 #define N -1 /* Knight */
\r
143 #define J -2 /* jump */
\r
144 #define D -3 /* linear double move */
\r
145 #define T -4 /* linear triple move */
\r
146 #define L -5 /* true Lion move */
\r
147 #define F -6 /* Lion + 3-step */
\r
148 #define S -7 /* Lion + range */
\r
149 #define H -9 /* hook move */
\r
150 #define C -10 /* capture only */
\r
151 #define M -11 /* non-capture only */
\r
153 #define LVAL 100 /* piece value of Lion. Used in chu for recognizing it to implement Lion-trade rules */
\r
154 #define FVAL 500 /* piece value of Fire Demon. Used in code for recognizing moves with it and do burns */
\r
156 PieceDesc chuPieces[] = {
\r
157 {"LN", "", LVAL, { L,L,L,L,L,L,L,L } }, // lion
\r
158 {"FK", "", 60, { X,X,X,X,X,X,X,X } }, // free king
\r
159 {"SE", "", 55, { X,D,X,X,X,X,X,D } }, // soaring eagle
\r
160 {"HF", "", 50, { D,X,X,X,X,X,X,X } }, // horned falcon
\r
161 {"FO", "", 40, { X,X,0,X,X,X,0,X } }, // flying ox
\r
162 {"FB", "", 40, { 0,X,X,X,0,X,X,X } }, // free boar
\r
163 {"DK", "SE", 40, { X,1,X,1,X,1,X,1 } }, // dragon king
\r
164 {"DH", "HF", 35, { 1,X,1,X,1,X,1,X } }, // dragon horse
\r
165 {"WH", "", 35, { X,X,0,0,X,0,0,X } }, // white horse
\r
166 {"R", "DK", 30, { X,0,X,0,X,0,X,0 } }, // rook
\r
167 {"FS", "", 30, { X,1,1,1,X,1,1,1 } }, // flying stag
\r
168 {"WL", "", 25, { X,0,0,X,X,X,0,0 } }, // whale
\r
169 {"K", "", 28, { 1,1,1,1,1,1,1,1 }, 4 }, // king
\r
170 {"CP", "", 27, { 1,1,1,1,1,1,1,1 }, 4 }, // king
\r
171 {"B", "DH", 25, { 0,X,0,X,0,X,0,X } }, // bishop
\r
172 {"VM", "FO", 20, { X,0,1,0,X,0,1,0 } }, // vertical mover
\r
173 {"SM", "FB", 20, { 1,0,X,0,1,0,X,0 } }, // side mover
\r
174 {"DE", "CP", 20, { 1,1,1,1,0,1,1,1 } }, // drunk elephant
\r
175 {"BT", "FS", 15, { 0,1,1,1,1,1,1,1 } }, // blind tiger
\r
176 {"G", "R", 15, { 1,1,1,0,1,0,1,1 } }, // gold
\r
177 {"FL", "B", 15, { 1,1,0,1,1,1,0,1 } }, // ferocious leopard
\r
178 {"KN", "LN", 15, { J,1,J,1,J,1,J,1 } }, // kirin
\r
179 {"PH", "FK", 15, { 1,J,1,J,1,J,1,J } }, // phoenix
\r
180 {"RV", "WL", 15, { X,0,0,0,X,0,0,0 } }, // reverse chariot
\r
181 {"L", "WH", 15, { X,0,0,0,0,0,0,0 } }, // lance
\r
182 {"S", "VM", 10, { 1,1,0,1,0,1,0,1 } }, // silver
\r
183 {"C", "SM", 10, { 1,1,0,0,1,0,0,1 } }, // copper
\r
184 {"GB", "DE", 5, { 1,0,0,0,1,0,0,0 } }, // go between
\r
185 {"P", "G", 4, { 1,0,0,0,0,0,0,0 } }, // pawn
\r
186 { NULL } // sentinel
\r
189 PieceDesc shoPieces[] = {
\r
190 {"DK", "", 70, { X,1,X,1,X,1,X,1 } }, // dragon king
\r
191 {"DH", "", 52, { 1,X,1,X,1,X,1,X } }, // dragon horse
\r
192 {"R", "DK", 50, { X,0,X,0,X,0,X,0 } }, // rook
\r
193 {"B", "DH", 32, { 0,X,0,X,0,X,0,X } }, // bishop
\r
194 {"K", "", 41, { 1,1,1,1,1,1,1,1 } }, // king
\r
195 {"CP", "", 40, { 1,1,1,1,1,1,1,1 } }, // king
\r
196 {"DE", "CP", 25, { 1,1,1,1,0,1,1,1 } }, // silver
\r
197 {"G", "", 22, { 1,1,1,0,1,0,1,1 } }, // gold
\r
198 {"S", "G", 20, { 1,1,0,1,0,1,0,1 } }, // silver
\r
199 {"L", "G", 15, { X,0,0,0,0,0,0,0 } }, // lance
\r
200 {"N", "G", 11, { N,0,0,0,0,0,0,N } }, // Knight
\r
201 {"P", "G", 8, { 1,0,0,0,0,0,0,0 } }, // pawn
\r
202 { NULL } // sentinel
\r
205 PieceDesc daiPieces[] = {
\r
206 {"FD", "G", 15, { 0,2,0,2,0,2,0,2 } }, // Flying Dragon
\r
207 {"VO", "G", 20, { 2,0,2,0,2,0,2,0 } }, // Violent Ox
\r
208 {"EW", "G", 8, { 1,1,1,0,0,0,1,1 } }, // Evil Wolf
\r
209 {"CS", "G", 7, { 0,1,0,1,0,1,0,1 } }, // Cat Sword
\r
210 {"AB", "G", 6, { 1,0,1,0,1,0,1,0 } }, // Angry Boar
\r
211 {"I", "G", 8, { 1,1,0,0,0,0,0,1 } }, // Iron
\r
212 {"N", "G", 6, { N,0,0,0,0,0,0,N } }, // Knight
\r
213 {"ST", "G", 5, { 0,1,0,0,0,0,0,1 } }, // Stone
\r
214 { NULL } // sentinel
\r
217 PieceDesc ddPieces[] = {
\r
218 {"LO", "", 1, { 1,H,1,H,1,H,1,H } }, // Long-Nosed Goblin
\r
219 {"OK", "LO", 1, { 2,1,2,0,2,0,2,1 } }, // Old Kite
\r
220 {"PS", "HM", 1, { J,0,1,J,0,J,1,0 } }, // Poisonous Snake
\r
221 {"GE", "", 1, { 3,3,5,5,3,5,5,3 } }, // Great Elephant
\r
222 {"WS", "LD", 1, { 1,1,2,0,1,0,2,1 } }, // Western Barbarian
\r
223 {"EA", "LN", 1, { 2,1,1,0,2,0,1,1 } }, // Eastern Barbarian
\r
224 {"NO", "FE", 1, { 0,2,1,1,0,1,1,2 } }, // Northern Barbarian
\r
225 {"SO", "WE", 1, { 0,1,1,2,0,2,1,1 } }, // Southern Barbarian
\r
226 {"FE", "", 1, { 2,X,2,2,2,2,2,X } }, // Fragrant Elephant
\r
227 {"WE", "", 1, { 2,2,2,X,2,X,2,2 } }, // White Elephant
\r
228 {"FT", "", 1, { X,X,5,0,X,0,5,X } }, // Free Dream-Eater
\r
229 {"FR", "", 1, { 5,X,X,0,5,0,X,X } }, // Free Demon
\r
230 {"WB", "FT", 1, { 2,X,X,X,2,X,X,X } }, // Water Buffalo
\r
231 {"RB", "FR", 1, { X,X,X,X,0,X,X,X } }, // Rushing Bird
\r
232 {"SB", "", 1, { X,X,2,2,2,2,2,X } }, // Standard Bearer
\r
233 {"FH", "FK", 1, { 1,2,1,0,1,0,1,2 } }, // Flying Horse
\r
234 {"NK", "SB", 1, { 1,1,1,1,1,1,1,1 } }, // Neighbor King
\r
235 {"BM", "MW", 1, { 0,1,1,1,0,1,1,1 } }, // Blind Monkey
\r
236 {"DO", "", 1, { 2,X,2,X,2,X,2,X } }, // Dove
\r
237 {"EB", "DO", 1, { 2,0,2,0,0,0,2,0 } }, // Enchanted Badger
\r
238 {"EF", "SD", 1, { 0,2,0,0,2,0,0,2 } }, // Enchanted Fox
\r
239 {"RA", "", 1, { X,0,X,1,X,1,X,0 } }, // Racing Chariot
\r
240 {"SQ", "", 1, { X,1,X,0,X,0,X,1 } }, // Square Mover
\r
241 {"PR", "SQ", 1, { 1,1,2,1,0,1,2,1 } }, // Prancing Stag
\r
242 {"WT", "", 1, { X,1,2,0,X,0,2,X } }, // White Tiger
\r
243 {"BD", "", 1, { 2,X,X,0,2,0,X,1 } }, // Blue Dragon
\r
244 {"HD", "", 1, { X,0,0,0,1,0,0,0 } }, // Howling Dog
\r
245 {"VB", "", 1, { 0,2,1,0,0,0,1,2 } }, // Violent Bear
\r
246 {"SA", "", 1, { 2,1,0,0,2,0,0,1 } }, // Savage Tiger
\r
247 {"W", "", 1, { 0,2,0,0,0,0,0,2 } }, // Wood
\r
248 {"CS", "DH", 7, { 0,1,0,1,0,1,0,1 } }, // cat sword
\r
249 {"FD", "DK", 15, { 0,2,0,2,0,2,0,2 } }, // flying dragon
\r
250 {"KN", "GD", 15, { J,1,J,1,J,1,J,1 } }, // kirin
\r
251 {"PH", "GB", 15, { 1,J,1,J,1,J,1,J } }, // phoenix
\r
252 {"LN", "FF", 100, { L,L,L,L,L,L,L,L } }, // lion
\r
253 {"LD", "GE", 1, { T,T,T,T,T,T,T,T } }, // Lion Dog
\r
254 {"AB", "", 1, { 1,0,1,0,1,0,1,0 } }, // Angry Boar
\r
255 {"B", "", 1, { 0,X,0,X,0,X,0,X } }, // Bishop
\r
256 {"C", "", 1, { 1,1,0,0,1,0,0,1 } }, // Copper
\r
257 {"DH", "", 1, { 1,X,1,X,1,X,1,X } }, // Dragon Horse
\r
258 {"DK", "", 1, { X,1,X,1,X,1,X,1 } }, // Dragon King
\r
259 {"FK", "", 1, { } }, //
\r
260 {"EW", "", 1, { 1,1,1,0,0,0,1,1 } }, // Evil Wolf
\r
261 {"FL", "", 1, { } }, //
\r
262 {"", "", 1, { } }, //
\r
263 {"", "", 1, { } }, //
\r
264 {"", "", 1, { } }, //
\r
265 {"", "", 1, { } }, //
\r
266 { NULL } // sentinel
\r
269 PieceDesc makaPieces[] = {
\r
270 {"DV", "", 1, { 0,1,0,1,0,0,1,1 } }, // Deva
\r
271 {"DS", "", 1, { 0,1,1,0,0,1,0,1 } }, // Dark Spirit
\r
272 {"T", "", 1, { 0,1,0,0,1,0,0,1 } }, // Tile
\r
273 {"CS", "", 1, { 1,0,0,1,1,1,0,0 } }, // Coiled Serpent
\r
274 {"RD", "", 1, { 1,0,1,1,1,1,1,0 } }, // Reclining Dragon
\r
275 {"CC", "", 1, { 0,1,1,0,1,0,1,1 } }, // Chinese Cock
\r
276 {"OM", "", 1, { 0,1,0,1,1,1,0,1 } }, // Old Monkey
\r
277 {"BB", "", 1, { 0,1,0,1,X,1,0,1 } }, // Blind Bear
\r
278 {"OR", "", 1, { 0,2,0,0,2,0,0,2 } }, // Old Rat
\r
279 {"LD", "WS", 1, { T,T,T,T,T,T,T,T } }, // Lion Dog
\r
280 {"WR", "", 1, { 0,3,1,3,0,3,1,3 } }, // Wrestler
\r
281 {"GG", "", 1, { 3,1,3,0,3,0,3,1 } }, // Guardian of the Gods
\r
282 {"BD", "", 1, { 0,3,1,0,1,0,1,3 } }, // Budhist Devil
\r
283 {"SD", "", 1, { 5,2,5,2,5,2,5,2 } }, // She-Devil
\r
284 {"DY", "", 1, { J,0,1,0,J,0,1,0 } }, // Donkey
\r
285 {"CP", "", 1, { 0,H,0,2,0,2,0,H } }, // Capricorn
\r
286 {"HM", "", 1, { H,0,H,0,H,0,H,0 } }, // Hook Mover
\r
287 {"SF", "", 1, { 0,1,X,1,0,1,0,1 } }, // Side Flier
\r
288 {"LC", "", 1, { X,0,0,X,1,0,0,X } }, // Left Chariot
\r
289 {"RC", "", 1, { X,X,0,0,1,X,0,0 } }, // Right Chariot
\r
290 {"FG", "", 1, { X,X,X,0,X,0,X,X } }, // Free Gold
\r
291 {"FS", "", 1, { X,X,0,X,0,X,0,X } }, // Free Silver
\r
292 {"FC", "", 1, { X,X,0,0,X,0,0,X } }, // Free Copper
\r
293 {"FI", "", 1, { X,X,0,0,0,0,0,X } }, // Free Iron
\r
294 {"FT", "", 1, { 0,X,0,0,X,0,0,X } }, // Free Tile
\r
295 {"FN", "", 1, { 0,X,0,0,0,0,0,X } }, // Free Stone
\r
296 {"FTg", "", 1, { 0,X,X,X,X,X,X,X } }, // Free Tiger
\r
297 {"FLp", "", 1, { X,X,0,X,X,X,0,X } }, // Free Leopard (Free Boar?)
\r
298 {"FSp", "", 1, { X,0,0,X,X,X,0,0 } }, // Free Serpent (Whale?)
\r
299 {"FrD", "", 1, { X,0,X,X,X,X,X,0 } }, // Free Dragon
\r
300 {"FC", "", 1, { 0,X,0,X,0,X,0,X } }, // Free Cat (Bishop?)
\r
301 {"EM", "", 1, { } }, // Emperor
\r
302 {"TK", "", 1, { } }, // Teaching King
\r
303 {"BS", "", 1, { } }, // Budhist Spirit
\r
304 {"WS", "", 1, { X,X,0,X,1,X,0,X } }, // Wizard Stork
\r
305 {"MW", "", 1, { 1,X,0,X,X,X,0,X } }, // Mountain Witch
\r
306 {"FF", "", 1, { } }, // Furious Fiend
\r
307 {"GD", "", 1, { 2,3,X,3,2,3,X,3 } }, // Great Dragon
\r
308 {"GB", "", 1, { X,3,2,3,X,3,2,3 } }, // Golden Bird
\r
309 {"FrW", "", 1, { } }, // Free Wolf
\r
310 {"FrB", "", 1, { } }, // Free Bear
\r
311 {"BT", "", 1, { X,0,0,X,0,X,0,0 } }, // Bat
\r
312 {"", "", 1, { } }, //
\r
313 { NULL } // sentinel
\r
316 PieceDesc taiPieces[] = {
\r
317 {"", "", 1, { } }, // Peacock
\r
318 {"", "", 1, { } }, // Vermillion Sparrow
\r
319 {"", "", 1, { } }, // Turtle Snake
\r
320 {"", "", 1, { } }, // Silver Hare
\r
321 {"", "", 1, { } }, // Golden Deer
\r
322 {"", "", 1, { } }, //
\r
323 {"", "", 1, { } }, //
\r
324 {"", "", 1, { } }, //
\r
325 { NULL } // sentinel
\r
328 PieceDesc tenjikuPieces[] = { // only those not in Chu, or different (because of different promotion)
\r
329 {"FI", "", FVAL, { X,X,0,X,X,X,0,X } }, // Fire Demon
\r
330 {"GG", "", 150, { R,R,R,R,R,R,R,R }, 3 }, // Great General
\r
331 {"VG", "", 140, { 0,R,0,R,0,R,0,R }, 2 }, // Vice General
\r
332 {"RG", "GG",120, { R,0,R,0,R,0,R,0 }, 1 }, // Rook General
\r
333 {"BG", "VG",110, { 0,R,0,R,0,R,0,R }, 1 }, // Bishop General
\r
334 {"SE", "RG", 1, { X,D,X,X,X,X,X,D } }, // Soaring Eagle
\r
335 {"HF", "BG", 1, { D,X,X,X,X,X,X,X } }, // Horned Falcon
\r
336 {"LH", "", 1, { L,S,L,S,L,S,L,S } }, // Lion-Hawk
\r
337 {"LN", "LH", LVAL, { L,L,L,L,L,L,L,L } }, // Lion
\r
338 {"FE", "", 1, { X,X,X,X,X,X,X,X } }, // Free Eagle
\r
339 {"FK", "FE", 60, { X,X,X,X,X,X,X,X } }, // Free King
\r
340 {"HT", "", 1, { X,X,2,X,X,X,2,X } }, // Heavenly Tetrarchs
\r
341 {"CS", "HT", 1, { X,X,2,X,X,X,2,X } }, // Chariot Soldier
\r
342 {"WB", "FI", 1, { 2,X,X,X,2,X,X,X } }, // Water Buffalo
\r
343 {"VS", "CS", 1, { X,0,2,0,1,0,2,0 } }, // Vertical Soldier
\r
344 {"SS", "WB", 1, { 2,0,X,0,1,0,X,0 } }, // Side Soldier
\r
345 {"I", "VS", 1, { 1,1,0,0,0,0,0,1 } }, // Iron
\r
346 {"N", "SS", 1, { N,0,0,0,0,0,0,N } }, // Knight
\r
347 {"MG", "", 1, { X,0,0,X,0,X,0,0 } }, // Multi-General
\r
348 {"D", "MG", 1, { 1,0,0,1,0,1,0,0 } }, // Dog
\r
349 { NULL } // sentinel
\r
352 PieceDesc taikyokuPieces[] = {
\r
353 {"", "", 1, { } }, //
\r
354 { NULL } // sentinel
\r
357 PieceDesc chessPieces[] = {
\r
358 {"Q", "", 95, { X,X,X,X,X,X,X,X } },
\r
359 {"R", "", 50, { X,0,X,0,X,0,X,0 } },
\r
360 {"B", "", 32, { 0,X,0,X,0,X,0,X } },
\r
361 {"N", "", 30, { N,N,N,N,N,N,N,N } },
\r
362 {"K", "", 28, { 1,1,1,1,1,1,1,1 } },
\r
363 {"P", "Q", 8, { M,C,0,0,0,0,0,C } },
\r
364 { NULL } // sentinel
\r
367 PieceDesc shatranjPieces[] = {
\r
368 {"FK", "", 15, { 0,1,0,1,0,1,0,1 } },
\r
369 {"R", "", 50, { X,0,X,0,X,0,X,0 } },
\r
370 {"B", "", 9, { 0,J,0,J,0,J,0,J } },
\r
371 {"N", "", 30, { N,N,N,N,N,N,N,N } },
\r
372 {"K", "", 28, { 1,1,1,1,1,1,1,1 } },
\r
373 {"P", "FK", 8, { M,C,0,0,0,0,0,C } },
\r
374 { NULL } // sentinel
\r
377 PieceDesc makrukPieces[] = {
\r
378 {"SM","", 15, { 0,1,0,1,0,1,0,1 } },
\r
379 {"R", "", 50, { X,0,X,0,X,0,X,0 } },
\r
380 {"S", "", 20, { 1,1,0,1,0,1,0,1 } }, // silver
\r
381 {"N", "", 30, { N,N,N,N,N,N,N,N } },
\r
382 {"K", "", 28, { 1,1,1,1,1,1,1,1 } },
\r
383 {"P", "SM", 8, { M,C,0,0,0,0,0,C } },
\r
384 { NULL } // sentinel
\r
387 char chuArray[] = "L:FLCSGK:DEGSC:FLL/:RV.B.:BT:KN:PH:BT.B.:RV/:SM:VMR:DH:DK:LN:FK:DK:DHR:VM:SM/PPPPPPPPPPPP/...:GB....:GB..."
\r
388 "/............/............/"
\r
389 "...:gb....:gb.../pppppppppppp/:sm:vmr:dh:dk:fk:ln:dk:dhr:vm:sm/:rv.b.:bt:ph:kn:bt.b.:rv/l:flcsg:dekgsc:fll";
\r
390 char daiArray[] = "LN:STICSGKGSCI:STNL/:RV.:CS.:FL.:BT:DE:BT.:FL.:CS.:RV/.:VO.:AB.:EW:KN:LN:PH:EW.:AB.:VO./R:FD:SM:VMB:DH:DK:FK:DK:DHB:VM:SM:FDR"
\r
391 "/PPPPPPPPPPPPPPP/....:GB.....:GB..../.............../.............../.............../....:gb.....:gb..../ppppppppppppppp/"
\r
392 "r:fd:sm:vmb:dh:dk:fk:dk:dhb:vm:sm:fdr/.:vo.:ab.:ew:ph:ln:kn:ew.:ab.:vo./:rv.:cs.:fl.:bt:de:bt.:fl.:cs.:rv/ln:sticsgkgsci:stnl";
\r
393 char tenArray[] = "LN:FLICSGK:DEGSCI:FLNL/:RV.:CS:CS.:BT:KN:LN:FK:PH:BT.:CS:CS.:RV/:SS:VSB:DH:DK:WB:FI:LH:FE:FI:WB:DK:DHB:VS:SS/"
\r
394 ":SM:VMR:HF:SE:BG:RG:GG:VG:RG:BG:SE:HFR:VM:SM/PPPPPPPPPPPPPPPP/....D......D..../"
\r
395 "................/................/................/................/"
\r
396 "....d......d..../pppppppppppppppp/:sm:vmr:hf:se:bg:rg:vg:gg:rg:bg:se:hfr:vm:sm/"
\r
397 ":ss:vsb:dh:dk:wb:fi:fe:lh:fi:wb:dk:dhb:vs:ss/:rv.:cs:cs.:bt:ph:fk:ln:kn:bt.:cs:cs.:rv/ln:flicsg:dekgsci:flnl";
\r
398 char shoArray[] = "LNSGKGSNL/.B..:DE..R./PPPPPPPPP/........./........./........./ppppppppp/.r..:de..b./lnsgkgsnl";
\r
399 char chessArray[] = "RNBQKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbqkbnr";
\r
400 char shatArray[]= "RNBK:FKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbk:fkbnr";
\r
401 char thaiArray[]= "RNSK:SMSNR/......../PPPPPPPP/......../......../pppppppp/......../rnsk:smsnr";
\r
404 int boardWidth, boardFiles, boardRanks, zoneDepth, varNr; // board sizes
\r
405 char *name; // WinBoard name
\r
406 char *array; // initial position
\r
409 typedef enum { V_CHESS, V_SHO, V_CHU, V_DAI, V_TENJIKU, V_DADA, V_MAKA, V_TAI, V_KYOKU, V_SHATRANJ, V_MAKRUK } Variant;
\r
411 VariantDesc variants[] = {
\r
412 { 16, 8, 8, 1, V_CHESS, "normal", chessArray }, // FIDE
\r
413 { 18, 9, 9, 3, V_SHO, "9x9+0_shogi", shoArray }, // Sho
\r
414 { 24, 12, 12, 4, V_CHU, "chu", chuArray }, // Chu
\r
415 { 30, 15, 15, 5, V_DAI, "dai", daiArray }, // Dai
\r
416 { 32, 16, 16, 5, V_TENJIKU, "tenjiku", tenArray }, // Tenjiku
\r
417 { 16, 8, 8, 1, V_SHATRANJ,"shatranj",shatArray}, // Shatranj
\r
418 { 16, 8, 8, 3, V_MAKRUK, "makruk", thaiArray}, // Makruk
\r
420 // { 0, 0, 0, 0, 0 }, // sentinel
\r
421 { 34, 17, 17, 0, V_DADA, "dada", chuArray }, // Dai Dai
\r
422 { 38, 19, 19, 0, V_MAKA, "maka", chuArray }, // Maka Dai Dai
\r
423 { 50, 25, 25, 0, V_TAI, "tai", chuArray }, // Tai
\r
424 { 40, 36, 36, 0, V_KYOKU, "kyoku", chuArray } // Taikyoku
\r
431 Vector direction[] = { // clockwise!
\r
441 { 2, 1}, // Knight jumps
\r
451 int epList[96], ep2List[96], toList[96], reverse[96]; // decoding tables for double and triple moves
\r
452 int kingStep[10], knightStep[10]; // raw tables for step vectors (indexed as -1 .. 8)
\r
453 char fireFlags[10]; // flags for Fire-Demon presence (last two are dummies, which stay 0, for compactify)
\r
454 #define kStep (kingStep+1)
\r
455 #define nStep (knightStep+1)
\r
457 int attackMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction
\r
468 int rayMask[8] = { // indicate which bits in attack-map item are used to count attacks from which direction
\r
479 int one[] = { // 1 in the bit fields for the various directions
\r
488 0100000000 // marks knight jumps
\r
491 // Main Data structures
\r
494 // Interleaved lists for black and white, white taking the odd slots
\r
495 // Pieces in general have two entries: one for the basic, and one for the promoted version
\r
496 // The unused one gets its position set to the invalid square number ABSENT
\r
497 // The list is sorted by piece value, most valuable pieces first
\r
498 // When a piece is captured in the search, both its versions are marked ABSENT
\r
499 // In the root the list is packed to eliminate all captured pieces
\r
500 // The list contains a table for how far the piece moves in each direction
\r
501 // Range encoding: -3 = full Lion, -2 = on-ray Lion, -1 = plain jump, 0 = none, 1 = step, >1 = (limited) range
\r
503 // A table in board format, containing pairs of consecutive integers for each square (indexed as 2*sqr and 2*sqr+1)
\r
504 // The first integer contains info on black attacks to the square, the second similarly for white attacks
\r
505 // Each integer contains eight 3-bit fields, which count the number of attacks on it with moves in a particular direction
\r
506 // (If there are attacks by range-jumpers, the 3-bit count is increased by 2 over the actual value)
\r
508 // The board has twice as many files as actually used, in 0x88 fashion
\r
509 // The used squares hold the piece numbers (for use as index in the piece list)
\r
510 // Unused squares are set to the invalid piece number EDGE
\r
511 // There are also 3 guard ranks of EDGE on each side
\r
513 // Moves are encoded as 11-bit from-square and to-square numbers packed in the low bits of an int
\r
514 // Special moves (like Lion double moves) are encoded by off-board to-squares above a certain value
\r
515 // Promotions are indicated by bit 22
\r
517 // Entries of 16 bytes, holding a 32-bit signature, 16-bit lower- and upper-bound scores,
\r
518 // 8-bit draft of each of those scores, an age counter that stores the search number of the last access.
\r
519 // The hash key is derived as the XOR of the products pieceKey[piece]*squareKey[square].
\r
521 // the promoBoard contains one byte with flags for each square, to indicate for each side whether the square
\r
522 // is in the promotion zone (twice), on the last two ranks, or on the last rank
\r
523 // the promoFlag field in the piece list can select which bits of this are tested, to see if it
\r
524 // (1) can promote (2) can defer when the to-square is on last rank, last two ranks, or anywhere.
\r
525 // Pawns normally can't defer anywhere, but if the user defers with them, their promoFlag is set to promote on last rank only
\r
533 signed char range[8];
\r
538 } PieceInfo; // piece-list entry
\r
540 int last[2], royal[2];
\r
541 PieceInfo p[NPIECES]; // piece list
\r
552 } HashEntry; // hash-table entry
\r
554 // Some global variables that control your engine's behavior
\r
558 int resign; // engine-defined option
\r
559 int contemptFactor; // likewise
\r
561 int squareKey[BSIZE];
\r
563 int rawBoard[BSIZE + 11*BHMAX + 6];
\r
564 //int attacks[2*BSIZE]; // attack map
\r
565 int attackMaps[200*BSIZE], *attacks = attackMaps;
\r
566 char distance[2*BSIZE]; // distance table
\r
567 char promoBoard[BSIZE]; // flags to indicate promotion zones
\r
568 char rawFire[BSIZE+2*BWMAX]; // flags to indicate squares controlled by Fire Demons
\r
569 signed char PST[2*BSIZE];
\r
571 #define board (rawBoard + 6*BHMAX + 3)
\r
572 #define fireBoard (rawFire + BWMAX + 1)
\r
573 #define dist (distance + BSIZE)
\r
576 ListLookUp (char *name, PieceDesc *list)
\r
577 { // find piece of given name in list of descriptors
\r
578 while(list->name && strcmp(name, list->name)) list++;
\r
579 return (list->name == NULL ? NULL : list);
\r
583 LookUp (char *name, int var)
\r
584 { // search piece of given name in all lists relevant for given variant
\r
587 case V_TENJIKU: // Tenjiku
\r
588 desc = ListLookUp(name, tenjikuPieces);
\r
589 if(desc) return desc;
\r
590 return ListLookUp(name, chuPieces);
\r
592 return ListLookUp(name, shoPieces);
\r
594 desc = ListLookUp(name, daiPieces);
\r
595 if(desc) return desc;
\r
597 return ListLookUp(name, chuPieces);
\r
598 case V_CHESS: // FIDE
\r
599 return ListLookUp(name, chessPieces);
\r
600 case V_SHATRANJ: // Shatranj
\r
601 return ListLookUp(name, shatranjPieces);
\r
602 case V_MAKRUK: // Makruk
\r
603 return ListLookUp(name, makrukPieces);
\r
610 { // remove piece number n from the mentioned side's piece list (and adapt the reference to the displaced pieces!)
\r
612 for(i=stm+2; i<last[stm]; i+=2)
\r
613 if(p[i].promo > n) p[i].promo -= 2;
\r
614 for(i=n; i<last[stm]; i+=2) {
\r
616 if(i+2 == royal[stm]) royal[stm] -= 2; // NB: squeezing out the King moves up Crown Prince to royal[stm]
\r
617 if(i < 10) fireFlags[i-2] = fireFlags[i];
\r
623 Worse (int a, int b)
\r
624 { // determine if range a not upward compatible with b
\r
625 if(a == b) return 0;
\r
626 if(a >= 0 && b >= 0) return a < b;
\r
627 if(a >= 0) return 1; // a (limited) range can never do the same as a special move
\r
629 case J: return b < J; // any special move is better than a plain jump
\r
630 case D: return b > 2 || b < D;
\r
631 case T: return b > 3 || b < T;
\r
632 case L: return b > 2 || b < D;
\r
633 case F: return b > 3 || b < F || b == T;
\r
634 case S: return b == H || b == T;
\r
635 case H: return b < 0;
\r
636 default: return 1; // a >= 0, so b must be < 0 and can always do something a ranging move cannot do
\r
642 IsUpwardCompatible (signed char *r, signed char *s)
\r
645 for(i=0; i<8; i++) {
\r
646 if(Worse(r[i], s[i])) return 0;
\r
652 Forward (signed char *r)
\r
655 for(i=2; i<7; i++) if(r[i]) return 0;
\r
660 Range (signed char *r)
\r
663 for(i=0; i<8; i++) {
\r
665 if(r[i] < 0) d == r[i] >= L ? 2 : 36;
\r
671 int multis[2], multiMovers[100];
\r
674 StackMultis (int col)
\r
678 for(i=col+2; i<last[col]; i+=2) { // scan piece list for multi-capturers
\r
679 for(j=0; j<8; j++) if(p[i].range[j] < J && p[i].range[j] >= S || p[i].value == 10*FVAL) {
\r
680 multiMovers[multis[col]] = i; // found one: put its piece number in list
\r
688 Compactify (int stm)
\r
689 { // remove pieces that are permanently gone (captured or promoted) from one side's piece list
\r
691 for(i=stm+2; i<last[stm]; i+=2) { // first pass: unpromoted pieces
\r
692 if((k = p[i].promo) >= 0 && p[i].pos == ABSENT) { // unpromoted piece no longer there
\r
693 p[k].promo = -2; // orphan promoted version
\r
697 for(i=stm+2; i<last[stm]; i+=2) { // second pass: promoted pieces
\r
699 if((k = p[i].promo) == -2 && p[i].pos == ABSENT) { // orphaned promoted piece not present
\r
707 AddPiece (int stm, PieceDesc *list)
\r
710 for(i=stm+2; i<=last[stm]; i += 2) {
\r
711 if(p[i].value < 10*list->value || p[i].value == 10*list->value && (p[i].promo < 0)) break;
\r
714 for(j=last[stm]; j>i; j-= 2) p[j] = p[j-2];
\r
715 p[i].value = v = 10*list->value;
\r
716 for(j=0; j<8; j++) p[i].range[j] = list->range[j^4*(WHITE-stm)];
\r
717 switch(Range(p[i].range)) {
\r
718 case 1: p[i].pst = BH; break;
\r
719 case 2: p[i].pst = bsize; break;
\r
720 default: p[i].pst = bsize + BH; break;
\r
722 key = (stm == WHITE ? &list->whiteKey : &list->blackKey);
\r
723 if(!*key) *key = ~(myRandom()*myRandom());
\r
724 p[i].pieceKey = *key;
\r
725 p[i].promoFlag = 0;
\r
726 p[i].mobWeight = v > 600 ? 0 : v >= 400 ? 1 : v >= 300 ? 2 : v > 150 ? 3 : v >= 100 ? 2 : 0;
\r
727 for(j=stm+2; j<= last[stm]; j+=2) {
\r
728 if(p[j].promo >= i) p[j].promo += 2;
\r
730 if(royal[stm] >= i) royal[stm] += 2;
\r
731 if(p[i].value == (currentVariant == V_SHO ? 410 : 280) ) royal[stm] = i, p[i].pst = 0;
\r
732 p[i].qval = (currentVariant == V_TENJIKU ? list->ranking : 0); // jump-capture hierarchy
\r
737 SetUp(char *array, int var)
\r
739 int i, j, n, m, nr, color;
\r
740 char c, *q, name[3], prince = 0;
\r
741 PieceDesc *p1, *p2;
\r
742 last[WHITE] = 1; last[BLACK] = 0;
\r
744 //printf("next rank: %s\n", array);
\r
745 for(j = BW*i; ; j++) {
\r
747 if(*array == '+') pflag++, array++;
\r
748 c = name[0] = *array++;
\r
750 if(c == '.') continue;
\r
751 if(c == '/') break;
\r
752 name[1] = name[2] = 0;
\r
753 if(c == ':') name[0] = *array++, name[1] = *array++;
\r
754 if(name[0] >= 'a') {
\r
756 name[0] += 'A' - 'a';
\r
757 if(name[1]) name[1] += 'A' - 'a';
\r
758 } else color = WHITE;
\r
759 if(!strcmp(name, "CP")) prince |= color+1; // remember if we added Crown Prince
\r
760 p1 = LookUp(name, var);
\r
761 if(!p1) printf("tellusererror Unknown piece '%s' in setup\n", name), exit(-1);
\r
762 if(pflag && p1->promoted) p1 = LookUp(p1->promoted, var); // use promoted piece instead
\r
763 n = AddPiece(color, p1);
\r
765 if(p1->promoted[0] && !pflag) {
\r
766 if(!strcmp(p1->promoted, "CP")) prince |= color+1; // remember if we added Crown Prince
\r
767 p2 = LookUp(p1->promoted, var);
\r
768 m = AddPiece(color, p2);
\r
771 p[n].promoFlag = IsUpwardCompatible(p2->range, p1->range) * DONT_DEFER + CAN_PROMOTE;
\r
772 if(Forward(p1->range)) p[n].promoFlag |= LAST_RANK; // Pieces that only move forward can't defer on last rank
\r
773 if(!strcmp(p1->name, "N")) p[n].promoFlag |= CANT_DEFER; // Knights can't defer on last 2 ranks
\r
774 p[n].promoFlag &= n&1 ? P_WHITE : P_BLACK;
\r
777 } else p[n].promo = -1; // unpromotable piece
\r
778 //printf("piece = %c%-2s %d(%d) %d/%d\n", color ? 'w' : 'b', name, n, m, last[color], last[!color]);
\r
782 // add dummy Crown Princes if not yet added
\r
783 if(!(prince & WHITE+1)) p[AddPiece(WHITE, LookUp("CP", V_CHU))].pos = ABSENT;
\r
784 if(!(prince & BLACK+1)) p[AddPiece(BLACK, LookUp("CP", V_CHU))].pos = ABSENT;
\r
785 for(i=0; i<8; i++) fireFlags[i] = 0;
\r
786 for(i=2, n=1; i<10; i++) if(p[i].value == 10*FVAL) {
\r
787 int x = p[i].pos; // mark all burn zones
\r
788 fireFlags[i-2] = n;
\r
789 if(x != ABSENT) for(j=0; j<8; j++) fireBoard[x+kStep[j]] |= n;
\r
792 for(i=0; i<BH; i++) for(j=0; j<BH; j++) board[BW*i+j] = EMPTY;
\r
793 for(i=WHITE+2; i<=last[WHITE]; i+=2) board[p[i].pos] = i;
\r
794 for(i=BLACK+2; i<=last[BLACK]; i+=2) board[p[i].pos] = i;
\r
795 StackMultis(WHITE);
\r
796 StackMultis(BLACK);
\r
797 stm = WHITE; xstm = BLACK;
\r
802 return rand() ^ rand()>>10 ^ rand() << 10 ^ rand() << 20;
\r
810 currentVariant = variants[var].varNr;
\r
811 bWidth = variants[var].boardWidth;
\r
812 bHeight = variants[var].boardRanks;
\r
813 zone = variants[var].zoneDepth;
\r
814 array = variants[var].array;
\r
815 bsize = bWidth*bHeight;
\r
816 chuFlag = (currentVariant == V_CHU);
\r
817 tenFlag = (currentVariant == V_TENJIKU);
\r
818 chessFlag = (currentVariant == V_CHESS);
\r
819 repDraws = (currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK);
\r
821 for(i= -1; i<9; i++) { // board steps in linear coordinates
\r
822 kStep[i] = STEP(direction[i&7].x, direction[i&7].y); // King
\r
823 nStep[i] = STEP(direction[(i&7)+8].x, direction[(i&7)+8].y); // Knight
\r
826 for(i=0; i<8; i++) { // Lion double-move decoding tables
\r
827 for(j=0; j<8; j++) {
\r
828 epList[8*i+j] = kStep[i];
\r
829 toList[8*i+j] = kStep[j] + kStep[i];
\r
830 for(k=0; k<8*i+j; k++)
\r
831 if(epList[k] == toList[8*i+j] && toList[k] == epList[8*i+j])
\r
832 reverse[k] = 8*i+j, reverse[8*i+j] = k;
\r
834 // Lion-Dog triple moves
\r
835 toList[64+i] = 3*kStep[i]; epList[64+i] = kStep[i];
\r
836 toList[72+i] = 3*kStep[i]; epList[72+i] = 2*kStep[i];
\r
837 toList[80+i] = 3*kStep[i]; epList[80+i] = kStep[i]; ep2List[80+i] = 2*kStep[i];
\r
838 toList[88+i] = kStep[i]; epList[88+i] = 2*kStep[i];
\r
841 // fill distance table
\r
842 for(i=0; i<2*BSIZE; i++) {
\r
846 for(j=1; j<BH; j++)
\r
847 dist[j * kStep[i]] = j;
\r
848 if(currentVariant == V_TENJIKU)
\r
849 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
852 for(i=0; i<bsize; i++) squareKey[i] = ~(myRandom()*myRandom());
\r
855 for(i=0; i<BSIZE + 11*BHMAX + 6; i++) rawBoard[i] = EDGE;
\r
858 for(i=0; i<BH; i++) for(j=0; j<BH; j++) {
\r
860 if(i == 0) v |= LAST_RANK & P_BLACK;
\r
861 if(i < 2) v |= CANT_DEFER & P_BLACK;
\r
862 if(i < ZONE) v |= (CAN_PROMOTE | DONT_DEFER) & P_BLACK; else v &= ~P_BLACK;
\r
863 if(i >= BH-ZONE) v |= (CAN_PROMOTE | DONT_DEFER) & P_WHITE; else v &= ~P_WHITE;
\r
864 if(i >= BH-2) v |= CANT_DEFER & P_WHITE;
\r
865 if(i == BH-1) v |= LAST_RANK & P_WHITE;
\r
866 promoBoard[BW*i + j] = v;
\r
869 // piece-square tables
\r
870 for(i=0; i<BH; i++) for(j=0; j<BH; j++) {
\r
871 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
873 PST[BH+s] = d/4 - (i == 0 || i == BH-1 ? 15 : 0) - (j == 0 || j == BH-1 ? 15 : 0);
\r
874 PST[BH*BW+s] = d/6;
\r
875 PST[BH*BW+BH+s] = d/12;
\r
878 p[EDGE].qval = 5; // tenjiku jump-capturer sentinel
\r
884 int r, f, score, tot=0;
\r
885 for(r=0; r<BH; r++) for(f=0; f<BH; f++) {
\r
887 int piece = board[s];
\r
888 if(!piece) continue;
\r
889 score = p[piece].value + PST[p[piece].pst + s];
\r
890 if(piece & 1) tot += score; else tot -= score;
\r
898 NewNonCapture (int x, int y, int promoFlags)
\r
900 if(board[y] != EMPTY) return 1; // edge, capture or own piece
\r
901 //if(flag) printf("# add %c%d%c%d, pf=%d\n", x%BW+'a',x/BW,y%BW+'a',y/BW, promoFlags);
\r
902 if( (promoBoard[x] | promoBoard[y]) & promoFlags) { // piece can promote with this move
\r
903 moveStack[msp++] = moveStack[nonCapts]; // create space for promotion
\r
904 moveStack[nonCapts++] = x<<SQLEN | y | PROMOTE; // push promotion
\r
905 if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative
\r
906 moveStack[msp++] = x<<SQLEN | y; // push deferral
\r
907 if( (promoBoard[x] & CAN_PROMOTE) == 0 ) { // enters zone
\r
908 moveStack[msp-1] |= DEFER; // flag that promo-suppression takes place after this move
\r
912 moveStack[msp++] = x<<SQLEN | y; // push normal move
\r
913 //if(flag) printf("msp=%d nc=%d\n", msp, nonCapts);
\r
918 NewCapture (int x, int y, int promoFlags)
\r
920 if( (promoBoard[x] | promoBoard[y]) & promoFlags) { // piece can promote with this move
\r
921 moveStack[msp++] = x<<SQLEN | y | PROMOTE; // push promotion
\r
922 if((promoFlags & promoBoard[y] & (CANT_DEFER | DONT_DEFER | LAST_RANK)) == 0) { // deferral could be a better alternative
\r
923 moveStack[msp++] = x<<SQLEN | y; // push deferral
\r
924 if( (promoBoard[x] & CAN_PROMOTE) == 0 ) { // enters zone
\r
925 moveStack[msp-1] |= DEFER; // flag that promo-suppression takes place after this move
\r
929 moveStack[msp++] = x<<SQLEN | y; // push normal move
\r
933 char map[49]; // 7x7 map for area movers
\r
934 char mapStep[] = { 7, 8, 1, -6, -7, -8, -1, 6 };
\r
935 char rowMask[] = { 0100, 0140, 0160, 070, 034, 016, 07, 03, 01 };
\r
939 AreaStep (int from, int x, int flags, int n, int d)
\r
942 for(i=0; i<8; i++) {
\r
943 int to = x + kStep[i], m = n + mapStep[i];
\r
944 if(board[to] == EDGE) continue; // off board
\r
945 if(map[m] >= d) continue; // already done
\r
946 if(!map[m]) moveStack[msp++] = from<<SQLEN | to;
\r
948 if(d > 1 && board[to] == EMPTY) AreaStep(from, to, flags, m, d-1);
\r
953 AreaMoves (int from, int piece, int range)
\r
956 for(i=0; i<49; i++) map[i] = 0;
\r
957 map[3*7+7] = range;
\r
958 AreaStep(from, from, p[piece].promoFlag, 3*7+3, range);
\r
963 { // make bitmap of squares in FI (7x7) neighborhood where opponents can be captured or burned
\r
964 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
965 if(r < 4) bottom = 4 - r, rows[b=bottom-1] = 0; else
\r
966 if(r > 11) top = 19 - r, rows[t=top+1] = 0; // adjust area to board edges
\r
967 if(f < 4) left = 4 - f; else if(f > 11) right = 19 - f;
\r
968 for(r=bottom; r<=top; r++) {
\r
969 int mask = 0, y = x + 16*r;
\r
970 for(f=left; f <= right; f++) {
\r
971 if(board[y + f - (4*16+4)] != EMPTY && (board[y + f - (4*16+4)] & TYPE) == xstm)
\r
972 mask |= rowMask[f]; // on-rank attacks
\r
976 for(r=b; r<=t-2; r++) rows[r] |= rows[r+1] | rows[r+2]; // smear vertically
\r
980 GenNonCapts (int promoSuppress)
\r
982 int i, j, nullMove = ABSENT;
\r
983 for(i=stm+2; i<=last[stm]; i+=2) {
\r
984 int x = p[i].pos, pFlag = p[i].promoFlag;
\r
985 if(x == ABSENT) continue;
\r
986 if(x == promoSuppress && chuFlag) pFlag = 0;
\r
987 for(j=0; j<8; j++) {
\r
988 int y, v = kStep[j], r = p[i].range[j];
\r
989 if(r < 0) { // jumping piece, special treatment
\r
990 if(r == N) { // pure Knightm do off-ray jump
\r
991 NewNonCapture(x, x + nStep[j], pFlag);
\r
993 if(r >= S) { // in any case, do a jump of 2
\r
994 int occup = NewNonCapture(x, x + 2*v, pFlag);
\r
995 if(r < J) { // Lion power, also single step
\r
996 if(!NewNonCapture(x, x + v, pFlag)) nullMove = x; else occup = 1;
\r
997 if(r <= L) { // true Lion, also Knight jump
\r
998 if(!occup & r < L) for(y=x+2*v; !NewNonCapture(x, y+=v, pFlag) && r == S; ); // BS and FF moves
\r
1000 NewNonCapture(x, x + v, pFlag);
\r
1004 if(r == M) { // FIDE Pawn; check double-move
\r
1005 if(!NewNonCapture(x, x+v, pFlag) && chessFlag && promoBoard[x-v])
\r
1006 NewNonCapture(x, x+2*v, pFlag), moveStack[msp-1] |= DEFER; // use promoSuppress flag as e.p. flag
\r
1012 if(NewNonCapture(x, y+=v, pFlag)) break;
\r
1019 report (int x, int y, int i)
\r
1024 MapOneColor (int start, int last, int *map)
\r
1026 int i, j, k, totMob = 0;
\r
1027 for(i=start+2; i<=last; i+=2) {
\r
1029 if(p[i].pos == ABSENT) continue;
\r
1030 for(j=0; j<8; j++) {
\r
1031 int x = p[i].pos, v = kStep[j], r = p[i].range[j];
\r
1032 if(r < 0) { // jumping piece, special treatment
\r
1035 if(board[x] != EMPTY && board[x] != EDGE)
\r
1036 map[2*x + start] += one[8];
\r
1038 if(r >= S) { // in any case, do a jump of 2
\r
1039 if(board[x + 2*v] != EMPTY && board[x + 2*v] != EDGE)
\r
1040 map[2*(x + 2*v) + start] += one[j], mob += (board[x + 2*v] ^ start) & 1;
\r
1041 if(r < J) { // Lion power, also single step
\r
1042 if(board[x + v] != EMPTY && board[x + v] != EDGE)
\r
1043 map[2*(x + v) + start] += one[j];
\r
1044 if(r == T) { // Lion Dog, also jump of 3
\r
1045 if(board[x + 3*v] != EMPTY && board[x + 3*v] != EDGE)
\r
1046 map[2*(x + 3*v) + start] += one[j];
\r
1048 if(r <= L) { // true Lion, also Knight jump
\r
1049 if(r < L) { // Lion plus (limited) range
\r
1051 r = (r == S ? 36 : 3);
\r
1053 if(board[y+=v] == EDGE) break;
\r
1054 if(board[y] != EMPTY) {
\r
1055 if(n > 2) map[2*y + start] += one[j]; // outside Lion range
\r
1061 if(board[x + v] != EMPTY && board[x + v] != EDGE)
\r
1062 map[2*(x + v) + start] += one[8];
\r
1066 if(r == C) { // FIDE Pawn diagonal
\r
1067 if(board[x + v] != EMPTY && board[x + v] != EDGE)
\r
1068 map[2*(x + v) + start] += one[j];
\r
1073 if(board[x+=v] != EMPTY) {
\r
1074 mob += dist[x-v-p[i].pos];
\r
1075 if(board[x] != EDGE) map[2*x + start] += one[j], mob += (board[x] ^ start) & 1;
\r
1077 if(p[i].range[j] > X) { // jump capturer
\r
1078 int c = p[i].qval;
\r
1079 if(p[board[x]].qval < c) {
\r
1080 x += v; // go behind directly captured piece, if jumpable
\r
1081 while(p[board[x]].qval < c) { // kludge alert: EDGE has qval = 5, blocking everything
\r
1082 if(board[x] != EMPTY) {
\r
1083 // int n = map[2*x + start] & attackMask[j];
\r
1084 // map[2*x + start] += (n < 3*one[j] ? 3*one[j] : one[j]); // first jumper gets 2 extra (to ease incremental update)
\r
1085 map[2*x + start] += one[j]; // for now use true count
\r
1096 totMob += mob * p[i].mobWeight;
\r
1098 if(!level) printf("# mobility %d = %d\n", start, totMob);
\r
1103 MapFromScratch (int *map)
\r
1106 for(i=0; i<2*bsize; i++) map[i] = 0;
\r
1107 mobilityScore = MapOneColor(1, last[WHITE], map);
\r
1108 mobilityScore -= MapOneColor(0, last[BLACK], map);
\r
1112 Connect (int sqr, int piece, int dir)
\r
1113 { // scan to both sides along ray to elongate attacks from there, and remove our own attacks on there, if needed
\r
1114 int x, step = kStep[dir], r1 = p[piece].range[dir], r2 = p[piece].range[dir+4], r3, r4, piece1, piece2;
\r
1115 int d1, d2, r, y, c;
\r
1117 if((attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir]) { // there are incoming attack(s) from 'behind'
\r
1119 while(board[x-=step] == EMPTY); // in any case, scan to attacker, to see where / what it is
\r
1120 d1 = dist[x-sqr]; piece1 = board[x];
\r
1121 attacks[2*x + stm] -= -(d1 <= r2) & one[dir+4]; // remove our attack on it if in-range
\r
1122 if((attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir+4]) { // there are also incoming attack(s) from 'ahead'
\r
1125 while(board[y+=step] == EMPTY); // also always scan to that one to see what it is
\r
1126 d2 = dist[y-sqr]; piece2 = board[y];
\r
1127 attacks[2*y+stm] -= -(d2 <= r1) & one[dir]; // remove our attack on it if in-range
\r
1128 // we have two pieces now shooting at each other. See how far they get.
\r
1129 if(d1 + d2 <= (r3 = p[piece1].range[dir])) { // 1 hits 2
\r
1130 attacks[2*y + (piece1 & WHITE)] += one[dir]; // count attack
\r
1131 UPDATE_MOBILITY(piece1, d2);
\r
1132 } else UPDATE_MOBILITY(piece1, r3 - d1); // does not connect, but could still gain mobility
\r
1133 if(d1 + d2 <= (r4 = p[piece2].range[dir+4])) { // 2 hits 1
\r
1134 attacks[2*x + (piece2 & WHITE)] += one[dir+4]; // count attack
\r
1135 UPDATE_MOBILITY(piece2, d1);
\r
1136 } else UPDATE_MOBILITY(piece2, r4 - d2); // does not connect, but could still gain mobility
\r
1137 // if r1 or r2<0, moves typically jump, and thus cannot be unblocked. Exceptions are FF and BS distant moves.
\r
1138 // test for d1+d2 > 2 && rN == F && d== 3 or rN == S
\r
1139 if(d1 <= 2) { // could be jump interactions
\r
1141 if(r2 <= J) attacks[2*x + stm] -= one[dir+4];
\r
1142 if(r1 <= J) attacks[2*y + stm] -= one[dir];
\r
1143 } else { // d1 == 1
\r
1144 if(r2 < J) attacks[2*x + stm] -= one[dir+4];
\r
1145 if(r1 < J) attacks[2*y + stm] -= one[dir];
\r
1146 if(board[x-step] != EMPTY && board[x-step] != EDGE)
\r
1147 attacks[2*(x-step) + stm] -= one[dir+4];
\r
1151 } else { // we were only attacked from behind
\r
1153 r = (r2 = p[piece1].range[dir]) - d1;
\r
1154 if(r < 0 || c > one[dir+4]) { // Oops! This was not our attacker, or not the only one. There must be a jump attack from even further behind!
\r
1155 // for now, forget jumpers
\r
1159 if(board[y+=step] != EMPTY) {
\r
1160 d2 = dist[y-sqr]; piece2 = board[y];
\r
1161 if(piece2 != EDGE) { // extended move hits a piece
\r
1162 attacks[2*y + (piece1 & WHITE)] += one[dir]; // count attack
\r
1163 attacks[2*y + stm] -= -(d2 <= r1) & one[dir]; // remove our own attack on it, if in-range
\r
1165 UPDATE_MOBILITY(piece1, d2); // count extra mobility even if we hit edge
\r
1168 // we hit nothing with the extended move of the attacker behind us.
\r
1169 UPDATE_MOBILITY(piece1, r2 - d1);
\r
1170 r = r1 - r2 + d1; // extra squares covered by mover
\r
1172 if(board[y+=step] != EMPTY) {
\r
1173 d2 = dist[y-sqr]; piece2 = board[y];
\r
1174 if(piece2 != EDGE) { // extended move hits a piece
\r
1175 attacks[2*y + stm] -= one[dir]; // count attack
\r
1180 // if r2<0 we should again test for F and S moves
\r
1182 } else // no incoming attack from behind
\r
1183 if(c = (attacks[2*sqr] + attacks[2*sqr+1]) & attackMask[dir+4]) { // but incoming attack(s) from 'ahead'
\r
1185 y = sqr; while(board[y+=step]); // locate attacker
\r
1186 d2 = dist[y-sqr]; piece2 = board[y];
\r
1187 attacks[2*y + stm] -= -(d2 <= r1) & one[dir]; // remove our attack on it if in-range
\r
1188 r = (r1 = p[piece1].range[dir]) - d2;
\r
1189 if(r < 0 || c > one[dir]) { // Oops! This was not our attacker, or not the only one. There must be a jump attack from even further behind!
\r
1190 // for now, forget jumpers
\r
1194 if(board[x-=step] != EMPTY) {
\r
1195 d1 = dist[x-sqr]; piece1 = board[x];
\r
1196 if(piece1 != EDGE) { // extended move hits a piece
\r
1197 attacks[2*x + (piece2 & WHITE)] += one[dir+4]; // count attack
\r
1198 attacks[2*x + stm] -= -(d1 <= r2) & one[dir+4]; // remove our own attack on it, if in-range
\r
1200 UPDATE_MOBILITY(piece2, d1); // count extra mobility even if we hit edge
\r
1203 // we hit nothing with the extended move of the attacker behind us.
\r
1204 UPDATE_MOBILITY(piece2, r2 - d1);
\r
1205 r = r2 - r1 + d2; // extra squares covered by mover
\r
1207 if(board[x-=step] != EMPTY) {
\r
1208 d1 = dist[x-sqr]; piece1 = board[x];
\r
1209 if(piece1 != EDGE) { // extended move hits a piece
\r
1210 attacks[2*x + stm] -= one[dir+4]; // count attack
\r
1215 } else { // no incoming attacks from either side. Only delete attacks of mover on others
\r
1219 if(board[x+=step] != EMPTY) { // piece found that we attacked
\r
1220 attacks[2*x + stm] -= one[dir]; // decrement attacks along that direction
\r
1226 if(board[x-=step] != EMPTY) { // piece found that we attacked
\r
1227 attacks[2*x + stm] -= one[dir+4]; // decrement attacks along opposite direction
\r
1235 Hit (int r, int d)
\r
1236 { // test if move with range r reaches over (un-obstructed) distance d
\r
1237 if(r < 0) switch(r) {
\r
1238 case J: return (d == 2);
\r
1240 case L: return (d <= 2);
\r
1242 case F: return (d <= 3);
\r
1244 default: return 0;
\r
1245 } else return (d <= r);
\r
1246 return 0; // not reached
\r
1250 Disconnect (int sqr, int piece, int dir)
\r
1252 int x = sqr, step = kStep[dir], piece1, piece2, d1, d2, r1, r2, y;
\r
1253 while( board[x+=step] == EMPTY );
\r
1254 piece1 = board[x];
\r
1255 if(piece1 != EDGE) { // x has hit a piece
\r
1257 r1 = p[piece1].range[dir+4];
\r
1258 y = sqr; while( board[y-=step] == EMPTY );
\r
1259 piece2 = board[y];
\r
1260 if(piece2 != EDGE) { // both ends of the ray hit a piece
\r
1262 r2 = p[piece2].range[dir];
\r
1263 if(r1 >= d1) { // piece1 hits us
\r
1264 attacks[2*sqr + (piece1 & WHITE)] += one[dir+4];
\r
1265 if(r1 >= d1 + d2) // was hitting piece2 before, now blocked
\r
1266 attacks[2*y + (piece1 & WHITE)] -= one[dir+4];
\r
1268 if(r2 >= d2) { // piece2 hits us
\r
1269 attacks[2*sqr + (piece2 & WHITE)] += one[dir];
\r
1270 if(r2 >= d1 + d2) // was hitting piece1 before, now blocked
\r
1271 attacks[2*x + (piece2 & WHITE)] -= one[dir];
\r
1273 if( Hit(p[piece].range[dir], d1) )
\r
1274 attacks[2*sqr + stm] += one[dir];
\r
1275 if( Hit(p[piece].range[dir+4], d2) )
\r
1276 attacks[2*sqr + stm] += one[dir+4];
\r
1280 x = sqr; while( board[x-=step] == EMPTY );
\r
1281 piece1 = board[x];
\r
1282 if(piece1 == EDGE) return; // ray empty on both sides
\r
1284 r1 = p[piece1].range[dir];
\r
1287 // we only get here if one side looks to the board edge
\r
1288 if(r1 >= d1) // piece1 hits us
\r
1289 attacks[2*sqr + (piece1 & WHITE)] += one[dir^4];
\r
1290 if( Hit(p[piece].range[dir], d1) )
\r
1291 attacks[2*sqr + stm] += one[dir];
\r
1296 { // determines attacks on square and blocking when a piece lands on an empty square
\r
1298 for(i=0; i<4; i++) {
\r
1299 Disconnect(sqr, board[sqr], i);
\r
1304 Evacuate (int sqr, int piece)
\r
1305 { // determines change in attacks on neighbors due to unblocking and mover when the mentioned piece vacates the given square
\r
1307 for(i=0; i<4; i++) Connect(sqr, piece, i);
\r
1311 MakeMove(Move m, UndoInfo *u)
\r
1313 int deferred = ABSENT;
\r
1314 // first execute move on board
\r
1315 u->from = m>>SQLEN & SQUARE;
\r
1316 u->to = m & SQUARE;
\r
1317 u->piece = board[u->from];
\r
1318 board[u->from] = EMPTY;
\r
1320 u->revMoveCount = cnt50++;
\r
1321 u->savKeyL = hashKeyL;
\r
1322 u->savKeyH = hashKeyH;
\r
1323 u->epVictim[0] = EMPTY;
\r
1325 if(p[u->piece].promoFlag & LAST_RANK) cnt50 = 0; // forward piece: move is irreversible
\r
1326 // TODO: put in some test for forward moves of non-backward pieces?
\r
1328 if(p[u->piece].value == 10*FVAL) { // move with Fire Demon
\r
1329 int i, f=~fireFlags[u->piece-2];
\r
1330 for(i=0; i<8; i++) fireBoard[u->from + kStep[i]] &= f; // clear old burn zone
\r
1333 if(m & (PROMOTE | DEFER)) {
\r
1334 if(m & DEFER) { // essential deferral: inform caller, but nothing special
\r
1336 u->new = u->piece;
\r
1338 p[u->piece].pos = ABSENT;
\r
1339 u->new = p[u->piece].promo;
\r
1340 u->booty = p[u->new].value - p[u->piece].value;
\r
1341 cnt50 = 0; // promotion irreversible
\r
1343 } else u->new = u->piece;
\r
1345 if(u->to >= SPECIAL) { // two-step Lion move
\r
1346 // take care of first e.p. victim
\r
1347 u->epSquare = u->from + epList[u->to - SPECIAL]; // decode
\r
1348 u->epVictim[0] = board[u->epSquare]; // remember for takeback
\r
1349 board[u->epSquare] = EMPTY; // and remove
\r
1350 p[u->epVictim[0]].pos = ABSENT;
\r
1351 // now take care of (optional) second e.p. victim
\r
1352 u->ep2Square = u->from + ep2List[u->to - SPECIAL]; // This is the (already evacuated) from-square when there is none!
\r
1353 u->epVictim[1] = board[u->ep2Square]; // remember
\r
1354 board[u->ep2Square] = EMPTY; // and remove
\r
1355 p[u->epVictim[1]].pos = ABSENT;
\r
1356 // decode the true to-square, and correct difEval and hash key for the e.p. captures
\r
1357 u->to = u->from + toList[u->to - SPECIAL];
\r
1358 u->booty += p[u->epVictim[1]].value + PST[p[u->epVictim[1]].pst + u->ep2Square];
\r
1359 u->booty += p[u->epVictim[0]].value + PST[p[u->epVictim[0]].pst + u->epSquare];
\r
1360 hashKeyL ^= p[u->epVictim[0]].pieceKey * squareKey[u->epSquare];
\r
1361 hashKeyH ^= p[u->epVictim[0]].pieceKey * squareKey[u->epSquare+BH];
\r
1362 hashKeyL ^= p[u->epVictim[1]].pieceKey * squareKey[u->ep2Square];
\r
1363 hashKeyH ^= p[u->epVictim[1]].pieceKey * squareKey[u->ep2Square+BH];
\r
1364 if(p[u->piece].value != 10*LVAL && p[u->epVictim[0]].value == 10*LVAL) deferred |= PROMOTE; // flag non-Lion x Lion
\r
1365 cnt50 = 0; // double capture irreversible
\r
1368 if(u->fireMask & fireBoard[u->to]) { // we moved next to enemy Fire Demon (must be done after SPECIAL, to decode to-sqr)
\r
1369 p[u->piece].pos = ABSENT; // this is suicide: implement as promotion to EMPTY
\r
1371 u->booty -= p[u->piece].value;
\r
1374 if(p[u->piece].value == 10*FVAL) { // move with Fire Demon that survives: burn
\r
1375 int i, f=fireFlags[u->piece-2];
\r
1376 for(i=0; i<8; i++) {
\r
1377 int x = u->to + kStep[i], burnVictim = board[x];
\r
1378 fireBoard[x] |= f; // mark new burn zone
\r
1379 u->epVictim[i+1] = burnVictim; // remember all neighbors, just in case
\r
1380 if(burnVictim != EMPTY && (burnVictim & TYPE) == xstm) { // opponent => actual burn
\r
1381 board[x] = EMPTY; // remove it
\r
1382 p[burnVictim].pos = ABSENT;
\r
1383 u->booty += p[burnVictim].value + PST[p[burnVictim].pst + x];
\r
1384 hashKeyL ^= p[burnVictim].pieceKey * squareKey[x];
\r
1385 hashKeyH ^= p[burnVictim].pieceKey * squareKey[x + BH];
\r
1386 cnt50 = 0; // actually burning something makes the move irreversible
\r
1389 u->epVictim[0] = EDGE; // kludge to flag to UnMake this is special move
\r
1392 u->booty += PST[p[u->new].pst + u->to] - PST[p[u->piece].pst + u->from];
\r
1394 u->victim = board[u->to];
\r
1395 p[u->victim].pos = ABSENT;
\r
1396 u->booty += p[u->victim].value + PST[p[u->victim].pst + u->to];
\r
1397 if(u->victim != EMPTY) cnt50 = 0; // capture irreversible
\r
1399 p[u->new].pos = u->to;
\r
1400 board[u->to] = u->new;
\r
1402 hashKeyL ^= p[u->new].pieceKey * squareKey[u->to]
\r
1403 ^ p[u->piece].pieceKey * squareKey[u->from]
\r
1404 ^ p[u->victim].pieceKey * squareKey[u->to];
\r
1405 hashKeyH ^= p[u->new].pieceKey * squareKey[u->to+BH]
\r
1406 ^ p[u->piece].pieceKey * squareKey[u->from+BH]
\r
1407 ^ p[u->victim].pieceKey * squareKey[u->to+BH];
\r
1413 UnMake(UndoInfo *u)
\r
1415 if(u->epVictim[0]) { // move with side effects
\r
1416 if(u->epVictim[0] == EDGE) { // fire-demon burn
\r
1417 int i, f=~fireFlags[u->piece-2];
\r
1418 for(i=0; i<8; i++) {
\r
1419 int x = u->to + kStep[i];
\r
1420 fireBoard[x] &= f;
\r
1421 board[x] = u->epVictim[i+1];
\r
1422 p[board[x]].pos = x; // even EDGE should have dummy entry in piece list
\r
1424 } else { // put Lion victim of first leg back
\r
1425 p[u->epVictim[1]].pos = u->ep2Square;
\r
1426 board[u->ep2Square] = u->epVictim[1];
\r
1427 p[u->epVictim[0]].pos = u->epSquare;
\r
1428 board[u->epSquare] = u->epVictim[0];
\r
1432 if(p[u->piece].value == 10*FVAL) {
\r
1433 int i, f=fireFlags[u->piece-2];
\r
1434 for(i=0; i<8; i++) fireBoard[u->from + kStep[i]] |= f; // restore old burn zone
\r
1437 p[u->victim].pos = u->to;
\r
1438 board[u->to] = u->victim; // can be EMPTY
\r
1440 p[u->new].pos = ABSENT;
\r
1441 p[u->piece].pos = u->from; // this can be the same as above
\r
1442 board[u->from] = u->piece;
\r
1444 cnt50 = u->revMoveCount;
\r
1445 hashKeyL = u->savKeyL;
\r
1446 hashKeyH = u->savKeyH;
\r
1450 GenCapts(int sqr, int victimValue)
\r
1451 { // generate all moves that capture the piece on the given square
\r
1452 int i, range, att = attacks[2*sqr + stm];
\r
1453 //printf("GenCapts(%c%d,%d) %08x\n",sqr%BW+'a',sqr/BW,victimValue,att);
\r
1454 if(!att) return; // no attackers at all!
\r
1455 for(i=0; i<8; i++) { // try all rays
\r
1456 int x, v, jumper, jcapt=0;
\r
1457 if(att & attackMask[i]) { // attacked by move in this direction
\r
1458 v = -kStep[i]; x = sqr;
\r
1459 while( board[x+=v] == EMPTY ); // scan towards source until we encounter a 'stop'
\r
1460 //printf("stop @ %c%d (dir %d)\n",x%BW+'a',x/BW,i);
\r
1461 if((board[x] & TYPE) == stm) { // stop is ours
\r
1462 int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];
\r
1463 //printf("attacker %d, range %d, dist %d\n", attacker, r, d);
\r
1464 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
1465 NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1467 if(!(att & attackMask[i])) continue; // no more; next direction
\r
1468 jcapt = p[board[x]].qval; // jump-capturer hierarchy
\r
1469 while(board[x+=v] == EMPTY);// one attack accounted for, but more to come, so skip to next stop
\r
1472 // we get here when we are on a piece that dous not attack us through a (limited) ranging move,
\r
1473 // it can be our own or an enemy with not (enough) range, or which is blocked
\r
1475 //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
1476 if((board[x] & TYPE) == stm) { // stop is ours
\r
1477 int attacker = board[x], d = dist[x-sqr], r = p[attacker].range[i];
\r
1478 if(jcapt < p[attacker].qval) { // it is a range jumper that jumps over the barrier
\r
1479 if(p[attacker].range[i] > 1) { // assumes all jump-captures are infinite range
\r
1480 NewCapture(x, sqr, p[attacker].promoFlag);
\r
1483 //if(board[x] == EDGE) { printf("edge hit %x-%x dir=%d att=%o\n", sqr, x, i, att); continue; }
\r
1485 if(r < 0) { // stop has non-standard moves
\r
1486 switch(p[attacker].range[i]) { // figure out what he can do (including multi-captures, which causes the complexity)
\r
1487 case F: // Lion power + 3-step (as in FF)
\r
1488 case S: // Lion power + ranging (as in BS)
\r
1491 NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1493 // now the multi-captures of designated victim together with lower-valued piece
\r
1494 if(d == 2) { // primary victim on second ring; look for victims to take in passing
\r
1495 if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr])
\r
1496 NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1497 if((i&1) == 0) { // orthogonal: two extra bent paths
\r
1499 if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])
\r
1500 NewCapture(x, SPECIAL + 8*(i-1&7) + (i+1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1502 if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])
\r
1504 NewCapture(x, SPECIAL + 8*(i+1&7) + (i-1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1506 } else { // primary victim on first ring
\r
1508 for(j=0; j<8; j++) { // we can go on in 8 directions after we captured it in passing
\r
1510 if(sqr + v == x || board[sqr+v] == EMPTY) // hit & run; make sure we include igui (attacker is still at x!)
\r
1511 NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag);
\r
1512 else if((board[sqr+v] & TYPE) == xstm && board[sqr+v] > board[sqr]) { // double capture
\r
1513 NewCapture(x, SPECIAL + 8*i + j + victimValue, p[attacker].promoFlag); // other victim after primary
\r
1514 if(dist[sqr+v-x] == 1) // other victim also on first ring; reverse order is possible
\r
1515 NewCapture(x, SPECIAL + reverse[8*i + j] + victimValue, p[attacker].promoFlag);
\r
1520 case D: // linear Lion move (as in HF, SE)
\r
1522 NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1524 if(d == 2) { // check if we can take intermediate with it
\r
1525 if((board[x-v] & TYPE) == xstm && board[x-v] > board[sqr])
\r
1526 NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // e.p.
\r
1527 } else { // d=1; can move on to second, or move back for igui
\r
1528 NewCapture(x, SPECIAL + 8*i + (i^4) + victimValue, p[attacker].promoFlag); // igui
\r
1529 if(board[sqr-v] == EMPTY || (board[sqr-v] & TYPE) == xstm && board[sqr-v] > board[sqr])
\r
1530 NewCapture(x, SPECIAL + 9*i + victimValue - SORTKEY(attacker), p[attacker].promoFlag); // hit and run
\r
1533 case J: // plain jump (as in KY, PH)
\r
1535 NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1538 case C: // FIDE Pawn
\r
1540 NewCapture(x, sqr + victimValue - SORTKEY(attacker), p[attacker].promoFlag);
\r
1544 //printf("mask[%d] = %o\n", i, att);
\r
1545 if((att & attackMask[i]) == 0) break;
\r
1547 // more attacks to come; san for next stop
\r
1548 if(jcapt < p[board[x]].qval) jcapt = p[board[x]].qval; // raise barrier for range jumpers further upstream
\r
1549 while(board[x+=v] == EMPTY); // this should never run off-board, if the attack map is not corrupted
\r
1553 // off-ray attacks
\r
1554 if(att & 0700000000) { // Knight attack
\r
1555 for(i=0; i<8; i++) { // scan all knight jumps to locate source
\r
1556 int x = sqr - nStep[i], attacker = board[x];
\r
1557 if(attacker == EMPTY || (attacker & TYPE) != stm) continue;
\r
1558 if(p[attacker].range[i] <= L && p[attacker].range[i] >= S || p[attacker].range[i] == N) { // has Knight jump in our direction
\r
1559 NewCapture(x, sqr + victimValue, p[attacker].promoFlag); // plain jump (as in N)
\r
1560 if(p[attacker].range[i] < N) { // Lion power; generate double captures over two possible intermediates
\r
1561 int v = kStep[i]; // leftish path
\r
1562 if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])
\r
1563 NewCapture(x, SPECIAL + 8*i + (i+1&7) + victimValue, p[attacker].promoFlag);
\r
1564 v = kStep[i+1]; // rightish path
\r
1565 if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr])
\r
1566 NewCapture(x, SPECIAL + 8*(i+1&7) + i + victimValue, p[attacker].promoFlag);
\r
1576 return (stm ? mobilityScore : -mobilityScore);
\r
1580 FireSet (UndoInfo *tb)
\r
1581 { // set fireFlags acording to remaining presene of Fire Demons
\r
1583 for(i=stm+2; p[i].value == 10*FVAL; i++) // Fire Demons are always leading pieces in list
\r
1584 if(p[i].pos != ABSENT) tb->fireMask |= fireFlags[i-2];
\r
1587 void TerminationCheck();
\r
1592 Search (int alpha, int beta, int difEval, int depth, int oldPromo, int promoSuppress)
\r
1594 int i, j, k, firstMove, oldMSP = msp, curMove, sorted, bad, phase, king, iterDep, replyDep, nextVictim, to, defer, dubious, bestMoveNr;
\r
1597 int score, bestScore, oldBest, curEval, iterAlpha;
\r
1598 Move move, nullMove;
\r
1601 Move hashMove; int index, nr, hit;
\r
1603 if(PATH) /*pboard(board),pmap(attacks, BLACK),*/printf("search(%d) {%d,%d} eval=%d, stm=%d\n",depth,alpha,beta,difEval,stm),fflush(stdout);
\r
1604 xstm = stm ^ WHITE;
\r
1605 //printf("map made\n");fflush(stdout);
\r
1607 k = p[king=royal[xstm]].pos;
\r
1608 if( k != ABSENT) {
\r
1609 if(attacks[2*k + stm]) {
\r
1610 if( p[king + 2].pos == ABSENT ) return INF; // we have an attack on his only King
\r
1612 } else { // he has no king! Test for attacks on Crown Prince
\r
1613 k = p[king + 2].pos;
\r
1614 if(attacks[2*k + stm]) return INF; // we have attack on Crown Prince
\r
1616 //printf("King safe\n");fflush(stdout);
\r
1617 // EVALUATION & WINDOW SHIFT
\r
1618 curEval = difEval + Evaluate();
\r
1619 alpha -= (alpha < curEval);
\r
1620 beta -= (beta <= curEval);
\r
1622 if(!(nodes++ & 4095)) TerminationCheck();
\r
1623 pv[pvPtr++] = 0; // start empty PV, directly behind PV of parent
\r
1626 firstMove = curMove = sorted = msp += 50; // leave 50 empty slots in front of move list
\r
1627 iterDep = 0; tb.fireMask = phase = 0;
\r
1630 index = hashKeyL & hashMask; nr = hashKeyL >> 30; hit = -1;
\r
1631 if(hashTable[index].lock[nr] == hashKeyH) hit = nr; else
\r
1632 if(hashTable[index].lock[4] == hashKeyH) hit = 4;
\r
1634 bestScore = hashTable[index].score[hit];
\r
1635 if((bestScore <= alpha || hashTable[index].flag[hit] & H_LOWER) &&
\r
1636 (bestScore >= beta || hashTable[index].flag[hit] & H_UPPER) ) {
\r
1637 iterDep = hashTable[index].depth[hit];
\r
1639 } else { // decide on replacement
\r
1640 if(depth >= hashTable[index].depth[nr]) hit = nr; else hit = 4;
\r
1644 replyDep = (depth < 1 ? depth-1 : iterDep);
\r
1645 while(++iterDep <= depth || iterDep == 1) {
\r
1646 if(flag && depth>= 0) printf("iter %d:%d\n", depth,iterDep),fflush(stdout);
\r
1647 oldBest = bestScore;
\r
1648 iterAlpha = alpha; bestScore = -INF; bestMoveNr = 0; resDep = 60;
\r
1649 for(curMove = firstMove; ; curMove++) { // loop over moves
\r
1650 if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase, firstMove, curMove, msp);fflush(stdout);
\r
1652 if(curMove >= msp) { // we ran out of moves; generate some new
\r
1654 case 0: // null move
\r
1656 bestScore = curEval; resDep = QSdepth;
\r
1657 if(bestScore >= beta || depth < -1) goto cutoff;
\r
1660 else if(curEval >= beta) {
\r
1662 score = -Search(-beta, 1-beta, -difEval, depth > 3 ? depth-3 : 0, promoSuppress & SQUARE, ABSENT);
\r
1664 if(score >= beta) { msp = oldMSP; retDep += 3; return score + (score < curEval); }
\r
1667 if(tenFlag) FireSet(&tb); // in tenjiku we must identify opposing Fire Demons to perform any moves
\r
1668 //if(PATH) printf("mask=%x\n",tb.fireMask),pbytes(fireBoard);
\r
1670 case 1: // hash move
\r
1673 moveStack[sorted = msp++] = hashMove;
\r
1678 case 2: // capture-gen init
\r
1679 nextVictim = xstm;
\r
1681 case 3: // generate captures
\r
1682 if(PATH) printf("%d:%2d:%2d next victim %d/%d\n",level,depth,iterDep,curMove,msp);
\r
1683 while(nextVictim < last[xstm]) { // more victims exist
\r
1684 int group, to = p[nextVictim += 2].pos; // take next
\r
1685 if(to == ABSENT) continue; // ignore if absent
\r
1686 if(!attacks[2*to + stm]) continue; // skip if not attacked
\r
1687 group = p[nextVictim].value; // remember value of this found victim
\r
1688 if(iterDep <= QSdepth + 1 && 2*group + curEval + 30 < alpha) { resDep = QSdepth + 1; goto cutoff; }
\r
1689 if(PATH) printf("%d:%2d:%2d group=%d, to=%c%d\n",level,depth,iterDep,group,to%BW+'a',to/BW+ONE);
\r
1691 if(PATH) printf("%d:%2d:%2d msp=%d\n",level,depth,iterDep,msp);
\r
1692 while(nextVictim < last[xstm] && p[nextVictim+2].value == group) { // more victims of same value exist
\r
1693 to = p[nextVictim += 2].pos; // take next
\r
1694 if(to == ABSENT) continue; // ignore if absent
\r
1695 if(!attacks[2*to + stm]) continue; // skip if not attacked
\r
1696 if(PATH) printf("%d:%2d:%2d p=%d, to=%c%d\n",level,depth,iterDep,nextVictim,to%BW+'a',to/BW+ONE);
\r
1698 if(PATH) printf("%d:%2d:%2d msp=%d\n",level,depth,iterDep,msp);
\r
1700 //printf("captures on %d generated, msp=%d\n", nextVictim, msp);
\r
1703 // if(currentVariant == V_CHESS && promoSuppress != ABSENT) { // e.p.
\r
1704 // int n = board[promoSuppress-1];
\r
1705 // if( n != EMPTY && (n&TYPE) == xstm && p[n].value == 8 )
\r
1707 phase = 4; // out of victims: all captures generated
\r
1708 case 4: // dubious captures
\r
1710 while( dubious < framePtr + 250 ) // add dubious captures back to move stack
\r
1711 moveStack[msp++] = moveStack[dubious++];
\r
1712 if(curMove != msp) break;
\r
1715 case 5: // killers
\r
1716 if(depth <= QSdepth) { resDep = QSdepth; goto cutoff; }
\r
1718 case 6: // non-captures
\r
1720 nullMove = GenNonCapts(oldPromo);
\r
1722 { // swap killers to front
\r
1723 Move h = killer[level][0]; int j = curMove;
\r
1724 for(i=curMove; i<msp; i++) if(moveStack[i] == h) { moveStack[i] = moveStack[j]; moveStack[j++] = h; break; }
\r
1725 h = killer[level][1];
\r
1726 for(i=curMove; i<msp; i++) if(moveStack[i] == h) { moveStack[i] = moveStack[j]; moveStack[j++] = h; break; }
\r
1730 sorted = msp; // do not sort noncapts
\r
1732 case 7: // bad captures
\r
1733 case 8: // PV null move
\r
1735 if(nullMove != ABSENT) {
\r
1736 moveStack[msp++] = nullMove + (nullMove << SQLEN) | DEFER; // kludge: setting DEFER guarantees != 0, and has no effect
\r
1738 //printf("# %d. sqr = %08x null = %08x\n", msp, nullMove, moveStack[msp-1]);
\r
1744 // MOVE EXTRACTION
\r
1746 if(flag & depth >= 0) printf("%2d:%d extract %d/%d\n", depth, iterDep, curMove, msp);
\r
1747 if(curMove > sorted) {
\r
1748 move = moveStack[sorted=j=curMove];
\r
1749 for(i=curMove+1; i<msp; i++)
\r
1750 if(moveStack[i] > move) move = moveStack[j=i]; // search move with highest priority
\r
1751 moveStack[j] = moveStack[curMove]; moveStack[curMove] = move; // swap highest-priority move to front of remaining
\r
1752 if(move == 0) { msp = curMove--; continue; } // all remaining moves must be 0; clip off move list
\r
1754 move = moveStack[curMove];
\r
1755 if(move == 0) continue; // skip invalidated move
\r
1757 if(flag & depth >= 0) printf("%2d:%d found %d/%d %08x %s\n", depth, iterDep, curMove, msp, moveStack[curMove], MoveToText(moveStack[curMove], 0));
\r
1761 defer = MakeMove(move, &tb);
\r
1763 if(flag & depth >= 0) printf("%2d:%d made %d/%d %s\n", depth, iterDep, curMove, msp, MoveToText(moveStack[curMove], 0));
\r
1764 for(i=2; i<=cnt50; i+=2) if(repStack[level-i+200] == hashKeyH) {
\r
1765 if(repDraws) { score = 0; goto repetition; }
\r
1766 moveStack[curMove] = 0; // erase forbidden move
\r
1767 if(!level) repeatMove[repCnt++] = move & 0xFFFFFF; // remember outlawed move
\r
1768 score = -INF; moveStack[curMove] = 0; goto repetition;
\r
1770 repStack[level+200] = hashKeyH;
\r
1772 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore);
\r
1773 path[level++] = move;
\r
1774 attacks += 2*bsize;
\r
1775 MapFromScratch(attacks); // for as long as incremental update does not work.
\r
1776 //if(flag & depth >= 0) printf("%2d:%d mapped %d/%d %s\n", depth, iterDep, curMove, msp, MoveToText(moveStack[curMove], 0));
\r
1777 //if(PATH) pmap(attacks, stm);
\r
1778 if(chuFlag && p[tb.victim].value == 10*LVAL) {// verify legality of Lion capture in Chu Shogi
\r
1780 if(p[tb.piece].value == 10*LVAL) { // Ln x Ln: can make Ln 'vulnerable' (if distant and not through intemediate > GB)
\r
1781 if(dist[tb.from-tb.to] != 1 && attacks[2*tb.to + stm] && p[tb.epVictim[0]].value <= 50)
\r
1782 score = -INF; // our Lion is indeed made vulnerable and can be recaptured
\r
1783 } else { // other x Ln
\r
1784 if(promoSuppress & PROMOTE) score = -INF; // non-Lion captures Lion after opponent did same
\r
1785 defer |= PROMOTE; // if we started, flag he cannot do it in reply
\r
1787 if(score == -INF) {
\r
1788 if(level == 1) repeatMove[repCnt++] = move & 0xFFFFFF | (p[tb.piece].value == 10*LVAL ? 3<<24 : 1 << 24);
\r
1789 moveStack[curMove] = 0; // zap illegal moves
\r
1794 score = -Search(-beta, -iterAlpha, -difEval - tb.booty, replyDep, promoSuppress & ~PROMOTE, defer);
\r
1799 attacks -= 2*bsize;
\r
1803 xstm = stm; stm ^= WHITE;
\r
1804 if(abortFlag > 0) { // unwind search
\r
1805 printf("# abort (%d) @ %d\n", abortFlag, level);
\r
1806 if(curMove == firstMove) bestScore = oldBest, bestMoveNr = firstMove; // none searched yet
\r
1810 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore);
\r
1812 // ALPHA-BETA STUFF
\r
1813 if(score > bestScore) {
\r
1814 bestScore = score; bestMoveNr = curMove;
\r
1815 if(score > iterAlpha) {
\r
1816 iterAlpha = score;
\r
1817 if(curMove < firstMove + 5) { // if not too much work, sort move to front
\r
1819 for(i=curMove; i>firstMove; i--) {
\r
1820 moveStack[i] = moveStack[i-1];
\r
1822 moveStack[firstMove] = move;
\r
1823 } else { // late move appended in front of list, and leaves hole in list
\r
1824 moveStack[--firstMove] = move;
\r
1825 moveStack[curMove] = 0;
\r
1827 bestMoveNr = firstMove;
\r
1828 if(score >= beta) { // beta cutoff
\r
1830 if(iterDep == depth && move != killer[level][0]) {
\r
1832 killer[level][1] = killer[level][0]; killer[level][0] = move;
\r
1839 for(pvPtr = myPV+1; pv[pvPtr++] = pv[i++]; ); // copy daughter PV
\r
1840 pv[myPV] = move; // behind our move (pvPtr left at end of copy)
\r
1845 if(retDep < resDep) resDep = retDep;
\r
1849 if(!level) { // root node
\r
1850 lastRootIter = GetTickCount() - startTime;
\r
1851 if(postThinking > 0) {
\r
1852 int i; // WB thinking output
\r
1853 printf("%d %d %d %d", iterDep, bestScore, lastRootIter/10, nodes);
\r
1854 if(ponderMove) printf(" (%s)", MoveToText(ponderMove, 0));
\r
1855 for(i=0; pv[i]; i++) printf(" %s", MoveToText(pv[i], 0));
\r
1856 if(iterDep == 1) printf(" { root eval = %4.2f dif = %4.2f; abs = %4.2f}", curEval/100., difEval/100., PSTest()/100.);
\r
1860 printf("# s=%d t=%d 1=%d 3=%d f=%d\n",startTime,GetTickCount(),tlim1,tlim3,abortFlag);
\r
1861 if(!(abortFlag & 1) && GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish
\r
1863 replyDep = iterDep;
\r
1866 hashTable[index].lock[hit] = hashKeyH;
\r
1867 hashTable[index].depth[hit] = iterDep;
\r
1868 hashTable[index].flag[hit] = (bestScore < beta) * H_UPPER;
\r
1869 if(bestScore > alpha) {
\r
1870 hashTable[index].flag[hit] |= H_LOWER;
\r
1871 hashTable[index].move[hit] = bestMoveNr ? moveStack[bestMoveNr] : 0;
\r
1872 } else hashTable[index].move[hit] = 0;
\r
1877 retFirst = firstMove;
\r
1878 msp = oldMSP; // pop move list
\r
1879 pvPtr = myPV; // pop PV
\r
1880 retMove = bestMoveNr ? moveStack[bestMoveNr] : 0;
\r
1881 retDep = resDep + 1;
\r
1882 if(PATH) printf("return %d: %d %d\n", depth, bestScore, curEval);
\r
1883 return bestScore + (bestScore < curEval);
\r
1890 for(i=0; i<182; i++) {
\r
1891 printf("%3d. %3d %3d %4d %02x %d ", i, p[i].value, p[i].promo, p[i].pos, p[i].promoFlag&255, p[i].qval);
\r
1892 for(j=0; j<8; j++) printf(" %2d", p[i].range[j]);
\r
1893 if(i<2 || i>11) printf("\n"); else printf(" %02x\n", fireFlags[i-2]&255);
\r
1895 printf("last: %d / %d\nroyal %d / %d\n", last[WHITE], last[BLACK], royal[WHITE], royal[BLACK]);
\r
1902 for(i=BH+2; i>-4; i--) {
\r
1904 for(j=-3; j<BH+3; j++) printf("%4d", b[BW*i+j]);
\r
1910 pbytes (unsigned char *b)
\r
1913 for(i=BH-1; i>=0; i--) {
\r
1914 for(j=0; j<BH; j++) printf("%3x", b[BW*i+j]);
\r
1920 pmap (int *m, int col)
\r
1923 for(i=BH-1; i>=0; i--) {
\r
1925 for(j=0; j<BH; j++) printf("%10o", m[2*(BW*i+j)+col]);
\r
1931 pmoves(int start, int end)
\r
1934 printf("# move stack from %d to %d\n", start, end);
\r
1935 for(i=start; i<end; i++) {
\r
1937 f = m>>SQLEN & SQUARE;
\r
1939 printf("# %3d. %08x %3d-%3d %s\n", i, m, f, t, MoveToText(m, 0));
\r
1943 /********************************************************/
\r
1944 /* Example of a WinBoard-protocol driver, by H.G.Muller */
\r
1945 /********************************************************/
\r
1947 #include <stdio.h>
\r
1949 // four different constants, with values for WHITE and BLACK that suit your engine
\r
1953 // some value that cannot occur as a valid move
\r
1956 // some parameter of your engine
\r
1957 #define MAXMOVES 2000 /* maximum game length */
\r
1958 #define MAXPLY 20 /* maximum search depth */
\r
1963 typedef Move MOVE;
\r
1965 int moveNr; // part of game state; incremented by MakeMove
\r
1966 MOVE gameMove[MAXMOVES]; // holds the game history
\r
1968 // Some routines your engine should have to do the various essential things
\r
1969 int MakeMove2(int stm, MOVE move); // performs move, and returns new side to move
\r
1970 void UnMake2(MOVE move); // unmakes the move;
\r
1971 int Setup2(char *fen); // sets up the position from the given FEN, and returns the new side to move
\r
1972 void SetMemorySize(int n); // if n is different from last time, resize all tables to make memory usage below n MB
\r
1973 char *MoveToText(MOVE move, int m); // converts the move from your internal format to text like e2e2, e1g1, a7a8q.
\r
1974 MOVE ParseMove(char *moveText); // converts a long-algebraic text move to your internal move format
\r
1975 int SearchBestMove(MOVE *move, MOVE *ponderMove);
\r
1976 void PonderUntilInput(int stm); // Search current position for stm, deepening forever until there is input.
\r
1978 UndoInfo undoInfo;
\r
1979 int sup0, sup1, sup2; // promo suppression squares
\r
1980 int lastLift, lastPut;
\r
1983 MakeMove2 (int stm, MOVE move)
\r
1986 FireSet(&undoInfo);
\r
1987 sup0 = sup1; sup1 = sup2;
\r
1988 sup2 = MakeMove(move, &undoInfo);
\r
1989 if(chuFlag && p[undoInfo.victim].value == 10*LVAL && p[undoInfo.piece].value != 10*LVAL) sup2 |= PROMOTE;
\r
1990 rootEval = -rootEval - undoInfo.booty;
\r
1991 for(i=0; i<200; i++) repStack[i] = repStack[i+1];
\r
1992 repStack[199] = hashKeyH;
\r
1993 printf("# makemove %08x %c%d %c%d\n", move, sup1%BW+'a', sup1/BW, sup2%BW+'a', sup2/BW);
\r
1994 return stm ^ WHITE;
\r
1998 UnMake2 (MOVE move)
\r
2001 rootEval = -rootEval - undoInfo.booty;
\r
2002 UnMake(&undoInfo);
\r
2003 for(i=200; i>0; i--) repStack[i] = repStack[i-1];
\r
2004 sup2 = sup1; sup1 = sup0;
\r
2007 char fenNames[] = "RV....DKDEFL..DHGB......SMLNKN..FK....BT..VM..PH...."; // pairs of char
\r
2008 char fenPromo[] = "WLDHSMSECPB R HFDE....WHFB..LNG ..DKVMFS..FO..FK...."; // pairs of char
\r
2011 Convert (char *fen)
\r
2013 char *p = fenArray, *q, *rows[36], tmp[4000];
\r
2015 printf("# convert FEN '%s'\n", fen);
\r
2016 q = strchr(fen, ' '); if(q) *q = 0; q = fen;
\r
2017 do { rows[n++] = q; q = strchr(q, '/'); if(!q) break; *q++ = 0; } while(1);
\r
2019 while(--n >= 0) { strcat(tmp, rows[n]); if(n) strcat(tmp, "/"); }
\r
2021 printf("# flipped FEN '%s'\n", fen);
\r
2023 if(*fen == ' ') { *p = 0; break; }
\r
2024 if(n=atoi(fen)) fen++; // digits read
\r
2025 if(n > 9) fen++; // double digit
\r
2026 while(n-- > 0) *p++ = '.'; // expand to empty squares
\r
2027 if(isalpha(*fen)) {
\r
2028 char *table = fenNames;
\r
2029 n = *fen > 'Z' ? 'a' - 'A' : 0;
\r
2030 if((currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK) && *fen - n == 'N' // In Chess N is Knight, not Lion
\r
2031 || table[2* (*fen - 'A' - n)] == '.') *p++ = *fen; else {
\r
2033 *p++ = table[2* (*fen - 'A' - n)] + n;
\r
2034 *p++ = table[2* (*fen - 'A' - n)+1] + n;
\r
2036 } else *p++ = *fen;
\r
2039 printf("# converted FEN '%s'\n", fenArray);
\r
2044 Setup2 (char *fen)
\r
2048 char *q = strchr(fen, '\n');
\r
2050 if(q = strchr(fen, ' ')) stm = (q[1] == 'b' ? BLACK : WHITE); // fen contains color field
\r
2051 if(strchr(fen, '.') || strchr(fen, ':')) array = fen; else array = Convert(fen);
\r
2053 SetUp(array, currentVariant);
\r
2054 sup0 = sup1 = sup2 = ABSENT;
\r
2055 rootEval = cnt50 = hashKeyH = hashKeyL = moveNr = 0;
\r
2060 SetMemorySize (int n)
\r
2063 static HashBucket *realHash;
\r
2064 static int oldSize;
\r
2067 if(n != oldSize) {
\r
2068 if(oldSize) free(realHash);
\r
2069 while(m*sizeof(HashBucket) <= n*512) m <<= 1;
\r
2070 m *= 1024; hashMask = m - 1;
\r
2071 realHash = calloc(m + 1, sizeof(HashBucket));
\r
2072 l = (intptr_t) realHash; hashTable = (HashBucket*) (l & ~63); // align with cache line
\r
2078 MoveToText (MOVE move, int multiLine)
\r
2080 static char buf[50];
\r
2081 int f = move>>SQLEN & SQUARE, g = f, t = move & SQUARE;
\r
2082 char *promoChar = "";
\r
2083 if(f == t) { sprintf(buf, "@@@@"); return buf; } // null-move notation in WB protocol
\r
2085 if(t >= SPECIAL) { // kludgy! Print as side effect non-standard WB command to remove victims from double-capture (breaks hint command!)
\r
2086 int e = f + epList[t - SPECIAL];
\r
2087 // printf("take %c%d\n", e%BW+'a', e/BW+ONE);
\r
2088 sprintf(buf, "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;
\r
2089 if(multiLine) printf("move %s\n", buf), buf[0] = '\0';
\r
2090 if(ep2List[t - SPECIAL]) {
\r
2091 e = g + ep2List[t - SPECIAL];
\r
2092 // printf("take %c%d\n", e%BW+'a', e/BW+ONE);
\r
2093 sprintf(buf+strlen(buf), "%c%d%c%d,", f%BW+'a', f/BW+ONE, e%BW+'a', e/BW+ONE); f = e;
\r
2094 if(multiLine) printf("move %s\n", buf), buf[0] = '\0';
\r
2096 t = g + toList[t - SPECIAL];
\r
2098 if(move & PROMOTE) promoChar = currentVariant == V_MAKRUK ? "m" : repDraws ? "q" : "+";
\r
2099 sprintf(buf+strlen(buf), "%c%d%c%d%s", f%BW+'a', f/BW+ONE, t%BW+'a', t/BW+ONE, promoChar);
\r
2104 ReadSquare (char *p, int *sqr)
\r
2108 r = atoi(p + 1) - ONE;
\r
2110 return 2 + (r + ONE > 9);
\r
2113 int listStart, listEnd;
\r
2114 char boardCopy[BSIZE];
\r
2118 { // create move list on move stack
\r
2120 for(i=0; i< BSIZE; i++) boardCopy[i] = !!board[i];
\r
2121 MapFromScratch(attacks);
\r
2122 postThinking--; repCnt = 0; tlim1 = tlim2 = tlim3 = 1e8; abortFlag = msp = 0;
\r
2123 Search(-INF-1, INF+1, 0, 1, sup1 & ~PROMOTE, sup2);
\r
2125 listStart = retFirst; listEnd = msp = retMSP;
\r
2129 ParseMove (char *moveText)
\r
2131 int i, j, f, t, t2, e, ret, deferred=0;
\r
2132 char c = moveText[0];
\r
2133 moveText += ReadSquare(moveText, &f);
\r
2134 moveText += ReadSquare(moveText, &t); t2 = t;
\r
2135 if(*moveText == ',') {
\r
2137 moveText += ReadSquare(moveText, &e);
\r
2138 if(e != t) return INVALID; // must continue with same piece
\r
2140 moveText += ReadSquare(moveText, &t);
\r
2141 for(i=0; i<8; i++) if(f + kStep[i] == e) break;
\r
2142 if(i >= 8) return INVALID; // this rejects Lion Dog 2+1 and 2-1 moves!
\r
2143 for(j=0; j<8; j++) if(e + kStep[j] == t) break;
\r
2144 if(j >= 8) return INVALID; // this rejects Lion Dog 1+2 moves!
\r
2145 t2 = SPECIAL + 8*i + j;
\r
2147 ret = f<<SQLEN | t2;
\r
2148 if(*moveText != '\n' && *moveText != '=') ret |= PROMOTE;
\r
2149 printf("# suppress = %c%d\n", sup1%BW+'a', sup1/BW);
\r
2151 for(i=listStart; i<listEnd; i++) {
\r
2152 if(moveStack[i] == INVALID) continue;
\r
2153 if(c == '@' && (moveStack[i] & SQUARE) == (moveStack[i] >> SQLEN & SQUARE)) break; // any null move matches @@@@
\r
2154 if((moveStack[i] & (PROMOTE | DEFER-1)) == ret) break;
\r
2155 if((moveStack[i] & DEFER-1) == ret) deferred = i; // promoted version of entered non-promotion is legal
\r
2157 printf("# moveNr = %d in {%d,%d}\n", i, listStart, listEnd);
\r
2158 if(i>=listEnd) { // no exact match
\r
2159 if(deferred) { // but maybe non-sensical deferral
\r
2160 int flags = p[board[f]].promoFlag;
\r
2161 printf("# deferral of %d\n", deferred);
\r
2162 i = deferred; // in any case we take that move
\r
2163 if(!(flags & promoBoard[t] & (CANT_DEFER | LAST_RANK))) { // but change it into a deferral if that is allowed
\r
2164 moveStack[i] &= ~PROMOTE;
\r
2165 if(p[board[f]].value == 40) p[board[f]].promoFlag &= LAST_RANK; else
\r
2166 if(!(flags & promoBoard[f])) moveStack[i] |= DEFER; // came from outside zone, so essential deferral
\r
2169 if(i >= listEnd) {
\r
2170 for(i=listStart; i<listEnd; i++) printf("# %d. %08x %08x %s\n", i-50, moveStack[i], ret, MoveToText(moveStack[i], 0));
\r
2172 for(i=0; i<repCnt; i++) {if((repeatMove[i] & 0xFFFFFF) == ret) {
\r
2173 if(repeatMove[i] & 1<<24) reason = (repeatMove[i] & 1<<25 ? "Distant capture of protected Lion" : "Counterstrike against Lion");
\r
2174 else reason = "Repeats earlier position";
\r
2177 printf("# %d. %08x %08x %s\n", i, repeatMove[i], ret, MoveToText(repeatMove[i], 0));
\r
2181 return (i >= listEnd ? INVALID : moveStack[i]);
\r
2185 Highlight(char *coords)
\r
2187 int i, j, n, sqr, cnt=0;
\r
2188 char b[BSIZE], buf[2000], *q;
\r
2189 for(i=0; i<bsize; i++) b[i] = 0;
\r
2190 ReadSquare(coords, &sqr);
\r
2192 for(i=listStart; i<listEnd; i++) {
\r
2193 if(sqr == (moveStack[i]>>SQLEN & SQUARE)) {
\r
2194 int t = moveStack[i] & SQUARE;
\r
2195 if(t >= SPECIAL) continue;
\r
2196 b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++;
\r
2199 if(!cnt) { // no moves from given square
\r
2200 if(sqr != lastPut) return; // refrain from sending empty FEN
\r
2201 // we lifted a piece for second leg of move
\r
2202 for(i=listStart; i<listEnd; i++) {
\r
2203 if(lastLift == (moveStack[i]>>SQLEN & SQUARE)) {
\r
2204 int e, t = moveStack[i] & SQUARE;
\r
2205 if(t < SPECIAL) continue; // only special moves
\r
2206 e = lastLift + epList[t - SPECIAL]; // decode
\r
2207 t = lastLift + toList[t - SPECIAL];
\r
2208 if(e != sqr) continue;
\r
2209 b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++;
\r
2213 } else lastLift = sqr; // remember
\r
2216 for(i=BH-1; i>=0; i--) {
\r
2217 for(j=0; j<BH; j++) {
\r
2219 if(b[n]) *q++ = b[n]; else {
\r
2220 if(q > buf && q[-1] <= '9' && q[-1] >= '0') {
\r
2223 if(q > buf+1 && q[-2] <= '9' && q[-2] >= '0') q[-2]++; else q[-1] = '1', *q++ = '0';
\r
2225 } else *q++ = '1';
\r
2231 printf("highlight %s\n", buf);
\r
2234 int timeLeft; // timeleft on engine's clock
\r
2235 int mps, timeControl, inc, timePerMove; // time-control parameters, to be used by Search
\r
2236 char inBuf[8000], command[80], ponderMoveText[20];
\r
2239 SetSearchTimes (int timeLeft)
\r
2241 int targetTime, movesLeft = BW*BH/4 + 20;
\r
2242 if(mps) movesLeft = mps - (moveNr>>1)%mps;
\r
2243 targetTime = (timeLeft - 1000*inc) / (movesLeft + 2) + 1000 * inc;
\r
2244 if(moveNr < 30) targetTime *= 0.5 + moveNr/60.; // speedup in opening
\r
2245 if(timePerMove > 0) targetTime = 0.5*timeLeft, movesLeft = 1;
\r
2246 tlim1 = 0.2*targetTime;
\r
2247 tlim2 = 1.9*targetTime;
\r
2248 tlim3 = 5*timeLeft / (movesLeft + 4.1);
\r
2252 SearchBestMove (MOVE *move, MOVE *ponderMove)
\r
2255 startTime = GetTickCount();
\r
2257 MapFromScratch(attacks);
\r
2258 retMove = INVALID; repCnt = 0;
\r
2259 score = Search(-INF-1, INF+1, rootEval, maxDepth, sup1, sup2);
\r
2261 *ponderMove = pv[1];
\r
2267 PonderUntilInput (int stm)
\r
2269 MapFromScratch(attacks);
\r
2270 repCnt = 0; abortFlag = -1;
\r
2271 Search(-INF-1, INF+1, rootEval, maxDepth, sup1, sup2);
\r
2274 int TakeBack(int n)
\r
2275 { // reset the game and then replay it to the desired point
\r
2277 Init(currentVariant); stm = Setup2(NULL);
\r
2278 printf("# setup done");fflush(stdout);
\r
2279 last = moveNr - n; if(last < 0) last = 0;
\r
2280 for(moveNr=0; moveNr<last; moveNr++) stm = MakeMove2(stm, gameMove[moveNr]),printf("make %2d: %x\n", moveNr, gameMove[moveNr]);
\r
2284 void PrintResult(int stm, int score)
\r
2287 if(reason) sprintf(tail, " {%s}", reason); else *tail = 0;
\r
2288 if(score == 0) printf("1/2-1/2%s\n", tail);
\r
2289 if(score > 0 && stm == WHITE || score < 0 && stm == BLACK) printf("1-0%s\n", tail);
\r
2290 else printf("0-1%s\n", tail);
\r
2293 void GetLine(int root)
\r
2297 // wait for input, and read it until we have collected a complete line
\r
2298 for(i = 0; (inBuf[i] = c = getchar()) != '\n'; i++) if(c == EOF || i>7997) exit(0);
\r
2301 // extract the first word
\r
2302 sscanf(inBuf, "%s", command);
\r
2303 printf("# in (mode = %d,%d): %s\n", root, abortFlag, command);
\r
2304 if(!strcmp(command, "otim")) { continue; } // do not start pondering after receiving time commands, as move will follow immediately
\r
2305 if(!strcmp(command, "time")) { sscanf(inBuf, "time %d", &timeLeft); continue; }
\r
2306 if(!strcmp(command, "put")) { ReadSquare(inBuf+4, &lastPut); continue; } // ditto
\r
2307 if(!strcmp(command, ".")) { inBuf[0] = 0; return; } // ignore for now
\r
2308 if(!strcmp(command, "lift")) { inBuf[0] = 0; Highlight(inBuf+5); return; } // treat here
\r
2315 TerminationCheck()
\r
2317 if(abortFlag < 0) { // check for input
\r
2318 if(InputWaiting()) GetLine(0); // read & examine input command
\r
2319 } else { // check for time
\r
2320 if(GetTickCount() - startTime > tlim3) abortFlag = 2;
\r
2326 int engineSide=NONE; // side played by engine
\r
2328 int i, score, curVarNr;
\r
2330 Init(V_CHU); // Chu
\r
2333 while(1) { // infinite loop
\r
2335 fflush(stdout); // make sure everything is printed before we do something that might take time
\r
2338 if(listEnd == 0) ListMoves(); // always maintain a list of legal moves in root position
\r
2341 if(stm == engineSide) { // if it is the engine's turn to move, set it thinking, and let it move
\r
2344 SetSearchTimes(10*timeLeft);
\r
2345 score = SearchBestMove(&move, &ponderMove);
\r
2347 if(move == INVALID) { // game apparently ended
\r
2348 int kcapt = 0, xstm = stm ^ WHITE, king, k = p[king=royal[xstm]].pos;
\r
2349 if( k != ABSENT) { // test if King capture possible
\r
2350 if(attacks[2*k + stm]) {
\r
2351 if( p[king + 2].pos == ABSENT ) kcapt = 1; // we have an attack on his only King
\r
2353 } else { // he has no king! Test for attacks on Crown Prince
\r
2354 k = p[king + 2].pos;
\r
2355 if(attacks[2*k + stm]) kcapt = 1; // we have attack on Crown Prince
\r
2357 if(kcapt) { // print King capture before claiming
\r
2359 printf("move %s\n", MoveToText(moveStack[msp-1], 1));
\r
2360 reason = "king capture";
\r
2361 } else reason = "resign";
\r
2362 engineSide = NONE; // so stop playing
\r
2363 PrintResult(stm, score);
\r
2365 stm = MakeMove2(stm, move); // assumes MakeMove returns new side to move
\r
2366 gameMove[moveNr++] = move; // remember game
\r
2367 printf("move %s\n", MoveToText(move, 1));
\r
2373 fflush(stdout); // make sure everything is printed before we do something that might take time
\r
2375 // now it is not our turn (anymore)
\r
2376 if(engineSide == ANALYZE) { // in analysis, we always ponder the position
\r
2377 PonderUntilInput(stm);
\r
2379 if(engineSide != NONE && ponder == ON && moveNr != 0) { // ponder while waiting for input
\r
2380 if(ponderMove == INVALID) { // if we have no move to ponder on, ponder the position
\r
2381 PonderUntilInput(stm);
\r
2383 int newStm = MakeMove2(stm, ponderMove);
\r
2384 PonderUntilInput(newStm);
\r
2385 UnMake2(ponderMove);
\r
2389 fflush(stdout); // make sure everything is printed before we do something that might take time
\r
2390 if(!*inBuf) GetLine(1); // takes care of time and otim commands
\r
2392 // recognize the command,and execute it
\r
2393 if(!strcmp(command, "quit")) { break; } // breaks out of infinite loop
\r
2394 if(!strcmp(command, "force")) { engineSide = NONE; continue; }
\r
2395 if(!strcmp(command, "analyze")) { engineSide = ANALYZE; continue; }
\r
2396 if(!strcmp(command, "exit")) { engineSide = NONE; continue; }
\r
2397 if(!strcmp(command, "level")) {
\r
2399 sscanf(inBuf, "level %d %d %d", &mps, &min, &inc) == 3 || // if this does not work, it must be min:sec format
\r
2400 sscanf(inBuf, "level %d %d:%d %d", &mps, &min, &sec, &inc);
\r
2401 timeControl = 60*min + sec; timePerMove = -1;
\r
2404 if(!strcmp(command, "protover")){
\r
2405 printf("feature ping=1 setboard=1 colors=0 usermove=1 memory=1 debug=1 sigint=0 sigterm=0\n");
\r
2406 printf("feature variants=\"normal,shatranj,makruk,chu,dai,tenjiku,12x12+0_fairy,9x9+0_shogi\"\n");
\r
2407 printf("feature myname=\"HaChu " VERSION "\" highlight=1\n");
\r
2408 printf("feature option=\"Resign -check 0\"\n"); // example of an engine-defined option
\r
2409 printf("feature option=\"Contempt -spin 0 -200 200\"\n"); // and another one
\r
2410 printf("feature done=1\n");
\r
2413 if(!strcmp(command, "option")) { // setting of engine-define option; find out which
\r
2414 if(sscanf(inBuf+7, "Resign=%d", &resign) == 1) continue;
\r
2415 if(sscanf(inBuf+7, "Contempt=%d", &contemptFactor) == 1) continue;
\r
2418 if(!strcmp(command, "sd")) { sscanf(inBuf, "sd %d", &maxDepth); continue; }
\r
2419 if(!strcmp(command, "st")) { sscanf(inBuf, "st %d", &timePerMove); continue; }
\r
2420 if(!strcmp(command, "memory")) { SetMemorySize(atoi(inBuf+7)); continue; }
\r
2421 if(!strcmp(command, "ping")) { printf("pong%s", inBuf+4); continue; }
\r
2422 // if(!strcmp(command, "")) { sscanf(inBuf, " %d", &); continue; }
\r
2423 if(!strcmp(command, "easy")) { ponder = OFF; continue; }
\r
2424 if(!strcmp(command, "hard")) { ponder = ON; continue; }
\r
2425 if(!strcmp(command, "go")) { engineSide = stm; continue; }
\r
2426 if(!strcmp(command, "post")) { postThinking = ON; continue; }
\r
2427 if(!strcmp(command, "nopost")) { postThinking = OFF;continue; }
\r
2428 if(!strcmp(command, "random")) { randomize = ON; continue; }
\r
2429 if(!strcmp(command, "hint")) { if(ponderMove != INVALID) printf("Hint: %s\n", MoveToText(ponderMove, 0)); continue; }
\r
2430 if(!strcmp(command, "book")) { continue; }
\r
2431 // non-standard commands
\r
2432 if(!strcmp(command, "p")) { pboard(board); continue; }
\r
2433 if(!strcmp(command, "f")) { pbytes(fireBoard); continue; }
\r
2434 if(!strcmp(command, "w")) { MapOneColor(WHITE, last[WHITE], attacks); pmap(attacks, WHITE); continue; }
\r
2435 if(!strcmp(command, "b")) { MapOneColor(BLACK, last[BLACK], attacks); pmap(attacks, BLACK); continue; }
\r
2436 if(!strcmp(command, "l")) { pplist(); continue; }
\r
2437 // ignored commands:
\r
2438 if(!strcmp(command, "xboard")) { continue; }
\r
2439 if(!strcmp(command, "computer")){ comp = 1; continue; }
\r
2440 if(!strcmp(command, "name")) { continue; }
\r
2441 if(!strcmp(command, "ics")) { continue; }
\r
2442 if(!strcmp(command, "accepted")){ continue; }
\r
2443 if(!strcmp(command, "rejected")){ continue; }
\r
2444 if(!strcmp(command, "result")) { continue; }
\r
2445 if(!strcmp(command, "hover")) { continue; }
\r
2446 if(!strcmp(command, "")) { continue; }
\r
2447 if(!strcmp(command, "usermove")){
\r
2448 int move = ParseMove(inBuf+9);
\r
2450 if(move == INVALID) {
\r
2451 if(reason) printf("Illegal move {%s}\n", reason); else printf("%s\n", reason="Illegal move");
\r
2452 if(comp) PrintResult(stm, -INF); // against computer: claim
\r
2454 stm = MakeMove2(stm, move);
\r
2455 ponderMove = INVALID; listEnd = 0;
\r
2456 gameMove[moveNr++] = move; // remember game
\r
2460 ponderMove = INVALID; // the following commands change the position, invalidating ponder move
\r
2462 if(!strcmp(command, "new")) {
\r
2463 engineSide = BLACK; Init(V_CHESS); stm = Setup2(NULL); maxDepth = MAXPLY; randomize = OFF; curVarNr = comp = 0;
\r
2466 if(!strcmp(command, "variant")) {
\r
2467 for(i=0; i<7; i++) {
\r
2468 sscanf(inBuf+8, "%s", command);
\r
2469 if(!strcmp(variants[i].name, command)) {
\r
2470 Init(curVarNr = i); stm = Setup2(NULL); break;
\r
2475 if(!strcmp(command, "setboard")){ engineSide = NONE; Init(curVarNr); stm = Setup2(inBuf+9); continue; }
\r
2476 if(!strcmp(command, "undo")) { stm = TakeBack(1); continue; }
\r
2477 if(!strcmp(command, "remove")) { stm = TakeBack(2); continue; }
\r
2478 printf("Error: unknown command\n");
\r