Fix ScorePosition() for MiniShogi.
[gnushogi.git] / gnushogi / eval.c
1 /*
2  * FILE: eval.c
3  *
4  * ----------------------------------------------------------------------
5  * Copyright (c) 1993, 1994, 1995 Matthias Mutz
6  * Copyright (c) 1999 Michael Vanier and the Free Software Foundation
7  *
8  * GNU SHOGI is based on GNU CHESS
9  *
10  * Copyright (c) 1988, 1989, 1990 John Stanback
11  * Copyright (c) 1992 Free Software Foundation
12  *
13  * This file is part of GNU SHOGI.
14  *
15  * GNU Shogi is free software; you can redistribute it and/or modify it
16  * under the terms of the GNU General Public License as published by the
17  * Free Software Foundation; either version 3 of the License,
18  * or (at your option) any later version.
19  *
20  * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
21  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
23  * for more details.
24  *
25  * You should have received a copy of the GNU General Public License along
26  * with GNU Shogi; see the file COPYING. If not, see
27  * <http://www.gnu.org/licenses/>.
28  * ----------------------------------------------------------------------
29  *
30  */
31
32 #include "gnushogi.h"
33 #include "pattern.h"
34
35 extern void
36 ShowStage(void);
37
38 /* Hash table for preventing multiple scoring of the same position */
39
40 int EADD = 0;       /* number of writes to the cache table */
41 int EGET = 0;       /* number of hits to the cache table */
42 int PUTVAR = false; /* shall the current scoring be cached? */
43
44
45 /* Pieces and colors of initial board setup */
46
47 #ifndef MINISHOGI
48 const small_short Stboard[NO_SQUARES] =
49 {
50     lance, knight, silver,   gold,   king,   gold, silver, knight,  lance,
51     0, bishop,      0,      0,      0,      0,      0,   rook,      0,
52     pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,
53     0,      0,      0,      0,      0,      0,      0,      0,      0,
54     0,      0,      0,      0,      0,      0,      0,      0,      0,
55     0,      0,      0,      0,      0,      0,      0,      0,      0,
56     pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,   pawn,
57     0,   rook,      0,      0,      0,      0,      0, bishop,      0,
58     lance, knight, silver,   gold,   king,   gold, silver, knight,  lance
59 };
60
61
62 const small_short Stcolor[NO_SQUARES] =
63 {
64     black,   black,   black,   black,
65     black,   black,   black,   black,   black,
66     neutral, black, neutral, neutral,
67     neutral, neutral, neutral,   black, neutral,
68     black,   black,   black,   black,
69     black,   black,   black,   black,   black,
70     neutral, neutral, neutral, neutral,
71     neutral, neutral, neutral, neutral, neutral,
72     neutral, neutral, neutral, neutral,
73     neutral, neutral, neutral, neutral, neutral,
74     neutral, neutral, neutral, neutral,
75     neutral, neutral, neutral, neutral, neutral,
76     white,   white,   white,   white,
77     white,   white,   white, white, white,
78     neutral, white, neutral, neutral,
79     neutral, neutral, neutral, white, neutral,
80     white,   white,   white,   white,
81     white,   white,   white, white, white
82 };
83 #else
84 const small_short Stboard[NO_SQUARES] =
85 {
86     king,   gold,   silver, bishop, rook,
87     pawn,   0,      0,      0,      0,
88     0,      0,      0,      0,      0,
89     0,      0,      0,      0,      pawn,
90     rook,   bishop, silver, gold,   king,
91 };
92
93
94 const small_short Stcolor[NO_SQUARES] =
95 {
96     black,   black,   black,   black,   black,
97     black,   neutral, neutral, neutral, neutral,
98     neutral, neutral, neutral, neutral, neutral,
99     neutral, neutral, neutral, neutral, white,
100     white,   white,   white,   white,   white
101 };
102 #endif
103
104 /* Actual pieces and colors */
105
106 small_short board[NO_SQUARES], color[NO_SQUARES];
107
108
109 /* relative piece values at the beginning of main stages */
110
111 #define MAIN_STAGES 4
112
113 static small_short ispvalue[NO_PIECES][MAIN_STAGES] =
114 {
115     {   0,  35,  70,  99 }, /* main stage borders */
116     /* ------------------------------------------ */
117     {   7,   7,   8,  10 }, /* Pawn               */
118 #ifndef MINISHOGI
119     {  20,  35,  45,  60 }, /* Lance              */
120     {  20,  35,  45,  60 }, /* Knight             */
121 #endif
122     {  35,  40,  60,  80 }, /* Silver             */
123     {  35,  50,  65,  80 }, /* Gold               */
124     {  90,  90,  90,  90 }, /* Bishop             */
125     {  95,  95,  95,  95 }, /* Rook               */
126     {  15,  25,  40,  65 }, /* promoted Pawn      */
127 #ifndef MINISHOGI
128     {  25,  45,  55,  65 }, /* promoted Lance     */
129     {  25,  45,  55,  65 }, /* promoted Knight    */
130 #endif
131     {  35,  55,  75,  75 }, /* promoted Silver    */
132     {  99,  99,  99,  99 }, /* promoted Bishop    */
133     {  97,  97,  99,  99 }, /* promoted Rook      */
134     { 100, 100, 100, 100 }, /* King               */
135 };
136
137 /* Features and Weights */
138
139 #define ATTACKED    0
140 #define HUNGP       1
141 #define HUNGX       2
142 #define CNTRL5TH    3
143 #define HOLES       4
144 #define PCASTLE     5
145 #define PATTACK     6
146 #define CTRLK       7
147 #define PROTECT     8
148 #define HCLSD       9
149 #define PINVAL     10
150 #define XRAY       11
151 #define OPENWRONG  12
152 #define SEED       13
153 #define LOOSE      14
154 #define MOBILITY   15
155 #define TARGET     16
156 #define KSFTY      17
157 #define HOPN       18
158 #define PROMD      19
159 #define KINGOD     20
160 #define PWNDROP    21
161 #define DFFDROP    22
162 #define FCLATTACK  23
163 #define KNGATTACK  24
164 #define KNGPROTECT 25
165 #define DNGLPC     26
166 #define LSATTACK   27
167 #define NIHATTACK  28
168 #define COHESION   29
169 #define OPPDROP    30
170
171
172 static small_short weight[NO_FEATURES + 1][MAIN_STAGES + 2] =
173 {
174     {  80, 100, 100,  40,  10,  15 },    /* ATTACKED      */
175     {  80, 100, 100,  50,  14,  10 },    /* HUNGP         */
176     {  80, 100, 100,  50,  18,  12 },    /* HUNGX         */
177     { 100,  50,   0,   0,   2,   1 },    /* CNTRL5TH      */
178     { 100, 100,  60,  10,   4,   2 },    /* HOLES         */
179     { 100,  50,   0,   0,  14,   7 },    /* PCASTLE       */
180     { 100,  50,   0,   0,   6,  12 },    /* PATTACK       */
181     {  10,  40,  70, 100,  10,  15 },    /* CTRLK         */
182     { 100,  80,  50,  40,   2,   1 },    /* PROTECT       */
183     {  40, 100,  40,   5,   4,   4 },    /* HCLSD         */
184     {  80, 100,  80,  30,  10,  15 },    /* PINVAL        */
185     {  80, 100,  60,  15,   6,  10 },    /* XRAY          */
186     { 100,  50,   0,   0,  15,  15 },    /* OPENWRONG     */
187     {   0,  40,  70, 100,   8,  12 },    /* SEED          */
188     {  50, 100,  80,  20,   5,   3 },    /* LOOSE         */
189     {  50, 100,  80,  50, 100, 100 },    /* MOBILITY (%)  */
190     {  50, 100,  80,  50,   4,   8 },    /* TARGET        */
191     {  50,  40, 100,  80,   8,   4 },    /* KSFTY         */
192     {  80, 100,  60,  20,   5,   5 },    /* HOPN          */
193     {  20,  40,  80, 100,   3,   6 },    /* PROMD         */
194     {  20,  40,  80, 100,   4,   1 },    /* KINGOD        */
195     {   5,  40, 100,  50,   0,   4 },    /* PWNDROP       */
196     {   0,  20,  80, 100,   0,   4 },    /* DFFDROP       */
197     {  20,  50, 100,  80,   0,   4 },    /* FCLATTACK     */
198     {   0,  20,  80, 100,   0,   8 },    /* KNGATTACK     */
199     {  40,  80, 100,  80,   6,   0 },    /* KNGPROTECT    */
200     {  50, 100,  60,  10,   0,   8 },    /* DNGPC         */
201     {  30, 100,  60,   5,   0,   6 },    /* LSATTACK      */
202     {   0,  50,  80, 100,   0,   8 },    /* NIHATTACK     */
203     {  50, 100,  80,  60,   8,   0 },    /* COHESION      */
204     { 100, 100,  80,  60,   4,   4 },    /* OPPDROP       */
205 };
206
207
208 short ADVNCM[NO_PIECES];
209
210 /* distance to enemy king */
211 static const short EnemyKingDistanceBonus[10] =
212 { 0, 6, 4, -1, -3, -4, -6, -8, -10, -12 };
213
214 /* distance to own king */
215 static const short OwnKingDistanceBonus[10] =
216 { 0, 5, 2, 1, 0, -1, -2, -3, -4, -5 };
217
218 /* distance to promotion zone */
219 #ifndef MINISHOGI
220 static const int PromotionZoneDistanceBonus[NO_ROWS] =
221 { 0, 0, 0, 0, 2, 6, 6, 8, 8 };
222 #else
223 static const int PromotionZoneDistanceBonus[NO_ROWS] =
224 { 0, 0, 2, 6, 8 };                                /* FIXME ? */
225 #endif
226
227 #define MAX_BMBLTY 20
228 #define MAX_RMBLTY 20
229 #define MAX_LMBLTY 8
230
231 /* Bishop mobility bonus indexed by # reachable squares */
232 static const short BMBLTY[MAX_BMBLTY] =
233 { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 14, 16, 16, 16, 16 };
234
235 /* Rook mobility bonus indexed by # reachable squares */
236 static const short RMBLTY[MAX_RMBLTY] =
237 { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 14, 16, 16, 16, 16 };
238
239 #ifndef MINISHOGI
240 /* Lance mobility bonus indexed by # reachable squares */
241 static const short LMBLTY[MAX_LMBLTY] =
242 { 0, 0, 0, 0, 4, 6, 8, 10 };
243 #endif
244
245 static const short MBLTY[NO_PIECES] =
246 { 0, 2,
247 #ifndef MINISHOGI
248   1, 10,
249 #endif
250   5, 5, 1, 1, 5,
251 #ifndef MINISHOGI
252   5, 5,
253 #endif
254   5, 1, 1, 4 };
255
256 static const short KTHRT[36] =
257 {   0,  -8, -20, -36, -52, -68, -80, -80, -80, -80, -80, -80,
258     -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80,
259     -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80 };
260
261 static small_short fvalue[2][NO_FEATURES];
262
263 long attack[2][NO_SQUARES];         /* threats to squares */
264 small_short sseed[NO_SQUARES];      /* square occupied by a seed piece? */
265
266 struct signature threats_signature[2] = /* statistics valid for position.. */
267 { { -1, -1 }, { -1, -1 } };             /* attack and sseed available */
268
269 small_short starget[2][NO_SQUARES]; /* significance as a target for a
270                                      * side of a square */
271 small_short sloose[NO_SQUARES];     /* square occupied by a loose piece? */
272 small_short shole[NO_SQUARES];      /* empty square a hole? */
273 small_short shung[NO_SQUARES];      /* hung piece? */
274
275 struct signature squares_signature =  /* statistics valid for position ... */
276 { 0, 0 };                /* starget, sloose, shole, shung available */
277
278 short target[2], seed[2], loose[2], hole[2];
279
280 short captured[2];  /* number of captured pieces */
281 short dcaptured[2]; /* different types of captured pieces */
282
283 small_short Kdist[2][NO_SQUARES];    /* distance to king */
284
285 short MAXADIST, MAXCDIST; /* maximum half move distance to pattern */
286
287 char GameType[2] = { UNKNOWN, UNKNOWN }; /* chosen game type of each side */
288
289
290 static short attack_opening_sequence[2];    /* current castle patterns */
291 static short castle_opening_sequence[2];    /* current attack formations */
292
293 static small_short Mpawn  [2][NO_SQUARES];
294 static small_short Msilver[2][NO_SQUARES];
295 static small_short Mgold  [2][NO_SQUARES];
296 static small_short Mking  [2][NO_SQUARES];
297 #ifndef MINISHOGI
298 static small_short Mlance [2][NO_SQUARES];
299 static small_short Mknight[2][NO_SQUARES];
300 #endif
301 static small_short Mbishop[2][NO_SQUARES];
302 static small_short Mrook  [2][NO_SQUARES];
303
304 static Mpiece_array Mpawn,
305 #ifndef MINISHOGI
306     Mlance, Mknight,
307 #endif
308     Msilver, Mgold, Mbishop, Mrook, Mking;
309
310 Mpiece_array *Mpiece[NO_PIECES] =
311 { NULL, &Mpawn,
312 #ifndef MINISHOGI
313   &Mlance, &Mknight,
314 #endif
315   &Msilver, &Mgold, &Mbishop, &Mrook,
316   &Mgold,
317 #ifndef MINISHOGI
318   &Mgold, &Mgold,
319 #endif
320   &Mgold, &Mbishop, &Mrook, &Mking };
321
322
323 static short c1, c2;
324 static small_short *PC1, *PC2;
325 static small_short *fv1;
326 static long *atk1, *atk2;
327 static long  a1, a2;
328
329 #define csquare(side, sq) ((side == black) ? sq : (NO_SQUARES - 1 - sq))
330 #define crow(side, sq)    row(csquare(side, sq))
331 #define ccolumn(side, sq) column(csquare(side, sq))
332
333
334 inline static short
335 on_csquare(short side, short piece, short square)
336 {
337     short sq;
338     /* FIXME: un-obfuscate this! */
339     return ((board[sq = csquare(side, square)] == piece)
340             && (color[sq] == side));
341 }
342
343
344 inline static short
345 on_column(short side, short piece, short c)
346 {
347     short sq;
348
349     for (sq = c; sq < NO_SQUARES; sq += NO_COLS)
350     {
351         if (on_csquare(side, piece, sq))
352             return true;
353     }
354
355     return false;
356 }
357
358
359 #define empty_csquare(side, square) \
360   (board[csquare(side, square)] == no_piece)
361
362 inline static short
363 on_left_side(short side, short piece)
364 {
365     short c;
366
367     for (c = 0; c < 4; c++)
368     {
369         if (on_column(side, piece, c))
370             return true;
371     }
372
373     return false;
374 }
375
376
377 inline static short
378 on_right_side(short side, short piece)
379 {
380     short c;
381
382     for (c = 5; c < NO_COLS; c++)
383     {
384         if (on_column(side, piece, c))
385             return true;
386     }
387
388     return false;
389 }
390
391
392 short pscore[2];  /* piece score for each side */
393
394
395
396
397 /*
398  * Fill array attack[side][] with info about attacks to a square.  Bits
399  * 16-31 are set if the piece (king .. pawn) attacks the square.  Bits 0-15
400  * contain a count of total attacks to the square.  Fill array sseed[] with
401  * info about occupation by a seed piece.
402  */
403
404 void
405 threats(short side)
406 {
407     short  u, sq;
408     long   c;
409     long  *a;
410 #ifdef SAVE_NEXTPOS
411     short d;
412 #else
413     unsigned char  *ppos, *pdir;
414 #endif
415     short i, kd, piece, xside;
416     small_short *PL;
417
418     if (MatchSignature(threats_signature[side]))
419     {
420         /* data valid for current positional signature */
421         return;
422     }
423
424     a = attack[side];
425     xside = side ^ 1;
426
427     array_zero(a, NO_SQUARES * sizeof(a[0]));
428
429     PL = PieceList[side];
430
431     for (i = PieceCnt[side]; i >= 0; i--)
432     {
433         short ptyp;
434
435         sq = PL[i];
436         piece = board[sq];
437         ptyp = ptype[side][piece];
438         c = control[piece];
439 #ifdef SAVE_NEXTPOS
440         u = first_direction(ptyp, &d, sq);
441 #else
442         ppos = (*nextpos[ptyp])[sq];
443         pdir = (*nextdir[ptyp])[sq];
444         u = ppos[sq];
445 #endif
446
447         do
448         {
449             a[u] = ((a[u] + 1) | c);
450
451             if ((kd = Kdist[xside][u]) < 2)
452             {
453                 sseed[sq] += 2 - kd;
454                 seed[side]++;
455             }
456
457 #ifdef SAVE_NEXTPOS
458             u = ((color[u] == neutral)
459                  ? next_position(ptyp, &d, sq, u)
460                  : next_direction(ptyp, &d, sq));
461 #else
462             u = ((color[u] == neutral) ? ppos[u] : pdir[u]);
463 #endif
464         }
465         while (u != sq);
466     }
467
468     /* data valid for current positional signature */
469     CopySignature(threats_signature[side]);
470 }
471
472
473
474 /*
475  * Compute the board square with nunmap offset "id".  If side == white,
476  * offset is negated.  inunmap[sq] is the corresponding nunmap index isq.
477  * nunmap[isq + id] computes the board square. If negative, it is outside
478  * the board.
479  */
480
481 static void
482 add_target(short sq, short side, short id)
483 {
484     short isq, tsq, xside;
485     isq = inunmap[sq];
486     tsq = (side == black) ? nunmap[isq + id] : nunmap[isq - id];
487
488     if (tsq >= 0)
489     {
490         target[xside = side^1]++;
491
492         if (attack[side][tsq])
493             starget[xside][tsq]++;  /* protected target square */
494         else
495             starget[xside][tsq] += 2; /* unprotected target square */
496     }
497 }
498
499
500
501 /*
502  * Target squares can be vertically ahead, diagonally ahead
503  * or diagonally behind.
504  */
505
506 static void
507 CheckTargetPiece(short sq, short side)
508 {
509     switch (board[sq])
510     {
511     case pawn: /* vertically ahead if unprotected */
512         if (!attack[side][sq])
513             add_target(sq, side, 11);
514         break;
515
516     case king: /* diagonally and vertically ahead */
517         add_target(sq, side, 10);
518         add_target(sq, side, 11);
519         add_target(sq, side, 12);
520         break;
521
522     case rook: /* diagonally ahead and behind */
523         add_target(sq, side, 10);
524         add_target(sq, side, 12);
525         add_target(sq, side, -10);
526         add_target(sq, side, -12);
527         break;
528
529     case bishop: /* vertically ahead */
530         add_target(sq, side, 11);
531         break;
532
533 #ifndef MINISHOGI
534     case knight: /* vertically ahead if advanced */
535         /* FIXME: gotta love them magic numbers... */
536         if ((sq != 1) && (sq != 7) && (sq != 73) && (sq != 79))
537             add_target(sq, side, 11);
538         break;
539 #endif
540     }
541 }
542
543
544
545 static short
546 ScoreKingOpeningFeatures(void)
547 {
548     short s = 0, sq = OwnKing, ds;
549
550     if (GameType[c1] == STATIC_ROOK)
551     {
552         /* Penalty for king on right side or fifth file */
553         short c;
554         c = 4 - ccolumn(c1, sq);
555
556         if ((c < 0) || ((c == 0) && (sq != kingP[c1])))
557             s += (ds = -c - c - fv1[OPENWRONG]);
558     }
559     else if (GameType[c1] == RANGING_ROOK)
560     {
561         /* Penalty for king on left side or fifth file */
562         short c;
563         c = 4 - ccolumn(c1, sq);
564
565         if ((c > 0) || ((c == 0) && (sq != kingP[c1])))
566         {
567             s += (ds = -c - c - fv1[OPENWRONG]);
568         }
569
570         /* Penalty for king moved before rook switch */
571         if (sq != kingP[c1])
572         {
573             if (on_csquare(c1, rook, 16))
574             {
575                 s += (ds = -4 * fv1[OPENWRONG]);
576             }
577         }
578         else
579         {
580             /* Penalty for sitting king after rook switch */
581             if (!on_csquare(c1, rook, 16))
582             {
583                 s += (ds = -2 * fv1[OPENWRONG]);
584             }
585         }
586
587         /* Penalty for defending general moved
588          * before king switch to right side */
589         if (ccolumn(c1, sq) < 6)
590         {
591             if (Mvboard[csquare(c1, 5)] || Mvboard[csquare(c1, 6)])
592             {
593                 s += (ds = -2 * fv1[OPENWRONG]);
594             }
595         }
596     }
597
598     return s;
599 }
600
601
602
603
604 inline static void
605 ExamineSquares(void)
606 {
607     short sq, side, piece, n;
608
609     if (MatchSignature(squares_signature))
610     {
611         /* data valid for current positional signature */
612         return;
613     }
614
615     array_zero(shole,   sizeof(shole));
616     array_zero(sloose,  sizeof(sloose));
617     array_zero(starget, sizeof(starget));
618
619     hole[0] = hole[1] = loose[0] = loose[1]
620         = target[0] = target[1] = 0;
621
622     for (sq = 0; sq < NO_SQUARES; sq++)
623     {
624         if ((side = color[sq]) == neutral)
625         {
626             if (InWhiteCamp(sq))
627             {
628                 if (!attack[white][sq])
629                 {
630                     shole[sq] = 1;
631                     hole[white]++;
632                 }
633             }
634             else if (InBlackCamp(sq))
635             {
636                 if (!attack[black][sq])
637                 {
638                     shole[sq] = 1;
639                     hole[black]++;
640                 }
641             }
642         }
643         else
644         {
645             /* occupied by "side" piece */
646             if (!attack[side][sq])
647             {
648                 sloose[sq] = 1;
649                 loose[side]++;
650             }
651
652             CheckTargetPiece(sq, side);
653         }
654     }
655
656     for (side = black; side <= white; side++)
657     {
658         captured[side] = dcaptured[side] = 0;
659
660         for (piece = pawn; piece <= rook; piece++)
661         {
662             if ((n = Captured[side][piece]) != 0)
663             {
664                 if (piece != pawn)
665                     captured[side] += n;
666
667                 dcaptured[side]++;
668             }
669         }
670     }
671
672     /* Data valid for current positional signature */
673     CopySignature(squares_signature);
674 }
675
676
677
678 /* ............    POSITIONAL EVALUATION ROUTINES    ............ */
679
680 /*
681  * Inputs are:
682  * mtl[side]       - value of all material
683  * hung[side]      - count of hung pieces
684  * Tscore[ply]     - search tree score for ply ply
685  * Pscore[ply]     - positional score for ply ply
686  * INCscore        - bonus score or penalty for certain moves
687  * Sdepth          - search goal depth
688  * xwndw           - evaluation window about alpha/beta
689  * EWNDW           - second evaluation window about alpha/beta
690  * ChkFlag[ply]    - checking piece at level ply or 0 if no check
691  * TesujiFlag[ply] - 1 if tesuji move at level ply or 0 if no tesuji
692  * PC1[column]     - # of my pawns in this column
693  * PC2[column]     - # of opponents pawns in column
694  * PieceCnt[side]  - just what it says
695  */
696
697
698
699
700 /*
701  * Compute an estimate of the score by adding the positional score from the
702  * previous ply to the material difference. If this score falls inside a
703  * window which is 180 points wider than the alpha-beta window (or within a
704  * 50 point window during quiescence search) call ScorePosition() to
705  * determine a score, otherwise return the estimated score.  "side" is the
706  * side which has to move.
707  */
708
709 int
710 evaluate(short side,
711          short ply,
712          short alpha,
713          short beta,
714          short INCscore,
715          short *InChk,     /* output Check flag     */
716          short *blockable) /* king threat blockable */
717 {
718     short xside;
719     short s;
720
721     xside = side ^ 1;
722     s = -Pscore[ply - 1] + mtl[side] - mtl[xside] /* - INCscore */;
723     hung[black] = hung[white] = 0;
724
725     /* should we use the estimete or score the position */
726     if ((ply == 1)
727         || (ply == Sdepth)
728         || (ply > Sdepth && s >= (alpha - 30) && s <= (beta + 30))
729 #ifdef CACHE
730         || (use_etable && CheckEETable(side))
731 #endif
732         )
733     {
734         short sq;
735
736         /* score the position */
737         array_zero(sseed, sizeof(sseed));
738
739         seed[0] = seed[1] = 0;
740         threats(side);
741
742         if (Anyattack(side, sq = PieceList[xside][0]) && (board[sq] == king))
743         {
744             *InChk = (board[sq = PieceList[side][0]] == king)
745                 ? SqAttacked(sq, xside, blockable)
746                 : false;
747
748             return ((SCORE_LIMIT + 1001) - ply);
749         }
750
751         threats(xside);
752         *InChk = (board[sq = PieceList[side][0]] == king)
753             ? Anyattack(xside, sq)
754             : false;
755         *blockable = true;
756         EvalNodes++;
757
758         if (ply > 4)
759             PUTVAR = true;
760
761         ExamineSquares();
762         s = ScorePosition(side);
763         PUTVAR = false;
764     }
765     else
766     {
767         /* use the estimate but look at check */
768         short sq;
769
770         *InChk = (board[sq = PieceList[side][0]] == king)
771             ? SqAttacked(sq, xside, blockable)
772             : false;
773
774         if ((board[sq = PieceList[xside][0]] == king)
775             && SqAttacked(sq, side, blockable))
776         {
777             return ((SCORE_LIMIT + 1001) - ply);
778         }
779     }
780
781     Pscore[ply] = s - mtl[side] + mtl[xside];
782     ChkFlag[ply - 1] = ((*InChk) ? Pindex[TOsquare] : 0);
783
784     return s;
785 }
786
787
788
789 static short
790 value_of_weakest_attacker(long a2)
791 {
792     short piece;
793     short min_value, v;
794     min_value = SCORE_LIMIT;
795
796     for (piece = pawn; piece <= king; piece++)
797     {
798         if (control[piece] & a2)
799         {
800             if (min_value > (v = (*value)[stage][piece]))
801                 min_value = v;
802         }
803     }
804
805     return min_value;
806 }
807
808
809
810
811 /*
812  * Find (promoted) Bishop, (promoted) Rook, and Lance mobility, x-ray
813  * attacks, and pins.  Let BRL be the bishop, rook, or lance.  Let P be the
814  * first piece (not a king or a pawn) in a direction and let Q be the
815  * second piece in the same direction.  If Q is an unprotected opponent's
816  * piece with bigger relative value than BRL, there is a pin if P is an
817  * opponent's piece and there is an x-ray attack if P belongs to this side.
818  * Increment the hung[] array if a pin is found.
819  */
820
821 inline int
822 BRLscan(short sq, short *mob)
823 {
824 #ifdef SAVE_NEXTPOS
825     short d, dd;
826 #else
827     unsigned char  *ppos, *pdir;
828 #endif
829
830     short s, mobx;
831     short u, xu, pin, ptyp, csq = column(sq);
832     short piece, upiece, xupiece, rvalue, ds;
833     small_short *Kd = Kdist[c2];
834
835     mobx = s = 0;
836     piece = board[sq];
837
838     rvalue = (*value)[stage][piece];
839     ptyp = ptype[c1][upiece = unpromoted[piece]];
840     rvalue = (*value)[stage][upiece];
841
842 #ifdef SAVE_NEXTPOS
843     u = first_direction(ptyp, &d, sq);
844 #else
845     ppos = (*nextpos[ptyp])[sq];
846     pdir = (*nextdir[ptyp])[sq];
847     u = ppos[sq];
848 #endif
849
850     pin = -1;           /* start new direction */
851
852     do
853     {
854         if (Kd[u] < 2)
855         {
856             s += (ds = fv1[CTRLK] * (2 - Kd[u]));
857         }
858
859         if ((ds = starget[c1][u]) != 0)
860         {
861             /* threatening a target square */
862             if ((pin < 0)               /* direct threat */
863                 || (color[pin] == c2))  /* pin threat    */
864             {
865                 s += (ds *= fv1[TARGET]);
866             }
867         }
868
869         if ((ds = shole[u]) != 0)
870         {
871             /* attacking or protecting a hole */
872             s += (ds = fv1[HOLES]);
873         }
874         else if (InPromotionZone(c1, u))
875         {
876             /* attacking a square in promotion zone */
877             s += (ds = fv1[HOLES] / 2);
878         }
879
880         if (color[u] == neutral)
881         {
882 #ifdef SAVE_NEXTPOS
883             dd = d;
884             xu = next_position(ptyp, &d, sq, u);
885
886             if (xu == next_direction(ptyp, &dd, sq))
887                 pin = -1;   /* oops new direction */
888 #else
889
890             if ((xu = ppos[u]) == pdir[u])
891                 pin = -1;   /* oops new direction */
892 #endif
893             u = xu;
894             mobx++;
895         }
896         else
897         {
898             /* there is a piece in current direction */
899             if (pin < 0)
900             {
901                 /* it's the first piece in the current direction */
902                 if (color[u] == c1)
903                 {
904 #ifndef MINISHOGI
905                     /* own intercepting piece in x-ray attack */
906                     if (upiece == lance)
907                     {
908                         /* lance x-ray */
909                         if (board[u] == pawn)
910                         {
911                             s += (ds = 2*fv1[PROTECT]);
912                         }
913                         else if (in_opening_stage)
914                         {
915                             s += (ds = -2*fv1[PROTECT]);
916                         }
917                     }
918                     else
919 #endif
920                     {
921                         /* bishop or rook x-ray */
922                         if ((upiece == bishop) && (board[u] == pawn)
923                             && (GameType[c1] == STATIC_ROOK))
924                         {
925                             s += (ds = -2*fv1[HCLSD]);
926                         }
927 #ifndef MINISHOGI
928                         else if ((upiece == rook) && (board[u] == lance)
929                                  && (GameType[c1] == STATIC_ROOK)
930                                  && (column(u) == csq))
931                         {
932                             s += (ds = fv1[XRAY]);
933                         }
934 #endif
935                     }
936                 }
937                 else
938                 {
939                     /* enemy's intercepting piece in pin attack */
940 #ifndef MINISHOGI
941                     if (upiece == lance)
942                     {
943                         /* lance pin attack */
944                         if (board[u] == pawn)
945                         {
946                             s += (ds = -2*fv1[PROTECT]);
947                         }
948                         else if (in_opening_stage)
949                         {
950                             s += (ds = 2 * fv1[PROTECT]);
951                         }
952                     }
953                     else
954 #endif
955                     {
956                         /* bishop or rook pin attack */
957                         if (board[u] == pawn)
958                         {
959                             s += (ds = -fv1[HCLSD]);
960                         }
961                     }
962                 }
963
964 #ifdef SAVE_NEXTPOS
965                 dd = d;
966                 xu = next_position(ptyp, &d, sq, u);
967
968                 if (xu != next_direction(ptyp, &dd, sq))
969                     pin = u;    /* not on the edge and on to find a pin */
970 #else
971                 if ((xu = ppos[u]) != pdir[u])
972                     pin = u;    /* not on the edge and on to find a pin */
973 #endif
974                 u = xu;
975             }
976             else
977             {
978                 /* it's the second piece in the current direction */
979
980                 if (color[u] == c1)
981                 {
982                     /* second piece is an own piece */
983                     if ((upiece == bishop) && (board[u] == pawn)
984                         && (GameType[c1] == STATIC_ROOK))
985                     {
986                         s += (ds = -fv1[HCLSD]);
987                     }
988                 }
989                 else
990                 {
991                     /* second piece is an enemy piece */
992                     if (upiece == bishop && board[u] == pawn)
993                     {
994                         s += (ds = -fv1[HCLSD]/2);
995                     }
996
997                     if (((*value)[stage][xupiece = unpromoted[board[u]]]
998                          > rvalue)
999                         || (atk2[u] == 0))
1000                     {
1001                         if (color[pin] == c2)
1002                         {
1003                             if ((xupiece == king) && (in_endgame_stage))
1004                             {
1005                                 s += (ds = 2 * fv1[PINVAL]);
1006                             }
1007                             else
1008                             {
1009                                 s += (ds = fv1[PINVAL]);
1010                             }
1011
1012                             if ((atk2[pin] == 0)
1013                                 || (atk1[pin] > control[board[pin]] + 1))
1014                             {
1015                                 hung[c2]++;
1016                                 shung[u]++;
1017                             }
1018                         }
1019                         else
1020                         {
1021 #ifndef MINISHOGI
1022                             if (upiece == lance)
1023                             {
1024                                 s += (ds = fv1[XRAY] / 2);
1025                             }
1026                             else
1027 #endif
1028                             {
1029                                 s += (ds = fv1[XRAY]);
1030                             }
1031                         }
1032                     }
1033                 }
1034
1035                 pin = -1;   /* new direction */
1036
1037 #ifdef SAVE_NEXTPOS
1038                 u = next_direction(ptyp, &d, sq);
1039 #else
1040                 u = pdir[u];
1041 #endif
1042             }
1043         }
1044     }
1045     while (u != sq);
1046
1047     *mob = mobx;
1048
1049     return s;
1050 }
1051
1052
1053 #define ctlSG (ctlS | ctlG | ctlPp | ctlLp | ctlNp | ctlSp)
1054
1055
1056
1057 /*
1058  * Assign penalties if king can be threatened by checks, if squares near
1059  * the king are controlled by the enemy (especially by promoted pieces), or
1060  * if there are no own generals near the king.
1061  *
1062  * The following must be true:
1063  * board[sq] == king, c1 == color[sq], c2 == otherside[c1]
1064  */
1065
1066 #define SCORETHREAT \
1067 { \
1068     if (color[u] != c2) \
1069     { \
1070         if ((atk1[u] == 0) || ((atk2[u] & CNT_MASK) != 0)) \
1071         { \
1072             ++cnt; \
1073         } \
1074         else \
1075         { \
1076             s += (ds = -fv1[CTRLK]); \
1077         } \
1078     } \
1079 }
1080
1081
1082
1083
1084 inline short
1085 KingScan(short sq)
1086 {
1087     short cnt;
1088
1089 #ifdef SAVE_NEXTPOS
1090     short d;
1091 #else
1092     unsigned char  *ppos, *pdir;
1093 #endif
1094
1095     short s;
1096     short u, ptyp;
1097     short ok, ds;
1098
1099     /* Penalties, if a king can be threatened by checks. */
1100
1101     s = 0;
1102     cnt = 0;
1103
1104     {
1105         short p;
1106
1107         for (p = pawn; p < king; p++)
1108         {
1109             if (HasPiece[c2][p] || Captured[c2][p])
1110             {
1111                 short ptyp;
1112
1113                 /* if a c1 piece can reach u from sq,
1114                  * then a c2 piece can reach sq from u.
1115                  * That means, each u is a square, from which a
1116                  * piece of type p and color c2 threats square sq.
1117                  */
1118                 ptyp = ptype[c1][p];
1119
1120 #ifdef SAVE_NEXTPOS
1121                 u = first_direction(ptyp, &d, sq);
1122 #else
1123                 ppos = (*nextpos[ptyp])[sq];
1124                 pdir = (*nextdir[ptyp])[sq];
1125                 u = ppos[sq];
1126 #endif
1127
1128                 do
1129                 {
1130                     /* If a p piece can reach (controls or can drop to)
1131                      * square u, then score threat.
1132                      */
1133
1134                     if (atk2[u] & control[p])
1135                         SCORETHREAT
1136                     else if ((Captured[c2][p] && color[u]) == neutral)
1137                         SCORETHREAT
1138
1139 #ifdef SAVE_NEXTPOS
1140                     u = ((color[u] == neutral)
1141                          ? next_position(ptyp, &d, sq, u)
1142                          : next_direction(ptyp, &d, sq));
1143 #else
1144                     u = ((color[u] == neutral) ? ppos[u] : pdir[u]);
1145 #endif
1146                 }
1147                 while (u != sq);
1148             }
1149         }
1150     }
1151
1152     s += (ds = fv1[KSFTY] * KTHRT[cnt] / 16);
1153
1154     /* Penalties, if squares near king are controlled by enemy. */
1155
1156     cnt = 0;
1157     ok = false;
1158     ptyp = ptype[c1][king];
1159
1160 #ifdef SAVE_NEXTPOS
1161     u = first_direction(ptyp, &d, sq);
1162 #else
1163     pdir = (*nextpos[ptyp])[sq];
1164     u = pdir[sq];
1165 #endif
1166
1167     do
1168     {
1169         if (!ok && color[u] == c1)
1170         {
1171             short ptype_piece = ptype[black][board[u]];
1172
1173             if ((ptype_piece == ptype_silver) || (ptype_piece == ptype_gold))
1174                 ok = true;
1175         }
1176
1177         if (atk2[u] > atk1[u])
1178         {
1179             ++cnt;
1180
1181             if (atk2[u] & ctlSG)
1182             {
1183                 s += (ds = -fv1[KSFTY] / 2);
1184             }
1185         }
1186
1187 #ifdef SAVE_NEXTPOS
1188         u = next_direction(ptyp, &d, sq);
1189 #else
1190         u = pdir[u];
1191 #endif
1192     }
1193     while (u != sq);
1194
1195     if (!ok || (cnt > 1))
1196     {
1197         if (cnt > 1)
1198             s += (ds = -fv1[KSFTY]/2);
1199         else
1200             s += (ds = -fv1[KSFTY]);
1201     }
1202
1203     return s;
1204 }
1205
1206
1207 static short checked_trapped;
1208
1209
1210 /*
1211  * See if the attacked piece has unattacked squares to move to. The following
1212  * must be true: c1 == color[sq] c2 == otherside[c1]
1213  */
1214
1215 inline int
1216 trapped(short sq)
1217 {
1218     short u, ptyp;
1219 #ifdef SAVE_NEXTPOS
1220     short d;
1221 #else
1222     unsigned char *ppos, *pdir;
1223 #endif
1224     short piece;
1225     short rvalue;
1226
1227     piece  = board[sq];
1228     rvalue = (*value)[stage][piece];
1229     ptyp   = ptype[c1][piece];
1230
1231 #ifdef SAVE_NEXTPOS
1232     u = first_direction(ptyp, &d, sq);
1233 #else
1234     ppos = (*nextpos[ptyp])[sq];
1235     pdir = (*nextdir[ptyp])[sq];
1236     u = ppos[sq];
1237 #endif
1238
1239     do
1240     {
1241         if (color[u] != c1)
1242         {
1243             if ((atk2[u] == 0) || ((*value)[stage][board[u]] >= rvalue))
1244                 return false;
1245         }
1246
1247 #ifdef SAVE_NEXTPOS
1248         u = ((color[u] == neutral)
1249              ? next_position(ptyp, &d, sq, u)
1250              : next_direction(ptyp, &d, sq));
1251 #else
1252         u = ((color[u] == neutral) ? ppos[u] : pdir[u]);
1253 #endif
1254     }
1255     while (u != sq);
1256
1257     checked_trapped = true;
1258
1259     return true;
1260 }
1261
1262
1263
1264 static int
1265 AttackedPieceValue(short sq, short side)
1266 {
1267     short s, ds;
1268
1269     s = 0;
1270
1271         ds = -fv1[HUNGP] * 2;
1272     hung[c1]++;
1273     shung[sq]++;
1274
1275     if (trapped(sq))
1276     {
1277         hung[c1]  += 2;
1278         shung[sq] += 2;
1279     }
1280
1281     return s;
1282 }
1283
1284
1285
1286 static inline int
1287 OpenFileValue(short sq, short hopn, short hopnx)
1288 {
1289     short s = 0, fyle;
1290
1291     if (PC1[fyle = column(sq)] == 0)
1292     {
1293         s += hopn;
1294     }
1295
1296     if (PC2[fyle] == 0)
1297     {
1298         s += hopnx;
1299     }
1300
1301     return s;
1302 }
1303
1304
1305
1306
1307 /* Distance bonus */
1308
1309 #define PromotionZoneDistanceValue(sq, dd) \
1310 if ((ds = fv1[PROMD])) \
1311 { \
1312     s += (ds = ds * PromotionZoneDistanceBonus[crow(c1, sq)] * dd); \
1313 }
1314
1315 #define OwnKingDistanceValue(sq, dd, maxd) \
1316 if ((ds = fv1[KINGOD]) && ((ad = Kdist[c1][sq]) <= maxd)) \
1317 { \
1318     s += (ds = ds * OwnKingDistanceBonus[ad] * dd); \
1319 }
1320
1321 #define EnemyKingDistanceValue(sq, dd, maxd) \
1322 if ((ds = fv1[KINGOD]) && ((ad = Kdist[c2][sq]) <= maxd)) \
1323 { \
1324     s += (ds = ds * EnemyKingDistanceBonus[ad] * dd); \
1325 }
1326
1327
1328
1329
1330
1331 /*
1332  * Calculate the positional value for a pawn on 'sq'.
1333  */
1334
1335 static inline int
1336 PawnValue(short sq, short side)
1337 {
1338     short s = 0;
1339     short ds;
1340     short ccol = ccolumn(c1, sq);
1341
1342     PromotionZoneDistanceValue(sq, 3);
1343
1344     /* pawn mobility */
1345     if (color[(c1 == black) ? (sq + NO_COLS) : (sq - NO_COLS)] == neutral)
1346     {
1347         s += (ds = MBLTY[pawn]);
1348     }
1349
1350     if ((a1 & ((ctlR | ctlRp) | ctlL)))
1351     {
1352         s += (ds = fv1[ATTACKED]);
1353     }
1354
1355     if (in_opening_stage)
1356     {
1357         if (crow(c1, sq) == 2) /* pawn on 3d rank */
1358         {
1359             if (board[(c1 == black) ?
1360                       (sq + 3*NO_COLS) : (sq - 3*NO_COLS)] == pawn)
1361             {
1362                 /* opposing pawn has been moved (even column == (sq & 1)) */
1363
1364                 short m;
1365
1366                 switch (ccol)
1367                 {
1368                 case 0:
1369                 case 8:
1370                     m = (side == c1) ? 3 : 5;
1371                     break;
1372
1373                 case 4:
1374                     m = (side == c1) ? 2 : 3;
1375                     break;
1376
1377                 default:
1378                     m = (side == c1) ? 1 : 2;
1379                     break;
1380                 }
1381
1382                 s += (ds = -m * MBLTY[pawn]);
1383             }
1384         }
1385
1386         if ((GameType[c1] == STATIC_ROOK) && (sq == csquare(c1, 43)))
1387         {
1388             if ((atk2[csquare(c1, 52)] & CNT_MASK) < 2)
1389             {
1390                 s += (ds = fv1[ATTACKED]);
1391             }
1392         }
1393
1394         if ((GameType[c2] == STATIC_ROOK) && (ccol == 1))
1395         {
1396             if (sq == csquare(c1, 28))
1397             {
1398                 s += (ds = -fv1[ATTACKED]);
1399             }
1400
1401             if (((atk1[csquare(c1, 19)] & CNT_MASK) < 2)
1402                 && ((atk1[csquare(c1, 28)] & CNT_MASK) < 2))
1403             {
1404                 s += (ds = -2 * fv1[ATTACKED]);
1405             }
1406         }
1407     }
1408
1409     return s;
1410 }
1411
1412
1413 #ifndef MINISHOGI
1414 /*
1415  * Calculate the positional value for a lance on 'sq'.
1416  */
1417
1418 static inline int
1419 LanceValue(short sq, short side)
1420 {
1421     short s = 0, ds, ad;
1422
1423     OwnKingDistanceValue(sq, 1, 2);
1424
1425     OpenFileValue(sq, -fv1[HOPN], fv1[HOPN]);
1426
1427     if (!checked_trapped && (crow(c1, sq) > 2))
1428     {
1429         if (in_opening_stage || trapped(sq))
1430         {
1431             s += (ds = -3 * fv1[ATTACKED]);
1432         }
1433         else
1434         {
1435             s += (ds = -2 * fv1[ATTACKED]);
1436         }
1437     }
1438
1439     return s;
1440 }
1441
1442
1443
1444 /*
1445  * Calculate the positional value for a knight on 'sq'.
1446  */
1447
1448 static inline int
1449 KnightValue(short sq, short side)
1450 {
1451     short s = 0, ad;
1452     short ds, checked_trapped = false;
1453     short c = column(sq);
1454
1455     PromotionZoneDistanceValue(sq, 1);
1456     OwnKingDistanceValue(sq, 1, 2);
1457
1458     if (!checked_trapped && (crow(c1, sq) > 2))
1459     {
1460         if (trapped(sq))
1461         {
1462             s += (ds = -4 * fv1[ATTACKED]);
1463         }
1464         else
1465         {
1466             s += (ds = -3 * fv1[ATTACKED]);
1467         }
1468     }
1469
1470     if ((c == 0) || (c == 8))
1471     {
1472         s += (ds = -fv1[ATTACKED]);
1473     }
1474
1475     return s;
1476 }
1477 #endif
1478
1479
1480
1481 /*
1482  * Calculate the positional value for a silver on 'sq'.
1483  */
1484
1485 static inline int
1486 SilverValue(short sq, short side)
1487 {
1488     short s= 0, ds, ad;
1489
1490     OwnKingDistanceValue(sq, 2, 3);
1491
1492     if ((Kdist[c1][sq] < 3)
1493         && (atk1[sq] & (control[gold] | control[silver])))
1494     {
1495         s += (ds = fv1[COHESION]);
1496     }
1497
1498     if (in_opening_stage)
1499     {
1500         if (GameType[c1] == STATIC_ROOK)
1501         {
1502             if (csquare(c1, sq) == 12)
1503             {
1504                 short csq;
1505
1506                 if ((board[csq = csquare(c1, 20)] == bishop)
1507                     && (color[csq] == c1))
1508                 {
1509                     s += (ds = -2 * fv1[OPENWRONG]);
1510                 }
1511             }
1512         }
1513     }
1514     else
1515     {
1516         EnemyKingDistanceValue(sq, 2, 3);
1517     }
1518
1519     return s;
1520 }
1521
1522
1523
1524 /*
1525  * Calculate the positional value for a gold on 'sq'.
1526  */
1527
1528 static inline int
1529 GoldValue(short sq, short side)
1530 {
1531     short s = 0, ds, ad;
1532
1533     OwnKingDistanceValue(sq, 2, 3);
1534
1535     if ((Kdist[c1][sq] < 3)
1536         && (atk1[sq] & (control[gold] | control[silver])))
1537     {
1538         s += (ds = fv1[COHESION]);
1539     }
1540
1541     if (in_opening_stage)
1542     {
1543         if ((GameType[c1] == STATIC_ROOK) && (GameType[c2] != STATIC_ROOK))
1544         {
1545             if (Mvboard[csquare(c1, 3)])
1546             {
1547                 s += (ds = -2 * fv1[OPENWRONG]);
1548             }
1549         }
1550     }
1551     else
1552     {
1553         EnemyKingDistanceValue(sq, 2, 3);
1554     }
1555
1556     return s;
1557 }
1558
1559
1560
1561 /*
1562  * Calculate the positional value for a bishop on 'sq'.
1563  */
1564
1565 static inline int
1566 BishopValue(short sq, short side)
1567 {
1568     short s = 0, ds, ad;
1569
1570     if (in_opening_stage)
1571     {
1572         if (GameType[c1] == RANGING_ROOK)
1573         {
1574             /* Bishops diagonal should not be open */
1575             if (!on_csquare(c1, pawn, 30))
1576             {
1577                 s += (ds = -fv1[OPENWRONG]);
1578             }
1579         }
1580         else if (GameType[c2] == RANGING_ROOK)
1581         {
1582             /* Bishops diagonal should be open */
1583             if ((csquare(c1, sq) == 10)
1584                 && (!empty_csquare(c1, 20) || !empty_csquare(c1, 30)))
1585             {
1586                 s += (ds = -fv1[OPENWRONG]);
1587             }
1588             else if ((csquare(c1, sq) == 20) && !empty_csquare(c1, 30))
1589             {
1590                 s += (ds = -fv1[OPENWRONG]);
1591             }
1592         }
1593     }
1594     else
1595     {
1596         EnemyKingDistanceValue(sq, 1, 3);
1597     }
1598
1599     return s;
1600 }
1601
1602
1603
1604 /*
1605  * Calculate the positional value for a rook on 'sq'.
1606  */
1607
1608 static inline int
1609 RookValue(short sq, short side)
1610 {
1611     short s = 0, ds, ad;
1612
1613     OpenFileValue(sq, 2 * fv1[HOPN], 4*fv1[HOPN]);
1614
1615     if (in_opening_stage)
1616     {
1617         short WRONG = fv1[OPENWRONG], OPOK = WRONG / 3;
1618
1619         if (GameType[c1] == STATIC_ROOK)
1620         {
1621             short c = ccolumn(c1, sq);
1622
1623             /* Bonus for rook on 8th file */
1624             if (c == 7)
1625             {
1626                  s += (ds = OPOK);
1627             }
1628
1629             /*
1630              * Bonus for rook on right side,
1631              * penalty for rook on left side
1632              */
1633
1634             c = 4 - c;
1635             ds = 0;
1636
1637             if (c < 0)
1638             {
1639                 s += (ds = c + c + OPOK);
1640             }
1641             else if (c >= 0)
1642             {
1643                 s += (ds = -c - c - WRONG);
1644             }
1645         }
1646         else if (GameType[c1] == RANGING_ROOK)
1647         {
1648             /* Bonus for rook on left side and
1649              * bishops diagonal closed, penalty otherwise. */
1650
1651             short c;
1652             c = 4 - ccolumn(c1, sq);
1653             ds = 0;
1654
1655             if (c >= 0)
1656             {
1657                 /* Bishops diagonal should not be open. */
1658                 if (on_csquare(c1, pawn, 30))
1659                     s += (ds = OPOK);
1660                 else
1661                     s += (ds = -c - c - WRONG);
1662             }
1663             else if (c < 0)
1664             {
1665                 s += (ds = -c - c - WRONG);
1666
1667                 /* Penalty for king not on initial square. */
1668                 if (!on_csquare(side, king, 4))
1669                 {
1670                     s  += -4 * WRONG;
1671                     ds += -4 * WRONG;
1672                 }
1673             }
1674         }
1675     }
1676     else
1677     {
1678         EnemyKingDistanceValue(sq, 1, 3);
1679     }
1680
1681     return s;
1682 }
1683
1684
1685
1686 /*
1687  * Calculate the positional value for a promoted pawn on 'sq'.
1688  */
1689
1690 static inline int
1691 PPawnValue(short sq, short side)
1692 {
1693     short s = 0, ds, ad;
1694
1695     EnemyKingDistanceValue(sq, 3, 10);
1696
1697     return s;
1698 }
1699
1700
1701
1702 #ifndef MINISHOGI
1703 /*
1704  * Calculate the positional value for a promoted lance on 'sq'.
1705  */
1706
1707 static inline int
1708 PLanceValue(short sq, short side)
1709 {
1710     short s = 0, ds, ad;
1711
1712     EnemyKingDistanceValue(sq, 3, 10);
1713
1714     return s;
1715 }
1716
1717
1718
1719 /*
1720  * Calculate the positional value for a promoted knight on 'sq'.
1721  */
1722
1723 static inline int
1724 PKnightValue(short sq, short side)
1725 {
1726     short s = 0, ds, ad;
1727
1728     EnemyKingDistanceValue(sq, 3, 10);
1729
1730     return s;
1731 }
1732 #endif
1733
1734
1735
1736 /*
1737  * Calculate the positional value for a promoted silver on 'sq'.
1738  */
1739
1740 static inline int
1741 PSilverValue(short sq, short side)
1742 {
1743     short s = 0, ds, ad;
1744
1745     EnemyKingDistanceValue(sq, 3, 10);
1746
1747     return s;
1748 }
1749
1750
1751
1752 /*
1753  * Calculate the positional value for a promoted bishop on 'sq'.
1754  */
1755
1756 static inline int
1757 PBishopValue(short sq, short side)
1758 {
1759     short s = 0, ds, ad;
1760
1761     EnemyKingDistanceValue(sq, 3, 4);
1762
1763     return s;
1764 }
1765
1766
1767
1768 /*
1769  * Calculate the positional value for a promoted rook on 'sq'.
1770  */
1771
1772 static inline int
1773 PRookValue(short sq, short side)
1774 {
1775     short s = 0, ds, ad;
1776
1777     EnemyKingDistanceValue(sq, 3, 4);
1778
1779     OpenFileValue(sq, 3 * fv1[HOPN], 2 * fv1[HOPN]);
1780
1781     return s;
1782 }
1783
1784
1785
1786 /*
1787  * Calculate the positional value for a king on 'sq'.
1788  */
1789
1790 static inline int
1791 KingValue(short sq, short side)
1792 {
1793     short s = 0, ds;
1794
1795     if (fv1[KSFTY] != 0)
1796         s += KingScan(sq);
1797
1798     if (in_opening_stage)
1799     {
1800         if ((GameType[c1] != UNKNOWN) && (ccolumn(c1, sq) == 4))
1801         {
1802             s += (ds = -fv1[OPENWRONG] / 3);
1803         }
1804         else if ((GameType[c1] == STATIC_ROOK) && on_right_side(c1, sq))
1805         {
1806             s += (ds = -fv1[OPENWRONG] / 2);
1807         }
1808         else if ((GameType[c1] == RANGING_ROOK) && on_left_side(c1, sq))
1809         {
1810             s += (ds = -fv1[OPENWRONG] / 2);
1811         }
1812     }
1813
1814     /* CHECKME: is this correct? */
1815     if ((ds = fv1[HOPN]))
1816     {
1817         s += OpenFileValue(sq, -2 * ds, -4 * ds);
1818     }
1819
1820     return s;
1821 }
1822
1823
1824
1825 /*
1826  * Calculate the positional value for a piece on 'sq'.
1827  */
1828
1829 static inline int
1830 PieceValue(short sq, short side)
1831 {
1832     short s, piece, ds;
1833     short mob;
1834
1835     piece = board[sq];
1836
1837     if (piece == no_piece)
1838         return 0;
1839
1840     s = (*Mpiece[piece])[c1][sq];
1841
1842     checked_trapped = false;
1843
1844     if (sweep[piece])
1845     {
1846         /* pin/x-ray attack and mobility for sweeping pieces */
1847         s += (ds = BRLscan(sq, &mob));
1848
1849         if ((piece == bishop) || (piece == pbishop))
1850             s += (ds = BMBLTY[mob] * fv1[MOBILITY] / 100);
1851         else if ((piece == rook) || (piece == prook))
1852             s += (ds = RMBLTY[mob] * fv1[MOBILITY] / 100);
1853 #ifndef MINISHOGI
1854         else
1855             s += (ds = LMBLTY[mob] * fv1[MOBILITY] / 100);
1856 #endif
1857     }
1858     else
1859     {
1860         /* mobility for non-sweeping pieces */
1861     }
1862
1863     a2 = atk2[sq];
1864     a1 = atk1[sq];
1865
1866     if (a2 > 0)
1867     {
1868         /* opponent attacks piece */
1869         if (a1 == 0)
1870         {
1871             /* undefended piece */
1872             s += AttackedPieceValue(sq, side);
1873         }
1874         else
1875         {
1876             /* defended piece */
1877             short attack_value = value_of_weakest_attacker(a2);
1878             short piece_value = (*value)[stage][piece];
1879
1880             if (attack_value < piece_value)
1881             {
1882                 /* attacked by a weaker piece */
1883                 s += AttackedPieceValue(sq, side) / 2;
1884             }
1885             else if (abs(attack_value - piece_value) < 10)
1886             {
1887                 /* opponent has the option to exchange equal pieces */
1888                 s += (ds = -fv1[ATTACKED]);
1889             }
1890         }
1891     }
1892
1893     if (piece != king)
1894     {
1895
1896         if (a1 > 0)
1897         {
1898             /* piece is defended */
1899             s += (ds = (a1 & CNT_MASK) * fv1[PROTECT]);
1900         }
1901
1902         if (sseed[sq])
1903         {
1904             s += (ds = fv1[SEED]);
1905         }
1906
1907         if (sloose[sq])
1908         {
1909             s += (ds = -fv1[LOOSE]);
1910         }
1911
1912         if (starget[c1][sq])
1913         {
1914             if (sweep[piece])
1915             {
1916                 s -= (ds = -fv1[ATTACKED]/2);
1917             }
1918             else if (piece == pawn)
1919             {
1920                 s += (ds = fv1[ATTACKED]);
1921             }
1922         }
1923
1924         if (starget[c2][sq])
1925         {
1926             if (piece != pawn)
1927             {
1928                 s -= (ds = -fv1[ATTACKED] / 3);
1929             }
1930             else
1931             {
1932                 s += (ds = fv1[ATTACKED]);
1933             }
1934         }
1935
1936         if (Kdist[c1][sq] == 1)
1937         {
1938             s += (ds = fv1[KSFTY]);
1939         }
1940     }
1941
1942     switch (piece)
1943     {
1944     case pawn:
1945         s += PawnValue(sq, side);
1946         break;
1947
1948 #ifndef MINISHOGI
1949     case lance:
1950         s += LanceValue(sq, side);
1951         break;
1952
1953     case knight:
1954         s += KnightValue(sq, side);
1955         break;
1956 #endif
1957
1958     case silver:
1959         s += SilverValue(sq, side);
1960         break;
1961
1962     case gold:
1963         s += GoldValue(sq, side);
1964         break;
1965
1966     case bishop:
1967         s += BishopValue(sq, side);
1968         break;
1969
1970     case rook:
1971         s += RookValue(sq, side);
1972         break;
1973
1974     case king:
1975         s += KingValue(sq, side);
1976         break;
1977
1978     case ppawn:
1979         s += PPawnValue(sq, side);
1980         break;
1981
1982 #ifndef MINISHOGI
1983     case plance:
1984         s += PLanceValue(sq, side);
1985         break;
1986
1987     case pknight:
1988         s += PKnightValue(sq, side);
1989         break;
1990 #endif
1991
1992     case psilver:
1993         s += PSilverValue(sq, side);
1994         break;
1995
1996     case pbishop:
1997         s += PBishopValue(sq, side);
1998         break;
1999
2000     case prook:
2001         s += PRookValue(sq, side);
2002         break;
2003     }
2004
2005     return s;
2006 }
2007
2008
2009
2010 /*
2011  * Score distance to pattern regarding the game type which side plays.
2012  */
2013
2014 short
2015 ScorePatternDistance(short c1)
2016 {
2017     short ds, s = 0;
2018     small_short *fv1 = fvalue[c1];
2019     short os = 0;
2020
2021     if ((MAXCDIST > 0) && (fv1[PCASTLE] != 0)
2022         && ((os = castle_opening_sequence[c1]) >= 0))
2023     {
2024         ds = board_to_pattern_distance(c1, os, MAXCDIST, GameCnt);
2025
2026         if (ds != 0)
2027         {
2028             s += (ds *= fv1[PCASTLE]);
2029         }
2030     }
2031
2032     if ((MAXADIST > 0) && (fv1[PATTACK] != 0)
2033         && ((os = attack_opening_sequence[c1]) >= 0))
2034     {
2035         ds = board_to_pattern_distance(c1, os, MAXADIST, GameCnt);
2036
2037         if (ds != 0)
2038         {
2039             s += (ds *= fv1[PATTACK]);
2040         }
2041     }
2042
2043     return s;
2044 }
2045
2046
2047
2048
2049 /*
2050  * Determine castle and attack pattern which should be reached next.
2051  * Only patterns are considered, which have not been reached yet.
2052  */
2053
2054 static void
2055 UpdatePatterns(short side, short GameCnt)
2056 {
2057     char s[12];
2058     short xside = side ^ 1;
2059     short os;
2060     short j, k, n = 0;
2061
2062     strcpy(s, "CASTLE_?_?");
2063     s[7] = GameType[side];
2064     s[9] = GameType[xside];
2065     castle_opening_sequence[side] = os
2066         = locate_opening_sequence(side, s, GameCnt);
2067
2068     if (flag.post && (os != END_OF_SEQUENCES))
2069     {
2070         for (j = 0; j < MAX_SEQUENCE; j++)
2071         {
2072             for (k = OpeningSequence[os].first_pattern[j];
2073                  k != END_OF_PATTERNS;
2074                  k = Pattern[k].next_pattern)
2075             {
2076                 if (Pattern[k].distance[side] >= 0)
2077                     n++;
2078             }
2079         }
2080     }
2081
2082     if (os != END_OF_SEQUENCES)
2083         update_advance_bonus(side, os);
2084
2085     strcpy(s, "ATTACK_?_?");
2086     s[7] = GameType[side];
2087     s[9] = GameType[xside];
2088     attack_opening_sequence[side] = os
2089         = locate_opening_sequence(side, s, GameCnt);
2090
2091     if (flag.post && (os != END_OF_SEQUENCES))
2092     {
2093         for (j = 0; j < MAX_SEQUENCE; j++)
2094         {
2095             for (k = OpeningSequence[os].first_pattern[j];
2096                  k != END_OF_PATTERNS;
2097                  k = Pattern[k].next_pattern)
2098             {
2099                 if (Pattern[k].distance[side] >= 0)
2100                     n++;
2101             }
2102         }
2103     }
2104
2105     if (flag.post)
2106         ShowPatternCount(side, n);
2107
2108     if (os != END_OF_SEQUENCES)
2109         update_advance_bonus(side, os);
2110 }
2111
2112
2113
2114 static void
2115 ScoreCaptures(void)
2116 {
2117     short ds, col, n, m, piece;
2118
2119     if ((n = Captured[c1][pawn]))
2120     {
2121         ds = m = 0;
2122
2123         for (col = 0; col < NO_COLS; col++)
2124         {
2125             if (!PC1[col])
2126             {
2127                 m++;
2128                 ds += fv1[PWNDROP];
2129             }
2130         }
2131
2132         /* FIXME! another great obfuscated line... */
2133         pscore[c1] += (ds *= ((n > 2) ? 3 : n));
2134     }
2135
2136     if ((m = seed[c1]))
2137     {
2138         for (piece = pawn+1, n = 0; piece <= rook; piece++)
2139         {
2140             if (Captured[c1][piece])
2141                 n++;
2142         }
2143
2144         pscore[c1] += (ds = m * fv1[DFFDROP]);
2145     }
2146
2147     for (piece = pawn, n = 0; piece <= rook; piece++)
2148     {
2149         if (Captured[c1][piece])
2150         {
2151             switch (piece)
2152             {
2153             case bishop:
2154                 ds = BMBLTY[MAX_BMBLTY - 1];
2155                 break;
2156
2157             case rook:
2158                 ds = RMBLTY[MAX_RMBLTY - 1];
2159                 break;
2160
2161 #ifndef MINISHOGI
2162             case lance:
2163                 ds = LMBLTY[MAX_LMBLTY - 1];
2164                 break;
2165 #endif
2166
2167             default:
2168                 ds = MBLTY[piece];
2169             }
2170
2171             pscore[c1] += ds;
2172
2173             if (!Captured[c2][piece])
2174                 n += relative_value[piece];
2175         }
2176     }
2177
2178     if (n)
2179     {
2180         pscore[c1] += (ds = -n * fv1[OPPDROP] / 2);
2181     }
2182 }
2183
2184
2185
2186
2187
2188 /*
2189  * Perform normal static evaluation of board position. A score is generated
2190  * for each piece and these are summed to get a score for each side.
2191  */
2192
2193 short
2194 ScorePosition(short side)
2195 {
2196     short score;
2197     short sq, i, xside;
2198     short s;
2199     short ds;
2200
2201     xside = side ^ 1;
2202
2203     UpdateWeights(side);
2204
2205     hung[black] = hung[white] = pscore[black] = pscore[white] = 0;
2206
2207     array_zero(shung, sizeof(shung));
2208
2209 #ifdef CACHE
2210     if (!(use_etable && ProbeEETable(side, &s)))
2211     {
2212 #endif
2213         for (c1 = black; c1 <= white; c1++)
2214         {
2215             c2 = c1 ^ 1;
2216
2217             /* atk1 is array of attacks on squares by my side */
2218             atk1 = attack[c1];
2219
2220             /* atk2 is array of attacks on squares by other side */
2221             atk2 = attack[c2];
2222
2223             /* same for PC1 and PC2 */
2224             PC1 = PawnCnt[c1];
2225             PC2 = PawnCnt[c2];
2226
2227             /* same for fv1 and fv2 */
2228             fv1 = fvalue[c1];
2229
2230             for (i = PieceCnt[c1]; i >= 0; i--)
2231             {
2232                 sq = PieceList[c1][i];
2233
2234 #if defined SAVE_SVALUE
2235                 pscore[c1] += PieceValue(sq, side);
2236 #else
2237                 pscore[c1] += (svalue[sq] = PieceValue(sq, side));
2238 #endif
2239             }
2240
2241             ScoreCaptures();
2242         }
2243
2244 #ifndef MINISHOGI
2245 # define BLACKHOME_START  0
2246 # define BLACKHOME_END   26
2247 # define MIDDLEROW_START 36
2248 # define MIDDLEROW_END   44
2249 # define WHITEHOME_START 54
2250 # define WHITEHOME_END   80
2251 #else
2252 # define BLACKHOME_START  0
2253 # define BLACKHOME_END    4
2254 # define MIDDLEROW_START 10
2255 # define MIDDLEROW_END   14
2256 # define WHITEHOME_START 19
2257 # define WHITEHOME_END   24
2258 #endif
2259         for (c1 = black, c2 = white; c1 <= white; c1++, c2--)
2260         {
2261             short n;
2262
2263             fv1 = fvalue[c1];
2264
2265             /* Score fifth rank */
2266             for (sq = MIDDLEROW_START, n = 0; sq <= MIDDLEROW_END; sq++)
2267             {
2268                 if ((color[sq] == c1) || (attack[c1][sq] != 0))
2269                     n++;
2270             }
2271
2272             if (n != 0)
2273             {
2274                 pscore[c1] += (ds = n * fv1[CNTRL5TH]);
2275             }
2276
2277             /* Score holes */
2278             for (sq = ((c1 == black) ? BLACKHOME_START : WHITEHOME_START), n = 0;
2279                  sq <= ((c1 == black) ? BLACKHOME_END : WHITEHOME_END);
2280                  sq++)
2281             {
2282                 if (board[sq] == no_piece && attack[c1][sq] == 0)
2283                     n++;
2284             }
2285
2286             if (n != 0)
2287             {
2288                 pscore[c1] += (ds = -n * fv1[HOLES]);
2289             }
2290
2291             if (hung[c1] > 1)
2292             {
2293                 pscore[c1] += (ds = -fv1[HUNGX]);
2294             }
2295
2296             /* Score opening features and
2297              * castle/attack pattern distances */
2298
2299             if (in_opening_stage)
2300             {
2301                 pscore[c1] += (ds = ScoreKingOpeningFeatures());
2302                 pscore[c1] += (ds = ScorePatternDistance(c1));
2303             }
2304         }
2305
2306         score = mtl[side] - mtl[xside]
2307             + pscore[side] - pscore[xside] + 10;
2308
2309 #ifdef CACHE
2310         if (use_etable && PUTVAR)
2311             PutInEETable(side, score);
2312 #endif
2313
2314         return score;
2315 #ifdef CACHE /* CHECKME: this looks bad */
2316     }
2317
2318     return s;
2319 #endif
2320 }
2321
2322
2323
2324 /*
2325  * Try to determine the game type of "side".
2326  */
2327
2328 inline static void
2329 GuessGameType(short side_to_move)
2330 {
2331     short side, gt;
2332     short StaticRook[2]  = { 0, 0 };
2333     short RangingRook[2] = { 0, 0 };
2334
2335     for (side = black; side <= white; side++)
2336     {
2337         /* computer should not change its mind */
2338
2339         extern int bookflag;
2340
2341         gt = GameType[side];
2342
2343         if (!bookflag && (side == side_to_move))
2344         {
2345             if (gt == STATIC_ROOK)
2346                 StaticRook[side] += 4;
2347             else if (gt == RANGING_ROOK)
2348                 RangingRook[side] += 4;
2349         }
2350
2351         /* static rook conditions */
2352
2353         if (on_column(side, rook, 7))
2354             StaticRook[side] += 3;
2355
2356         if (on_csquare(side, pawn, 34))
2357             StaticRook[side] += 6;
2358         else if (on_csquare(side, pawn, 43))
2359             StaticRook[side] += 4;
2360         else if (!on_column(side, pawn, 7))
2361             StaticRook[side] += 5;
2362
2363         if (empty_csquare(side, 5) || empty_csquare(side, 6))
2364             StaticRook[side] += 2;
2365
2366         if (on_left_side(side, king))
2367             StaticRook[side] += 2;
2368
2369         /* ranging rook conditions */
2370
2371         if (on_left_side(side, rook))
2372             RangingRook[side] += 5;
2373         else if (!on_column(side, rook, 7))
2374             RangingRook[side] += 3;
2375
2376         if (on_csquare(side, pawn, 25))
2377             RangingRook[side] += 1;
2378
2379         if (on_csquare(side, pawn, 30))
2380             RangingRook[side] += 1;
2381         else
2382             RangingRook[side] -= 2;
2383
2384         if (!on_right_side(side, rook))
2385             RangingRook[side] += 4;
2386
2387         if (on_right_side(side, king))
2388             RangingRook[side] += 4;
2389
2390         if (on_csquare(side, bishop, 20))
2391         {
2392             if (on_csquare(side, silver, 11)
2393                 || on_csquare(side, silver, 12)
2394                 || on_csquare(side, silver, 21))
2395             {
2396                 RangingRook[side] += 3;
2397             }
2398         }
2399
2400         if ((StaticRook[side] > 5) || (RangingRook[side] > 5))
2401         {
2402             GameType[side] = (StaticRook[side] > RangingRook[side])
2403                 ? STATIC_ROOK : RANGING_ROOK;
2404         }
2405         else
2406         {
2407             GameType[side] = UNKNOWN;
2408         }
2409     }
2410
2411     if ((GameType[black] == UNKNOWN) || (GameType[white] == UNKNOWN))
2412     {
2413         for (side = black; side <= white; side++)
2414         {
2415             if ((side == computer) && (GameType[side] == UNKNOWN))
2416             {
2417                 /*
2418                  * Game type is UNKNOWN.
2419                  * Make a decision what type of game to play.
2420                  * To make computer games more interesting, make a
2421                  * random decision.
2422                  */
2423
2424                 if (!on_csquare(side, pawn, 25))
2425                 {
2426                     /* Play static rook if rook pawn has been pushed! */
2427                     GameType[side] = STATIC_ROOK;
2428                 }
2429                 else
2430                 {
2431                     unsigned int random = urand() % 100;
2432                     short d = StaticRook[side] - RangingRook[side];
2433
2434                     switch (GameType[side ^ 1])
2435                     {
2436                     case STATIC_ROOK:
2437                         if (random < 35 + d)
2438                             GameType[side] = STATIC_ROOK;
2439                         else if (random < 95)
2440                             GameType[side] = RANGING_ROOK;
2441                         break;
2442
2443                     case RANGING_ROOK:
2444                         if (random < 75 + d)
2445                             GameType[side] = STATIC_ROOK;
2446                         else if (random < 95)
2447                             GameType[side] = RANGING_ROOK;
2448                         break;
2449
2450                     default:
2451                         if (random < 33 + d)
2452                             GameType[side] = STATIC_ROOK;
2453                         else if (random < 66)
2454                             GameType[side] = RANGING_ROOK;
2455                     }
2456                 }
2457             }
2458         }
2459     }
2460 }
2461
2462
2463
2464
2465 static void
2466 DetermineGameType(short side_to_move)
2467 {
2468     short side;
2469
2470     GuessGameType(side_to_move);
2471
2472     array_zero(Mpawn,   sizeof(Mpawn));
2473 #ifndef MINISHOGI
2474     array_zero(Mlance,  sizeof(Mlance));
2475     array_zero(Mknight, sizeof(Mknight));
2476 #endif
2477     array_zero(Msilver, sizeof(Msilver));
2478     array_zero(Mgold,   sizeof(Mgold));
2479     array_zero(Mbishop, sizeof(Mbishop));
2480     array_zero(Mrook,   sizeof(Mrook));
2481     array_zero(Mking,   sizeof(Mking));
2482
2483     if (in_opening_stage)
2484     {
2485         for (side = black; side <= white; side++)
2486             UpdatePatterns(side, GameCnt);
2487     }
2488     else
2489     {
2490         ShowPatternCount(black, -1);
2491         ShowPatternCount(white, -1);
2492     }
2493 }
2494
2495
2496
2497 /*
2498  * This is done one time before the search is started. Set up arrays
2499  * Mwpawn, Mbpawn, Mknight, Mbishop, Mking which are used in the SqValue()
2500  * function to determine the positional value of each piece.
2501  */
2502
2503 void
2504 ExaminePosition(short side)
2505 {
2506     short c1, piece, sq, i, bsq, wsq;
2507
2508     /* Build enemy king distance tables. */
2509
2510     for (sq = 0, bsq = BlackKing, wsq = WhiteKing; sq < NO_SQUARES; sq++)
2511     {
2512         Kdist[black][sq] = distance(sq, bsq);
2513         Kdist[white][sq] = distance(sq, wsq);
2514     }
2515
2516     threats(black);
2517     threats(white);
2518
2519     ExamineSquares();
2520
2521     DetermineGameType(side);
2522     DetermineStage(side);
2523
2524     UpdateWeights(side);
2525
2526     array_zero(HasPiece, sizeof(HasPiece));
2527
2528     for (c1 = black; c1 <= white; c1++)
2529     {
2530         for (i = PieceCnt[c1]; i >= 0; i--)
2531         {
2532             ++HasPiece[c1][piece = board[sq = PieceList[c1][i]]];
2533         }
2534     }
2535 }
2536
2537
2538
2539 void
2540 DetermineStage(short side)
2541 {
2542     short xside = side ^ 1, ds, db1, c1, c2, feature;
2543
2544     /* Determine initial stage */
2545
2546     balance[side] = balance[xside] = 50;
2547
2548     if ((GameType[side] == STATIC_ROOK)
2549         && (GameType[xside] == STATIC_ROOK))
2550     {
2551         if (GameCnt < 40)
2552             stage = 0;
2553         else if (GameCnt < 60)
2554             stage = 15;
2555         else if (GameCnt < 80)
2556             stage = 25;
2557         else
2558             stage = 30;
2559     }
2560     else if ((GameType[side] == RANGING_ROOK)
2561              || (GameType[xside] == RANGING_ROOK))
2562     {
2563         if (GameCnt < 30)
2564             stage = 0;
2565         else if (GameCnt < 50)
2566             stage = 15;
2567         else if (GameCnt < 70)
2568             stage = 25;
2569         else
2570             stage = 30;
2571     }
2572     else
2573     {
2574         if (GameCnt < 35)
2575             stage = 0;
2576         else if (GameCnt < 55)
2577             stage = 15;
2578         else if (GameCnt < 75)
2579             stage = 25;
2580         else
2581             stage = 30;
2582     }
2583
2584 #ifndef MINISHOGI
2585     /* Update stage depending on board features and attack balance value */
2586
2587     if (abs(ds = (mtl[side] - mtl[xside]))
2588         > (db1 = (*value)[stage][lance]))
2589     {
2590         db1 = abs(4 * ds / db1);
2591
2592         if (ds < 0)
2593             balance[side] += db1;
2594         else if (ds > 0)
2595             balance[xside] += db1;
2596
2597         stage += (ds = db1);
2598     }
2599 #endif
2600
2601     for (c1 = black, c2 = white; c1 <= white; c1++, c2--)
2602     {
2603         if ((ds = seed[c1]) > 2)
2604         {
2605             balance[c1] += (db1 = ds * 2);
2606             balance[c2] -= db1;
2607
2608             if (stage < 30)
2609                 stage = 30;
2610
2611             stage += ds;
2612         }
2613
2614         if ((db1 = hung[c1]) > 2)
2615         {
2616             balance[c1] -= (db1 *= 2);
2617             balance[c2] += db1;
2618         }
2619
2620         if ((db1 = loose[c1]) > 4)
2621         {
2622             balance[c1] -= (db1 /= 2);
2623             balance[c2] += db1;
2624             stage += (ds = 1);
2625         }
2626
2627         if ((ds = hole[c1]))
2628         {
2629             balance[c1] -= (db1 = ds);
2630             balance[c2] += db1;
2631             stage += (ds /= 2);
2632         }
2633
2634         if ((db1 = target[c1]) > 3)
2635         {
2636             balance[c1] += (db1 /= 3);
2637             balance[c2] -= db1;
2638             stage += (ds = db1 / 4);
2639         }
2640
2641         stage += (ds = captured[c1] / 2);
2642
2643         if ((db1 = captured[c1]) > 4)
2644         {
2645             balance[c1] += (db1 /= 2);
2646             stage += (ds = 3);
2647         }
2648
2649         if ((db1 = dcaptured[c1]) > 3)
2650         {
2651             balance[c1] += db1;
2652             stage += (ds = 3);
2653         }
2654
2655         if (balance[c1] > 99)
2656             balance[c1] = 99;
2657         else if (balance[c1] < 0)
2658             balance[c1] = 0;
2659     }
2660
2661     if (stage > 99)
2662         stage = 99;
2663     else if (stage < 0)
2664         stage = 0;
2665
2666     if (flag.post)
2667         ShowStage();
2668
2669     /* Determine stage dependant weights */
2670
2671     ADVNCM[pawn]   = 1; /* advanced pawn bonus increment   */
2672 #ifndef MINISHOGI
2673     ADVNCM[lance]  = 1;
2674     ADVNCM[knight] = 1;
2675 #endif
2676     ADVNCM[silver] = 1; /* advanced silver bonus increment */
2677     ADVNCM[gold]   = 1; /* advanced gold bonus increment   */
2678     ADVNCM[bishop] = 1;
2679     ADVNCM[rook]   = 1;
2680     ADVNCM[king]   = 1; /* advanced king bonus increment   */
2681
2682     MAXCDIST = (stage < 33) ? (33 - stage) / 4 : 0;
2683     MAXADIST = (stage < 30) ? (30 - stage) / 4 : 0;
2684
2685     for (c1 = black; c1 <= white; c1++)
2686     {
2687         for (feature = 0; feature < NO_FEATURES; feature++)
2688         {
2689             fvalue[c1][feature] =
2690                 ((((*fscore)[stage][feature][0] * (99 - balance[c1])) + 50)
2691                  / 100)
2692                 + ((((*fscore)[stage][feature][1] * balance[c1]) + 50)
2693                    / 100);
2694         }
2695     }
2696 }
2697
2698
2699
2700 void
2701 UpdateWeights(short stage)
2702 {
2703 }
2704
2705
2706
2707 /*
2708  * Compute stage dependent relative material values assuming
2709  * linearity between the main stages:
2710  *
2711  *   minstage < stage < maxstage =>
2712  *          stage - minstage        value - minvalue
2713  *         -------------------  =  -------------------
2714  *         maxstage - minstage     maxvalue - minvalue
2715  */
2716
2717
2718 static short
2719 linear_piece_value(short piece, short stage, short i, short j)
2720 {
2721     short minvalue, maxvalue, minstage, maxstage;
2722
2723     minstage = ispvalue[0][i];
2724     maxstage = ispvalue[0][j];
2725     minvalue = ispvalue[piece][i];
2726     maxvalue = ispvalue[piece][j];
2727
2728     /* FIXME: set a variable then return it, puh-leeze! */
2729     return ((stage - minstage) * (maxvalue - minvalue)
2730             / (maxstage - minstage)) + minvalue;
2731 }
2732
2733
2734
2735 static short
2736 linear_feature_value(short feature, short stage, short i, short j)
2737 {
2738     short minvalue, maxvalue, minstage, maxstage;
2739
2740     minstage = ispvalue[0][i];
2741     maxstage = ispvalue[0][j];
2742     minvalue = weight[feature][i];
2743     maxvalue = weight[feature][j];
2744
2745     /* FIXME: set a variable then return it, puh-leeze! */
2746     return ((stage - minstage) * (maxvalue - minvalue)
2747             / (maxstage - minstage)) + minvalue;
2748 }
2749
2750
2751 /*
2752  * matweight = percentage_of_max_value * max_value(stage) / 100
2753  * max_value(0) = MAX_VALUE; max_value(100) = MIN_VALUE
2754  *  => max_value(stage) = a * stage + b; b = MAX_VALUE,
2755  *     a = (MIN_VALUE - MAX_VALUE)/100
2756  */
2757
2758 #define MIN_VALUE 300
2759 #define MAX_VALUE 1000
2760
2761 #define max_value(stage) \
2762 ((long)(MIN_VALUE - MAX_VALUE) * stage + (long)100 * MAX_VALUE)
2763 #define matweight(value, stage) \
2764 ((long)max_value(stage) * value / 10000)
2765
2766
2767
2768 void
2769 Initialize_eval(void)
2770 {
2771     short stage, piece, feature, i;
2772
2773     for (stage = 0; stage < NO_STAGES; stage++)
2774     {
2775         for (i = 0; i < MAIN_STAGES; i++)
2776         {
2777             if (stage == ispvalue[0][i])
2778             {
2779                 for (piece = 0; piece < NO_PIECES; piece++)
2780                 {
2781                     (*value)[stage][piece] =
2782                         matweight(ispvalue[piece][i], stage);
2783                 }
2784
2785                 for (feature = 0; feature < NO_FEATURES; feature++)
2786                 {
2787                     (*fscore)[stage][feature][0] =
2788                         (weight[feature][i]
2789                          * weight[feature][MAIN_STAGES] + 50) / 100;
2790
2791                     (*fscore)[stage][feature][1] =
2792                         (weight[feature][i]
2793                          * weight[feature][MAIN_STAGES + 1] + 50) / 100;
2794                 }
2795
2796                 break;
2797             }
2798
2799             if (stage < ispvalue[0][i + 1])
2800             {
2801                 for (piece = 0; piece < NO_PIECES; piece++)
2802                 {
2803                     (*value)[stage][piece] =
2804                         matweight(
2805                             linear_piece_value(piece, stage, i, i + 1),
2806                             stage);
2807                 }
2808
2809                 for (feature = 0; feature < NO_FEATURES; feature++)
2810                 {
2811                     (*fscore)[stage][feature][0] =
2812                         (linear_feature_value(feature, stage, i, i + 1)
2813                          * weight[feature][MAIN_STAGES] + 50) / 100;
2814
2815                     (*fscore)[stage][feature][1] =
2816                         (linear_feature_value(feature, stage, i, i + 1)
2817                          * weight[feature][MAIN_STAGES + 1] + 50) / 100;
2818                 }
2819
2820                 break;
2821             }
2822         }
2823     }
2824 }
2825