X-Git-Url: http://winboard.nl/cgi-bin?a=blobdiff_plain;f=hachu.c;h=aa37ab3f44b6648e853fe784e1e3426c0a784385;hb=c40c2b9d2eb9abc3cd530a1ff96aaf0e6fc91643;hp=173aae96c176820fdc7247f3f9d60efc2424403b;hpb=6b60ddf69ce961d41a579a258444f653729e5c95;p=hachu.git diff --git a/hachu.c b/hachu.c index 173aae9..aa37ab3 100644 --- a/hachu.c +++ b/hachu.c @@ -11,21 +11,43 @@ // promotions by pieces with Lion power stepping in & out the zone in same turn // promotion on capture -#define VERSION "0.4beta" +#define VERSION "0.7beta" #define PATH level==0 || path[0] == 0xc4028 && (level==1 /*|| path[1] == 0x75967 && (level == 2 || path[2] == 0x3400b && (level == 3))*/) //define PATH 0 +#define XHASH +#define XKILLERS +#define XNULLMOVE + #include #include #include #include #include +#include #ifdef WIN32 # include + int InputWaiting() + { // checks for waiting input in pipe + static int pipe, init; + static HANDLE inp; + DWORD cnt; + + if(!init) inp = GetStdHandle(STD_INPUT_HANDLE); + if(!PeekNamedPipe(inp, NULL, 0, NULL, &cnt, NULL)) return 1; + return cnt; + } #else # include +# include + int InputWaiting() + { + int cnt; + if(ioctl(0, FIONREAD, &cnt)) return 1; + return cnt; + } int GetTickCount() // with thanks to Tord { struct timeval t; gettimeofday(&t, NULL); @@ -40,7 +62,7 @@ #define BSIZE BWMAX*BHMAX #define ZONE zone -#define ONE (currentVariant == V_SHO || currentVariant == V_CHESS || currentVariant == V_SHATRANJ) +#define ONE (currentVariant == V_SHO || currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK) #define BLACK 0 #define WHITE 1 @@ -79,6 +101,21 @@ void pboard(int *b); void pbytes(unsigned char *b); typedef struct { + int lock[5]; + int move[5]; + short int score[5]; + char depth[5]; + char flag[5]; + char age[4]; +} HashBucket; + +HashBucket *hashTable; +int hashMask; + +#define H_UPPER 2 +#define H_LOWER 1 + +typedef struct { char *name, *promoted; int value; signed char range[8]; @@ -92,10 +129,11 @@ typedef struct { } UndoInfo; char *array, fenArray[4000], *reason; -int bWidth, bHeight, bsize, zone, currentVariant, chuFlag, tenFlag, chessFlag; +int bWidth, bHeight, bsize, zone, currentVariant, chuFlag, tenFlag, chessFlag, repDraws; int stm, xstm, hashKeyH, hashKeyL, framePtr, msp, nonCapts, rootEval, retMSP, retFirst, retDep, pvPtr, level, cnt50, mobilityScore; -int nodes, startTime, tlim1, tlim2, repCnt, comp; -Move retMove, moveStack[10000], path[100], repStack[300], pv[1000], repeatMove[300]; +int nodes, startTime, tlim1, tlim2, tlim3, repCnt, comp, abortFlag; +Move ponderMove; +Move retMove, moveStack[10000], path[100], repStack[300], pv[1000], repeatMove[300], killer[100][2]; int maxDepth; // used by search @@ -327,12 +365,22 @@ PieceDesc chessPieces[] = { }; PieceDesc shatranjPieces[] = { - {"Q", "", 15, { 0,1,0,1,0,1,0,1 } }, + {"FK", "", 15, { 0,1,0,1,0,1,0,1 } }, {"R", "", 50, { X,0,X,0,X,0,X,0 } }, {"B", "", 9, { 0,J,0,J,0,J,0,J } }, {"N", "", 30, { N,N,N,N,N,N,N,N } }, {"K", "", 28, { 1,1,1,1,1,1,1,1 } }, - {"P", "Q", 8, { M,C,0,0,0,0,0,C } }, + {"P", "FK", 8, { M,C,0,0,0,0,0,C } }, + { NULL } // sentinel +}; + +PieceDesc makrukPieces[] = { + {"SM","", 15, { 0,1,0,1,0,1,0,1 } }, + {"R", "", 50, { X,0,X,0,X,0,X,0 } }, + {"S", "", 20, { 1,1,0,1,0,1,0,1 } }, // silver + {"N", "", 30, { N,N,N,N,N,N,N,N } }, + {"K", "", 28, { 1,1,1,1,1,1,1,1 } }, + {"P", "SM", 8, { M,C,0,0,0,0,0,C } }, { NULL } // sentinel }; @@ -349,7 +397,8 @@ char tenArray[] = "LN:FLICSGK:DEGSCI:FLNL/:RV.:CS:CS.:BT:KN:LN:FK:PH:BT.:CS:CS.: ":ss:vsb:dh:dk:wb:fi:fe:lh:fi:wb:dk:dhb:vs:ss/:rv.:cs:cs.:bt:ph:fk:ln:kn:bt.:cs:cs.:rv/ln:flicsg:dekgsci:flnl"; char shoArray[] = "LNSGKGSNL/.B..:DE..R./PPPPPPPPP/........./........./........./ppppppppp/.r..:de..b./lnsgkgsnl"; char chessArray[] = "RNBQKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbqkbnr"; -char shatArray[]= "RNBKQBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbkqbnr"; +char shatArray[]= "RNBK:FKBNR/PPPPPPPP/......../......../......../......../pppppppp/rnbk:fkbnr"; +char thaiArray[]= "RNSK:SMSNR/......../PPPPPPPP/......../......../pppppppp/......../rnsk:smsnr"; typedef struct { int boardWidth, boardFiles, boardRanks, zoneDepth, varNr; // board sizes @@ -357,7 +406,7 @@ typedef struct { char *array; // initial position } VariantDesc; -typedef enum { V_CHESS, V_SHO, V_CHU, V_DAI, V_TENJIKU, V_DADA, V_MAKA, V_TAI, V_KYOKU, V_SHATRANJ } Variant; +typedef enum { V_CHESS, V_SHO, V_CHU, V_DAI, V_TENJIKU, V_DADA, V_MAKA, V_TAI, V_KYOKU, V_SHATRANJ, V_MAKRUK } Variant; VariantDesc variants[] = { { 16, 8, 8, 1, V_CHESS, "normal", chessArray }, // FIDE @@ -366,6 +415,7 @@ VariantDesc variants[] = { { 30, 15, 15, 5, V_DAI, "dai", daiArray }, // Dai { 32, 16, 16, 5, V_TENJIKU, "tenjiku", tenArray }, // Tenjiku { 16, 8, 8, 1, V_SHATRANJ,"shatranj",shatArray}, // Shatranj + { 16, 8, 8, 3, V_MAKRUK, "makruk", thaiArray}, // Makruk // { 0, 0, 0, 0, 0 }, // sentinel { 34, 17, 17, 0, V_DADA, "dada", chuArray }, // Dai Dai @@ -549,6 +599,8 @@ LookUp (char *name, int var) return ListLookUp(name, chessPieces); case V_SHATRANJ: // Shatranj return ListLookUp(name, shatranjPieces); + case V_MAKRUK: // Makruk + return ListLookUp(name, makrukPieces); } return NULL; } @@ -676,7 +728,7 @@ AddPiece (int stm, PieceDesc *list) if(p[j].promo >= i) p[j].promo += 2; } if(royal[stm] >= i) royal[stm] += 2; - if(p[i].value == (currentVariant == V_SHO ? 410 : 280) ) royal[stm] = i; + if(p[i].value == (currentVariant == V_SHO ? 410 : 280) ) royal[stm] = i, p[i].pst = 0; p[i].qval = (currentVariant == V_TENJIKU ? list->ranking : 0); // jump-capture hierarchy return i; } @@ -685,11 +737,9 @@ void SetUp(char *array, int var) { int i, j, n, m, nr, color; - char c, *q, name[3]; + char c, *q, name[3], prince = 0; PieceDesc *p1, *p2; last[WHITE] = 1; last[BLACK] = 0; - if(var == V_CHESS || var == V_SHATRANJ) // add dummy Crown Princes - p[AddPiece(WHITE, LookUp("CP", V_CHU))].pos = p[AddPiece(BLACK, LookUp("CP", V_CHU))].pos = ABSENT; for(i=0; ; i++) { //printf("next rank: %s\n", array); for(j = BW*i; ; j++) { @@ -706,12 +756,14 @@ SetUp(char *array, int var) name[0] += 'A' - 'a'; if(name[1]) name[1] += 'A' - 'a'; } else color = WHITE; + if(!strcmp(name, "CP")) prince |= color+1; // remember if we added Crown Prince p1 = LookUp(name, var); if(!p1) printf("tellusererror Unknown piece '%s' in setup\n", name), exit(-1); if(pflag && p1->promoted) p1 = LookUp(p1->promoted, var); // use promoted piece instead n = AddPiece(color, p1); p[n].pos = j; if(p1->promoted[0] && !pflag) { + if(!strcmp(p1->promoted, "CP")) prince |= color+1; // remember if we added Crown Prince p2 = LookUp(p1->promoted, var); m = AddPiece(color, p2); if(m <= n) n += 2; @@ -727,6 +779,9 @@ SetUp(char *array, int var) } } eos: + // add dummy Crown Princes if not yet added + if(!(prince & WHITE+1)) p[AddPiece(WHITE, LookUp("CP", V_CHU))].pos = ABSENT; + if(!(prince & BLACK+1)) p[AddPiece(BLACK, LookUp("CP", V_CHU))].pos = ABSENT; for(i=0; i<8; i++) fireFlags[i] = 0; for(i=2, n=1; i<10; i++) if(p[i].value == 10*FVAL) { int x = p[i].pos; // mark all burn zones @@ -761,6 +816,7 @@ Init (int var) chuFlag = (currentVariant == V_CHU); tenFlag = (currentVariant == V_TENJIKU); chessFlag = (currentVariant == V_CHESS); + repDraws = (currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK); for(i= -1; i<9; i++) { // board steps in linear coordinates kStep[i] = STEP(direction[i&7].x, direction[i&7].y); // King @@ -1444,6 +1500,7 @@ GenCapts(int sqr, int victimValue) NewCapture(x, SPECIAL + 8*(i-1&7) + (i+1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag); v = kStep[i+1]; if((board[x+v] & TYPE) == xstm && board[x+v] > board[sqr]) + NewCapture(x, SPECIAL + 8*(i+1&7) + (i-1&7) + victimValue - SORTKEY(attacker), p[attacker].promoFlag); } } else { // primary victim on first ring @@ -1527,6 +1584,8 @@ FireSet (UndoInfo *tb) if(p[i].pos != ABSENT) tb->fireMask |= fireFlags[i-2]; } +void TerminationCheck(); + #define QSdepth 0 int @@ -1535,9 +1594,12 @@ Search (int alpha, int beta, int difEval, int depth, int oldPromo, int promoSupp int i, j, k, firstMove, oldMSP = msp, curMove, sorted, bad, phase, king, iterDep, replyDep, nextVictim, to, defer, dubious, bestMoveNr; int resDep; int myPV = pvPtr; - int score, bestScore, curEval, iterAlpha; + int score, bestScore, oldBest, curEval, iterAlpha; Move move, nullMove; UndoInfo tb; +#ifdef HASH + Move hashMove; int index, nr, hit; +#endif if(PATH) /*pboard(board),pmap(attacks, BLACK),*/printf("search(%d) {%d,%d} eval=%d, stm=%d\n",depth,alpha,beta,difEval,stm),fflush(stdout); xstm = stm ^ WHITE; //printf("map made\n");fflush(stdout); @@ -1557,12 +1619,30 @@ if(PATH) /*pboard(board),pmap(attacks, BLACK),*/printf("search(%d) {%d,%d} eval= alpha -= (alpha < curEval); beta -= (beta <= curEval); - nodes++; + if(!(nodes++ & 4095)) TerminationCheck(); pv[pvPtr++] = 0; // start empty PV, directly behind PV of parent + firstMove = curMove = sorted = msp += 50; // leave 50 empty slots in front of move list - tb.fireMask = phase = 0; iterDep=1; replyDep = (depth < 1 ? depth : 1) - 1; - do { + iterDep = 0; tb.fireMask = phase = 0; + +#ifdef HASH + index = hashKeyL & hashMask; nr = hashKeyL >> 30; hit = -1; + if(hashTable[index].lock[nr] == hashKeyH) hit = nr; else + if(hashTable[index].lock[4] == hashKeyH) hit = 4; + if(hit >= 0) { + bestScore = hashTable[index].score[hit]; + if((bestScore <= alpha || hashTable[index].flag[hit] & H_LOWER) && + (bestScore >= beta || hashTable[index].flag[hit] & H_UPPER) ) { + iterDep = hashTable[index].depth[hit]; + } + } else { // decide on replacement + if(depth >= hashTable[index].depth[nr]) hit = nr; else hit = 4; + } +#endif + + replyDep = (depth < 1 ? depth-1 : iterDep); + while(++iterDep <= depth || iterDep == 1) { if(flag && depth>= 0) printf("iter %d:%d\n", depth,iterDep),fflush(stdout); iterAlpha = alpha; bestScore = -INF; bestMoveNr = 0; resDep = 60; for(curMove = firstMove; ; curMove++) { // loop over moves @@ -1575,10 +1655,10 @@ if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase bestScore = curEval; resDep = QSdepth; if(bestScore >= beta || depth < -1) goto cutoff; } -#if 0 - if(curEval >= beta) { +#ifdef NULLMOVE + else if(curEval >= beta) { stm ^= WHITE; - score = -Search(-beta, -iterAlpha, -difEval, depth-3, promoSuppress & SQUARE, ABSENT); + score = -Search(-beta, 1-beta, -difEval, depth > 3 ? depth-3 : 0, promoSuppress & SQUARE, ABSENT); stm ^= WHITE; if(score >= beta) { msp = oldMSP; retDep += 3; return score + (score < curEval); } } @@ -1587,6 +1667,12 @@ if(flag && depth>= 0) printf("phase=%d: first/curr/last = %d / %d / %d\n", phase //if(PATH) printf("mask=%x\n",tb.fireMask),pbytes(fireBoard); phase = 1; case 1: // hash move +#ifdef HASH + if(hashMove) { + moveStack[sorted = msp++] = hashMove; + goto extractMove; + } +#endif phase = 2; case 2: // capture-gen init nextVictim = xstm; @@ -1631,6 +1717,14 @@ if(PATH) printf("%d:%2d:%2d msp=%d\n",level,depth,iterDep,msp); case 6: // non-captures nonCapts = msp; nullMove = GenNonCapts(oldPromo); +#ifdef KILLERS + { // swap killers to front + Move h = killer[level][0]; int j = curMove; + for(i=curMove; i= 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)); for(i=2; i<=cnt50; i+=2) if(repStack[level-i+200] == hashKeyH) { + if(repDraws) { score = 0; goto repetition; } moveStack[curMove] = 0; // erase forbidden move if(!level) repeatMove[repCnt++] = move & 0xFFFFFF; // remember outlawed move score = -INF; moveStack[curMove] = 0; goto repetition; @@ -1705,6 +1800,11 @@ level--; repetition: UnMake(&tb); xstm = stm; stm ^= WHITE; + if(abortFlag > 0) { // unwind search +printf("# abort (%d) @ %d\n", abortFlag, level); + if(curMove == firstMove) bestScore = oldBest, bestMoveNr = firstMove; // none searched yet + goto leave; + } #if 1 if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curMove, moveStack[curMove], MoveToText(moveStack[curMove], 0), score, bestScore); @@ -1725,7 +1825,12 @@ if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curM } bestMoveNr = firstMove; if(score >= beta) { // beta cutoff - // update killer +#ifdef KILLERS + if(iterDep == depth && move != killer[level][0]) { + // update killer + killer[level][1] = killer[level][0]; killer[level][0] = move; + } +#endif resDep = retDep; goto cutoff; } @@ -1749,10 +1854,22 @@ if(PATH) printf("%d:%2d:%d %3d %6x %-10s %6d %6d\n", level, depth, iterDep, curM printf("\n"); fflush(stdout); } - if(GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish +printf("# s=%d t=%d 1=%d 3=%d f=%d\n",startTime,GetTickCount(),tlim1,tlim3,abortFlag); + if(!(abortFlag & 1) && GetTickCount() - startTime > tlim1) break; // do not start iteration we can (most likely) not finish } replyDep = iterDep; - } while(++iterDep <= depth); // next depth +#ifdef HASH + // hash store + hashTable[index].lock[hit] = hashKeyH; + hashTable[index].depth[hit] = iterDep; + hashTable[index].flag[hit] = (bestScore < beta) * H_UPPER; + if(bestScore > alpha) { + hashTable[index].flag[hit] |= H_LOWER; + hashTable[index].move[hit] = bestMoveNr ? moveStack[bestMoveNr] : 0; + } else hashTable[index].move[hit] = 0; +#endif + } // next depth +leave: retMSP = msp; retFirst = firstMove; msp = oldMSP; // pop move list @@ -1852,7 +1969,7 @@ typedef Move MOVE; void SetMemorySize(int n); // if n is different from last time, resize all tables to make memory usage below n MB char *MoveToText(MOVE move, int m); // converts the move from your internal format to text like e2e2, e1g1, a7a8q. MOVE ParseMove(char *moveText); // converts a long-algebraic text move to your internal move format - int SearchBestMove(int stm, int timeLeft, int mps, int timeControl, int inc, int timePerMove, MOVE *move, MOVE *ponderMove); + int SearchBestMove(MOVE *move, MOVE *ponderMove); void PonderUntilInput(int stm); // Search current position for stm, deepening forever until there is input. UndoInfo undoInfo; @@ -1907,7 +2024,7 @@ Convert (char *fen) if(isalpha(*fen)) { char *table = fenNames; n = *fen > 'Z' ? 'a' - 'A' : 0; - if((currentVariant == V_CHESS || currentVariant == V_SHATRANJ) && *fen - 'A' - n == 'N' // In Chess N is Knight, not Lion + if((currentVariant == V_CHESS || currentVariant == V_SHATRANJ || currentVariant == V_MAKRUK) && *fen - n == 'N' // In Chess N is Knight, not Lion || table[2* (*fen - 'A' - n)] == '.') *p++ = *fen; else { *p++ = ':'; *p++ = table[2* (*fen - 'A' - n)] + n; @@ -1939,6 +2056,19 @@ Setup2 (char *fen) void SetMemorySize (int n) { +#ifdef HASH + static HashBucket *realHash; + static int oldSize; + int m = 1; + intptr_t l; + if(n != oldSize) { + if(oldSize) free(realHash); + while(m*sizeof(HashBucket) <= n*512) m <<= 1; + m *= 1024; hashMask = m - 1; + realHash = calloc(m + 1, sizeof(HashBucket)); + l = (intptr_t) realHash; hashTable = (HashBucket*) (l & ~63); // align with cache line + } +#endif } char * @@ -1946,6 +2076,7 @@ MoveToText (MOVE move, int multiLine) { static char buf[50]; int f = move>>SQLEN & SQUARE, g = f, t = move & SQUARE; + char *promoChar = ""; if(f == t) { sprintf(buf, "@@@@"); return buf; } // null-move notation in WB protocol buf[0] = '\0'; if(t >= SPECIAL) { // kludgy! Print as side effect non-standard WB command to remove victims from double-capture (breaks hint command!) @@ -1961,7 +2092,8 @@ MoveToText (MOVE move, int multiLine) } t = g + toList[t - SPECIAL]; } - sprintf(buf+strlen(buf), "%c%d%c%d%s", f%BW+'a', f/BW+ONE, t%BW+'a', t/BW+ONE, move & PROMOTE ? "+" : ""); + if(move & PROMOTE) promoChar = currentVariant == V_MAKRUK ? "m" : repDraws ? "q" : "+"; + sprintf(buf+strlen(buf), "%c%d%c%d%s", f%BW+'a', f/BW+ONE, t%BW+'a', t/BW+ONE, promoChar); return buf; } @@ -1975,6 +2107,21 @@ ReadSquare (char *p, int *sqr) return 2 + (r + ONE > 9); } +int listStart, listEnd; +char boardCopy[BSIZE]; + +void +ListMoves () +{ // create move list on move stack + int i; + for(i=0; i< BSIZE; i++) boardCopy[i] = !!board[i]; +MapFromScratch(attacks); + postThinking--; repCnt = 0; tlim1 = tlim2 = tlim3 = 1e8; abortFlag = msp = 0; + Search(-INF-1, INF+1, 0, 1, sup1 & ~PROMOTE, sup2); + postThinking++; + listStart = retFirst; listEnd = msp = retMSP; +} + MOVE ParseMove (char *moveText) { @@ -1995,20 +2142,17 @@ ParseMove (char *moveText) t2 = SPECIAL + 8*i + j; } ret = f<> SQLEN & SQUARE)) break; // any null move matches @@@@ if((moveStack[i] & (PROMOTE | DEFER-1)) == ret) break; if((moveStack[i] & DEFER-1) == ret) deferred = i; // promoted version of entered non-promotion is legal } -printf("# moveNr = %d in {%d,%d}\n", i, retFirst, retMSP); - if(i>=retMSP) { // no exact match +printf("# moveNr = %d in {%d,%d}\n", i, listStart, listEnd); + if(i>=listEnd) { // no exact match if(deferred) { // but maybe non-sensical deferral int flags = p[board[f]].promoFlag; printf("# deferral of %d\n", deferred); @@ -2019,8 +2163,8 @@ printf("# deferral of %d\n", deferred); if(!(flags & promoBoard[f])) moveStack[i] |= DEFER; // came from outside zone, so essential deferral } } - if(i >= retMSP) { - for(i=retFirst; i= listEnd) { + for(i=listStart; i= retMSP ? INVALID : moveStack[i]); + return (i >= listEnd ? INVALID : moveStack[i]); } void @@ -2041,32 +2185,25 @@ Highlight(char *coords) char b[BSIZE], buf[2000], *q; for(i=0; i>SQLEN & SQUARE)) { int t = moveStack[i] & SQUARE; if(t >= SPECIAL) continue; - b[t] = (board[t] == EMPTY ? 'Y' : 'R'); cnt++; + b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++; } } if(!cnt) { // no moves from given square if(sqr != lastPut) return; // refrain from sending empty FEN // we lifted a piece for second leg of move - for(i=retFirst; i>SQLEN & SQUARE)) { int e, t = moveStack[i] & SQUARE; if(t < SPECIAL) continue; // only special moves e = lastLift + epList[t - SPECIAL]; // decode t = lastLift + toList[t - SPECIAL]; if(e != sqr) continue; - b[t] = (board[t] == EMPTY ? 'Y' : 'R'); cnt++; + b[t] = (!boardCopy[t] ? 'Y' : 'R'); cnt++; } } if(!cnt) return; @@ -2091,31 +2228,46 @@ flag=0; printf("highlight %s\n", buf); } -int -SearchBestMove (int stm, int timeLeft, int mps, int timeControl, int inc, int timePerMove, MOVE *move, MOVE *ponderMove) +int timeLeft; // timeleft on engine's clock +int mps, timeControl, inc, timePerMove; // time-control parameters, to be used by Search +char inBuf[8000], command[80], ponderMoveText[20]; + +void +SetSearchTimes (int timeLeft) { - int score, targetTime, movesLeft = BW*BH/4 + 20; + int targetTime, movesLeft = BW*BH/4 + 20; if(mps) movesLeft = mps - (moveNr>>1)%mps; - targetTime = timeLeft*10 / (movesLeft + 2) + 1000 * inc; + targetTime = (timeLeft - 1000*inc) / (movesLeft + 2) + 1000 * inc; if(moveNr < 30) targetTime *= 0.5 + moveNr/60.; // speedup in opening - if(timePerMove > 0) targetTime = timeLeft * 5; - startTime = GetTickCount(); + if(timePerMove > 0) targetTime = 0.5*timeLeft, movesLeft = 1; tlim1 = 0.2*targetTime; tlim2 = 1.9*targetTime; + tlim3 = 5*timeLeft / (movesLeft + 4.1); +} + +int +SearchBestMove (MOVE *move, MOVE *ponderMove) +{ + int score; + startTime = GetTickCount(); nodes = 0; MapFromScratch(attacks); retMove = INVALID; repCnt = 0; score = Search(-INF-1, INF+1, rootEval, maxDepth, sup1, sup2); *move = retMove; - *ponderMove = INVALID; + *ponderMove = pv[1]; return score; } + void PonderUntilInput (int stm) { +MapFromScratch(attacks); + repCnt = 0; abortFlag = -1; + Search(-INF-1, INF+1, rootEval, maxDepth, sup1, sup2); } - + int TakeBack(int n) { // reset the game and then replay it to the desired point int last, stm; @@ -2135,25 +2287,59 @@ printf("# setup done");fflush(stdout); else printf("0-1%s\n", tail); } + void GetLine(int root) + { + int i, c; + while(1) { + // wait for input, and read it until we have collected a complete line + for(i = 0; (inBuf[i] = c = getchar()) != '\n'; i++) if(c == EOF || i>7997) exit(0); + inBuf[i+1] = 0; + + // extract the first word + sscanf(inBuf, "%s", command); +printf("# in (mode = %d,%d): %s\n", root, abortFlag, command); + if(!strcmp(command, "otim")) { continue; } // do not start pondering after receiving time commands, as move will follow immediately + if(!strcmp(command, "time")) { sscanf(inBuf, "time %d", &timeLeft); continue; } + if(!strcmp(command, "put")) { ReadSquare(inBuf+4, &lastPut); continue; } // ditto + if(!strcmp(command, ".")) { inBuf[0] = 0; return; } // ignore for now + if(!strcmp(command, "lift")) { inBuf[0] = 0; Highlight(inBuf+5); return; } // treat here + abortFlag = 1; + return; + } + } + + void + TerminationCheck() + { + if(abortFlag < 0) { // check for input + if(InputWaiting()) GetLine(0); // read & examine input command + } else { // check for time + if(GetTickCount() - startTime > tlim3) abortFlag = 2; + } + } + main() { int engineSide=NONE; // side played by engine - int timeLeft; // timeleft on engine's clock - int mps, timeControl, inc, timePerMove; // time-control parameters, to be used by Search - MOVE move, ponderMove; - int i, score; - char inBuf[8000], command[80]; + MOVE move; + int i, score, curVarNr; Init(V_CHU); // Chu + listEnd = 1; while(1) { // infinite loop fflush(stdout); // make sure everything is printed before we do something that might take time + *inBuf = 0; + + if(listEnd == 0) ListMoves(); // always maintain a list of legal moves in root position + abortFlag = 0; if(stm == engineSide) { // if it is the engine's turn to move, set it thinking, and let it move pboard(board); - score = SearchBestMove(stm, timeLeft, mps, timeControl, inc, timePerMove, &move, &ponderMove); + SetSearchTimes(10*timeLeft); + score = SearchBestMove(&move, &ponderMove); if(move == INVALID) { // game apparently ended int kcapt = 0, xstm = stm ^ WHITE, king, k = p[king=royal[xstm]].pos; @@ -2176,6 +2362,8 @@ pboard(board); stm = MakeMove2(stm, move); // assumes MakeMove returns new side to move gameMove[moveNr++] = move; // remember game printf("move %s\n", MoveToText(move, 1)); + listEnd = 0; + continue; } } @@ -2195,22 +2383,14 @@ pboard(board); } } - noPonder: - // wait for input, and read it until we have collected a complete line - for(i = 0; (inBuf[i] = getchar()) != '\n'; i++); - inBuf[i+1] = 0; - - // extract the first word - sscanf(inBuf, "%s", command); -printf("in: %s\n", command); + fflush(stdout); // make sure everything is printed before we do something that might take time + if(!*inBuf) GetLine(1); // takes care of time and otim commands // recognize the command,and execute it if(!strcmp(command, "quit")) { break; } // breaks out of infinite loop if(!strcmp(command, "force")) { engineSide = NONE; continue; } if(!strcmp(command, "analyze")) { engineSide = ANALYZE; continue; } if(!strcmp(command, "exit")) { engineSide = NONE; continue; } - if(!strcmp(command, "otim")) { goto noPonder; } // do not start pondering after receiving time commands, as move will follow immediately - if(!strcmp(command, "time")) { sscanf(inBuf, "time %d", &timeLeft); goto noPonder; } if(!strcmp(command, "level")) { int min, sec=0; sscanf(inBuf, "level %d %d %d", &mps, &min, &inc) == 3 || // if this does not work, it must be min:sec format @@ -2220,7 +2400,7 @@ printf("in: %s\n", command); } if(!strcmp(command, "protover")){ printf("feature ping=1 setboard=1 colors=0 usermove=1 memory=1 debug=1 sigint=0 sigterm=0\n"); - printf("feature variants=\"normal,shatranj,chu,dai,tenjiku,12x12+0_fairy,9x9+0_shogi\"\n"); + printf("feature variants=\"normal,shatranj,makruk,chu,dai,tenjiku,12x12+0_fairy,9x9+0_shogi\"\n"); printf("feature myname=\"HaChu " VERSION "\" highlight=1\n"); printf("feature option=\"Resign -check 0\"\n"); // example of an engine-defined option printf("feature option=\"Contempt -spin 0 -200 200\"\n"); // and another one @@ -2232,36 +2412,18 @@ printf("in: %s\n", command); if(sscanf(inBuf+7, "Contempt=%d", &contemptFactor) == 1) continue; continue; } - if(!strcmp(command, "variant")) { - for(i=0; i<5; i++) { - sscanf(inBuf+8, "%s", command); - if(!strcmp(variants[i].name, command)) { - Init(i); stm = Setup2(NULL); break; - } - } - continue; - } if(!strcmp(command, "sd")) { sscanf(inBuf, "sd %d", &maxDepth); continue; } if(!strcmp(command, "st")) { sscanf(inBuf, "st %d", &timePerMove); continue; } if(!strcmp(command, "memory")) { SetMemorySize(atoi(inBuf+7)); continue; } if(!strcmp(command, "ping")) { printf("pong%s", inBuf+4); continue; } // if(!strcmp(command, "")) { sscanf(inBuf, " %d", &); continue; } - if(!strcmp(command, "new")) { - engineSide = BLACK; Init(V_CHESS); stm = Setup2(NULL); maxDepth = MAXPLY; randomize = OFF; comp = 0; - continue; - } - if(!strcmp(command, "setboard")){ engineSide = NONE; Init(currentVariant); stm = Setup2(inBuf+9); continue; } if(!strcmp(command, "easy")) { ponder = OFF; continue; } if(!strcmp(command, "hard")) { ponder = ON; continue; } - if(!strcmp(command, "undo")) { stm = TakeBack(1); continue; } - if(!strcmp(command, "remove")) { stm = TakeBack(2); continue; } if(!strcmp(command, "go")) { engineSide = stm; continue; } if(!strcmp(command, "post")) { postThinking = ON; continue; } if(!strcmp(command, "nopost")) { postThinking = OFF;continue; } if(!strcmp(command, "random")) { randomize = ON; continue; } if(!strcmp(command, "hint")) { if(ponderMove != INVALID) printf("Hint: %s\n", MoveToText(ponderMove, 0)); continue; } - if(!strcmp(command, "lift")) { Highlight(inBuf+5); continue; } - if(!strcmp(command, "put")) { ReadSquare(inBuf+4, &lastPut); continue; } if(!strcmp(command, "book")) { continue; } // non-standard commands if(!strcmp(command, "p")) { pboard(board); continue; } @@ -2277,7 +2439,7 @@ printf("in: %s\n", command); if(!strcmp(command, "accepted")){ continue; } if(!strcmp(command, "rejected")){ continue; } if(!strcmp(command, "result")) { continue; } - if(!strcmp(command, "hover")) { continue; } + if(!strcmp(command, "hover")) { continue; } if(!strcmp(command, "")) { continue; } if(!strcmp(command, "usermove")){ int move = ParseMove(inBuf+9); @@ -2287,11 +2449,28 @@ pboard(board); if(comp) PrintResult(stm, -INF); // against computer: claim } else { stm = MakeMove2(stm, move); - ponderMove = INVALID; + ponderMove = INVALID; listEnd = 0; gameMove[moveNr++] = move; // remember game } continue; } + listEnd = 0; + if(!strcmp(command, "new")) { + engineSide = BLACK; Init(V_CHESS); stm = Setup2(NULL); maxDepth = MAXPLY; randomize = OFF; curVarNr = comp = 0; + continue; + } + if(!strcmp(command, "variant")) { + for(i=0; i<7; i++) { + sscanf(inBuf+8, "%s", command); + if(!strcmp(variants[i].name, command)) { + Init(curVarNr = i); stm = Setup2(NULL); break; + } + } + continue; + } + if(!strcmp(command, "setboard")){ engineSide = NONE; Init(curVarNr); stm = Setup2(inBuf+9); continue; } + if(!strcmp(command, "undo")) { stm = TakeBack(1); continue; } + if(!strcmp(command, "remove")) { stm = TakeBack(2); continue; } printf("Error: unknown command\n"); } }