Implement setboard command
[hachu.git] / hachu.c
diff --git a/hachu.c b/hachu.c
index dcf4842..28f58f1 100644 (file)
--- a/hachu.c
+++ b/hachu.c
@@ -91,11 +91,11 @@ typedef struct {
   char fireMask;\r
 } UndoInfo;\r
 \r
-char *array;\r
+char *array, fenArray[4000], *reason;\r
 int bWidth, bHeight, bsize, zone, currentVariant;\r
 int stm, xstm, hashKeyH, hashKeyL, framePtr, msp, nonCapts, rootEval, retMSP, retFirst, retDep, pvPtr, level, cnt50, chuFlag=1, tenFlag, mobilityScore;\r
-int nodes, startTime, tlim1, tlim2;\r
-Move retMove, moveStack[10000], path[100], repStack[300], pv[1000];\r
+int nodes, startTime, tlim1, tlim2, repCnt, comp;\r
+Move retMove, moveStack[10000], path[100], repStack[300], pv[1000], repeatMove[300];\r
 \r
 #define X 36 /* slider              */\r
 #define R 37 /* jump capture        */\r
@@ -675,6 +675,8 @@ SetUp(char *array, int var)
   for(i=0; ; i++) {\r
 //printf("next rank: %s\n", array);\r
     for(j = BW*i; ; j++) {\r
+      int pflag=0;\r
+      if(*array == '+') pflag++, array++;\r
       c = name[0] = *array++;\r
       if(!c) goto eos;\r
       if(c == '.') continue;\r
@@ -687,9 +689,10 @@ SetUp(char *array, int var)
        if(name[1]) name[1] += 'A' - 'a';\r
       } else color = WHITE;\r
       p1 = LookUp(name, var);\r
+      if(pflag && p1->promoted) p1 = LookUp(p1->promoted, var); // use promoted piece instead\r
       n = AddPiece(color, p1);\r
       p[n].pos = j;\r
-      if(p1->promoted[0]) {\r
+      if(p1->promoted[0] && !pflag) {\r
        p2 = LookUp(p1->promoted, var);\r
         m = AddPiece(color, p2);\r
        if(m <= n) n += 2;\r
@@ -789,7 +792,8 @@ Init (int var)
 \r
   // piece-square tables\r
   for(i=0; i<BH; i++) for(j=0; j<BH; j++) {\r
-    int s = BW*i + j, d = BH*(BH-2) - (2*i - BH + 1)*(2*i - BH + 1) - (2*j - BH + 1)*(2*j - BH + 1);\r
+    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
+    PST[s] = 0;\r
     PST[BH+s] = d/4 - (i == 0 || i == BH-1 ? 15 : 0) - (j == 0 || j == BH-1 ? 15 : 0);\r
     PST[BH*BW+s] = d/6;\r
     PST[BH*BW+BH+s] = d/12;\r
@@ -798,6 +802,20 @@ Init (int var)
   p[EDGE].qval = 5; // tenjiku jump-capturer sentinel\r
 }\r
 \r
+int\r
+PSTest ()\r
+{\r
+  int r, f, score, tot=0;\r
+  for(r=0; r<BH; r++) for(f=0; f<BH; f++) {\r
+    int s = BW*r+f;\r
+    int piece = board[s];\r
+    if(!piece) continue;\r
+    score = p[piece].value + PST[p[piece].pst + s];\r
+    if(piece & 1) tot += score; else tot -= score;\r
+  }\r
+  return tot;\r
+}\r
+\r
 int flag;\r
 \r
 inline int\r
@@ -1356,7 +1374,7 @@ void
 GenCapts(int sqr, int victimValue)\r
 { // generate all moves that capture the piece on the given square\r
   int i, range, att = attacks[2*sqr + stm];\r
-//printf("GenCapts(%d,%d)\n",sqr,victimValue);\r
+//printf("GenCapts(%c%d,%d) %08x\n",sqr%BW+'a',sqr/BW,victimValue,att);\r
   if(!att) return; // no attackers at all!\r
   for(i=0; i<8; i++) {               // try all rays\r
     int x, v, jumper, jcapt=0;\r
@@ -1460,7 +1478,7 @@ GenCapts(int sqr, int victimValue)
     for(i=0; i<8; i++) {    // scan all knight jumps to locate source\r
       int x = sqr - nStep[i], attacker = board[x];\r
       if(attacker == EMPTY || (attacker & TYPE) != stm) continue;\r
-      if(p[attacker].range[i] <= N && p[attacker].range[i] >= S && p[attacker].range[i] != J) { // has Knight jump in our direction\r
+      if(p[attacker].range[i] <= L && p[attacker].range[i] >= S || p[attacker].range[i] == N) { // has Knight jump in our direction\r
        NewCapture(x, sqr + victimValue, p[attacker].promoFlag);   // plain jump (as in N)\r
        if(p[attacker].range[i] < N) { // Lion power; generate double captures over two possible intermediates\r
          int v = kStep[i]; // leftish path\r
@@ -1522,7 +1540,7 @@ if(PATH) /*pboard(board),pmap(attacks, BLACK),*/printf("search(%d) {%d,%d} eval=
   nodes++;\r
   pv[pvPtr++] = 0; // start empty PV, directly behind PV of parent\r
 \r
-  firstMove = curMove = sorted = msp += 20; // leave 20 empty slots in front of move list\r
+  firstMove = curMove = sorted = msp += 50; // leave 50 empty slots in front of move list\r
   tb.fireMask = phase = 0; iterDep=1; replyDep = (depth < 1 ? depth : 1) - 1;\r
   do {\r
 if(flag && depth>= 0) printf("iter %d:%d\n", depth,iterDep),fflush(stdout);\r
@@ -1540,7 +1558,7 @@ if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase
 #if 0\r
            if(curEval >= beta) {\r
              stm ^= WHITE;\r
-             score = -Search(-beta, -iterAlpha, difEval, depth-3, promoSuppress & SQUARE, ABSENT);\r
+             score = -Search(-beta, -iterAlpha, -difEval, depth-3, promoSuppress & SQUARE, ABSENT);\r
              stm ^= WHITE;\r
              if(score >= beta) { msp = oldMSP; retDep += 3; return score + (score < curEval); }\r
            }\r
@@ -1611,7 +1629,7 @@ if(PATH) printf("%d:%2d:%2d msp=%d\n",level,depth,iterDep,msp);
       // MOVE EXTRACTION\r
     extractMove:\r
 if(flag & depth >= 0) printf("%2d:%d extract %d/%d\n", depth, iterDep, curMove, msp);\r
-      if(curMove < sorted) {\r
+      if(curMove > sorted) {\r
        move = moveStack[sorted=j=curMove];\r
        for(i=curMove+1; i<msp; i++)\r
          if(moveStack[i] > move) move = moveStack[j=i]; // search move with highest priority\r
@@ -1630,7 +1648,8 @@ if(flag & depth >= 0) printf("%2d:%d found %d/%d %08x %s\n", depth, iterDep, cur
 if(flag & depth >= 0) printf("%2d:%d made %d/%d %s\n", depth, iterDep, curMove, msp, MoveToText(moveStack[curMove], 0));\r
       for(i=2; i<=cnt50; i+=2) if(repStack[level-i+200] == hashKeyH) {\r
        moveStack[curMove] = 0; // erase forbidden move\r
-       score = -INF; goto repetition;\r
+       if(!level) repeatMove[repCnt++] = move & 0xFFFFFF; // remember outlawed move\r
+       score = -INF; moveStack[curMove] = 0; goto repetition;\r
       }\r
       repStack[level+200] = hashKeyH;\r
 \r
@@ -1649,7 +1668,11 @@ MapFromScratch(attacks); // for as long as incremental update does not work.
          if(promoSuppress & PROMOTE) score = -INF; // non-Lion captures Lion after opponent did same\r
          defer |= PROMOTE;                         // if we started, flag  he cannot do it in reply\r
        }\r
-        if(score == -INF) { moveStack[curMove] = 0; goto abortMove; } // zap illegal moves\r
+        if(score == -INF) {\r
+          if(level == 1) repeatMove[repCnt++] = move & 0xFFFFFF | (p[tb.piece].value == 10*LVAL ? 3<<24 : 1 << 24);\r
+          moveStack[curMove] = 0; // zap illegal moves\r
+          goto abortMove;\r
+        }\r
       }\r
 #if 1\r
       score = -Search(-beta, -iterAlpha, -difEval - tb.booty, replyDep, promoSuppress & ~PROMOTE, defer);\r
@@ -1702,7 +1725,9 @@ if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curM
         int i;   // WB thinking output\r
        printf("%d %d %d %d", iterDep, bestScore, (GetTickCount() - startTime)/10, nodes);\r
        for(i=0; pv[i]; i++) printf(" %s", MoveToText(pv[i], 0));\r
-       printf("\n"); fflush(stdout);\r
+        if(iterDep == 1) printf(" { root eval = %4.2f dif = %4.2f; abs = %4.2f}", curEval/100., difEval/100., PSTest()/100.);\r
+       printf("\n");\r
+        fflush(stdout);\r
       }\r
       if(GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish\r
     }\r
@@ -1841,13 +1866,55 @@ UnMake2 (MOVE move)
   sup2 = sup1; sup1 = sup0;\r
 }\r
 \r
+char fenNames[] = "RV....DKDEFL..DHGB......SMLNKN..FK....BT..VM..PH...."; // pairs of char\r
+char fenPromo[] = "WLDHSMSECPB R HFDE....WHFB..LNG ..DKVMFS..FO..FK...."; // pairs of char\r
+\r
+char *\r
+Convert (char *fen)\r
+{\r
+  char *p = fenArray, *q, *rows[36], tmp[4000];\r
+  int n=0;\r
+  printf("# convert FEN '%s'\n", fen);\r
+  q = strchr(fen, ' '); if(q) *q = 0; q = fen;\r
+  do { rows[n++] = q; q = strchr(q, '/'); if(!q) break; *q++ = 0; } while(1);\r
+  *tmp = 0;\r
+  while(--n >= 0) { strcat(tmp, rows[n]); if(n) strcat(tmp, "/"); }\r
+  fen = tmp;\r
+  printf("# flipped FEN '%s'\n", fen);\r
+  while(*fen) {\r
+    if(*fen == ' ') { *p = 0; break; }\r
+    if(n=atoi(fen)) fen++; // digits read\r
+    if(n > 9) fen++; // double digit\r
+    while(n-- > 0) *p++ = '.'; // expand to empty squares\r
+    if(isalpha(*fen)) {\r
+      char *table = fenNames;\r
+      n = *fen > 'Z' ? 'a' - 'A' : 0;\r
+      if(table[2* (*fen - 'A' - n)] == '.') *p++ = *fen; else {\r
+        *p++ = ':';\r
+        *p++ = table[2* (*fen - 'A' - n)] + n;\r
+        *p++ = table[2* (*fen - 'A' - n)+1] + n;\r
+      }\r
+    } else *p++ = *fen;\r
+    fen++;\r
+  }\r
+  printf("# converted FEN '%s'\n", fenArray);\r
+  return fenArray;\r
+}\r
+\r
 int\r
 Setup2 (char *fen)\r
 {\r
+  int stm = WHITE;\r
+  if(fen) {\r
+    char *q = strchr(fen, '\n');\r
+    if(q) *q = 0;\r
+    if(q = strchr(fen, ' ')) stm = (q[1] == 'b' ? BLACK : WHITE); // fen contains color field\r
+    if(strchr(fen, '.') || strchr(fen, ':')) array = fen; else array = Convert(fen);\r
+  }\r
   SetUp(array, currentVariant);\r
   sup0 = sup1 = sup2 = ABSENT;\r
-  rootEval = cnt50 = hashKeyH = hashKeyL = 0;\r
-  return WHITE;\r
+  rootEval = cnt50 = hashKeyH = hashKeyL = moveNr = 0;\r
+  return stm;\r
 }\r
 \r
 void\r
@@ -1912,7 +1979,7 @@ ParseMove (char *moveText)
   if(*moveText == '+') ret |= PROMOTE;\r
 printf("# suppress = %c%d\n", sup1%BW+'a', sup1/BW);\r
 MapFromScratch(attacks);\r
-  postThinking--;\r
+  postThinking--; repCnt = 0;\r
   Search(-INF-1, INF+1, 0, 1, sup1 & ~PROMOTE, sup2);\r
   postThinking++;\r
   for(i=retFirst; i<retMSP; i++) {\r
@@ -1932,8 +1999,17 @@ printf("# deferral of %d\n", deferred);
        if(!(flags & promoBoard[f])) moveStack[i] |= DEFER; // came from outside zone, so essential deferral\r
       }\r
     }\r
-    if(i >= retMSP)\r
-      for(i=retFirst; i<retMSP; i++) printf("# %d. %08x %08x %s\n", i-20, moveStack[i], ret, MoveToText(moveStack[i], 0));\r
+    if(i >= retMSP) {\r
+      for(i=retFirst; i<retMSP; i++) printf("# %d. %08x %08x %s\n", i-50, moveStack[i], ret, MoveToText(moveStack[i], 0));\r
+      reason = NULL;\r
+      for(i=0; i<repCnt; i++) {if((repeatMove[i] & 0xFFFFFF) == ret) {\r
+        if(repeatMove[i] & 1<<24) reason = (repeatMove[i] & 1<<25 ? "Distant capture of protected Lion" : "Counterstrike against Lion");\r
+        else reason = "Repeats earlier position";\r
+        break;\r
+      }\r
+ printf("# %d. %08x %08x %s\n", i, repeatMove[i], ret, MoveToText(repeatMove[i], 0));\r
+}\r
+    }\r
   }\r
   return (i >= retMSP ? INVALID : moveStack[i]);\r
 }\r
@@ -1949,7 +2025,7 @@ MapFromScratch(attacks);
 //pmap(attacks, WHITE);\r
 //pmap(attacks, BLACK);\r
 //flag=1;\r
-  postThinking--;\r
+  postThinking--; repCnt = 0;\r
   Search(-INF-1, INF+1, 0, 1, sup1 & ~PROMOTE, sup2);\r
   postThinking++;\r
 flag=0;\r
@@ -1998,15 +2074,17 @@ flag=0;
 int\r
 SearchBestMove (int stm, int timeLeft, int mps, int timeControl, int inc, int timePerMove, MOVE *move, MOVE *ponderMove)\r
 {\r
-  int score, targetTime, movesLeft = 50;\r
+  int score, targetTime, movesLeft = BW*BH/4 + 20;\r
   if(mps) movesLeft = mps - (moveNr>>1)%mps;\r
   targetTime = timeLeft*10 / (movesLeft + 2) + 1000 * inc;\r
+  if(moveNr < 30) targetTime *= 0.5 + moveNr/60.; // speedup in opening\r
   if(timePerMove > 0) targetTime = timeLeft * 5;\r
   startTime = GetTickCount();\r
   tlim1 = 0.2*targetTime;\r
   tlim2 = 1.9*targetTime;\r
   nodes = 0;\r
 MapFromScratch(attacks);\r
+  retMove = INVALID; repCnt = 0;\r
   score = Search(-INF-1, INF+1, rootEval, 20, sup1, sup2);\r
   *move = retMove;\r
   *ponderMove = INVALID;\r
@@ -2030,9 +2108,11 @@ printf("# setup done");fflush(stdout);
 \r
     void PrintResult(int stm, int score)\r
     {\r
-      if(score == 0) printf("1/2-1/2\n");\r
-      if(score > 0 && stm == WHITE || score < 0 && stm == BLACK) printf("1-0\n");\r
-      else printf("0-1\n");\r
+      char tail[100];\r
+      if(reason) sprintf(tail, " {%s}", reason); else *tail = 0;\r
+      if(score == 0) printf("1/2-1/2%s\n", tail);\r
+      if(score > 0 && stm == WHITE || score < 0 && stm == BLACK) printf("1-0%s\n", tail);\r
+      else printf("0-1%s\n", tail);\r
     }\r
 \r
     main()\r
@@ -2056,6 +2136,20 @@ printf("# setup done");fflush(stdout);
           score = SearchBestMove(stm, timeLeft, mps, timeControl, inc, timePerMove, &move, &ponderMove);\r
 \r
           if(move == INVALID) {         // game apparently ended\r
+            int kcapt = 0, xstm = stm ^ WHITE, king, k = p[king=royal[xstm]].pos;\r
+            if( k != ABSENT) { // test if King capture possible\r
+              if(attacks[2*k + stm]) {\r
+                if( p[king + 2].pos == ABSENT ) kcapt = 1; // we have an attack on his only King\r
+              }\r
+            } else { // he has no king! Test for attacks on Crown Prince\r
+              k = p[king + 2].pos;\r
+              if(attacks[2*k + stm]) kcapt = 1; // we have attack on Crown Prince\r
+            }\r
+            if(kcapt) { // print King capture before claiming\r
+              GenCapts(k, 0);\r
+              printf("move %s\n", MoveToText(moveStack[msp-1], 1));\r
+              reason = "king capture";\r
+            } else reason = "resign";\r
             engineSide = NONE;          // so stop playing\r
             PrintResult(stm, score);\r
           } else {\r
@@ -2135,7 +2229,10 @@ printf("var %d\n",i);
         if(!strcmp(command, "memory"))  { SetMemorySize(atoi(inBuf+7)); continue; }\r
         if(!strcmp(command, "ping"))    { printf("pong%s", inBuf+4); continue; }\r
     //  if(!strcmp(command, ""))        { sscanf(inBuf, " %d", &); continue; }\r
-        if(!strcmp(command, "new"))     { engineSide = BLACK; Init(V_CHESS); stm = Setup2(DEFAULT_FEN); maxDepth = MAXPLY; randomize = OFF; continue; }\r
+        if(!strcmp(command, "new"))     {\r
+          engineSide = BLACK; Init(V_CHESS); stm = Setup2(DEFAULT_FEN); maxDepth = MAXPLY; randomize = OFF; comp = 0;\r
+          continue;\r
+        }\r
         if(!strcmp(command, "setboard")){ engineSide = NONE;  stm = Setup2(inBuf+9); continue; }\r
         if(!strcmp(command, "easy"))    { ponder = OFF; continue; }\r
         if(!strcmp(command, "hard"))    { ponder = ON;  continue; }\r
@@ -2157,7 +2254,7 @@ printf("var %d\n",i);
         if(!strcmp(command, "l"))       { pplist(); continue; }\r
         // ignored commands:\r
         if(!strcmp(command, "xboard"))  { continue; }\r
-        if(!strcmp(command, "computer")){ continue; }\r
+        if(!strcmp(command, "computer")){ comp = 1; continue; }\r
         if(!strcmp(command, "name"))    { continue; }\r
         if(!strcmp(command, "ics"))     { continue; }\r
         if(!strcmp(command, "accepted")){ continue; }\r
@@ -2167,8 +2264,10 @@ printf("var %d\n",i);
         if(!strcmp(command, ""))  {  continue; }\r
         if(!strcmp(command, "usermove")){\r
           int move = ParseMove(inBuf+9);\r
-          if(move == INVALID) printf("Illegal move\n");\r
-          else {\r
+          if(move == INVALID) {\r
+            if(reason) printf("Illegal move {%s}\n", reason); else printf("%s\n", reason="Illegal move");\r
+            if(comp) PrintResult(stm, -INF); // against computer: claim\r
+          } else {\r
             stm = MakeMove2(stm, move);\r
             ponderMove = INVALID;\r
             gameMove[moveNr++] = move;  // remember game\r