tinycodinglm / chess /chess-0095.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
3.29 kB
opencode trace
System You are an expert programmer specializing in chess programming and game AI. You implement efficient algorithms with optimal performance.

You are an expert programmer specializing in chess programming and game AI. You implement efficient algorithms with optimal performance.

User

Implement Syzygy endgame tablebase probing for a chess engine

Assistant

#include <cstdint>
#include <cstring>
#include <algorithm>

class SyzygyTablebase {
static const int TBPIECES = 7;
struct TBEntry {
uint64_t key;
int pieceCount;
uint8_t pieceOrder;
uint8_t* data;
uint32_t numEntries;
};

markdown
struct TBHashEntry {
    uint64_t key;
    TBEntry* ptr;
};

TBHashEntry hashTable[1 << 12]; // simplified
int numTables;

uint64_t computeKey(const BitboardBoard& board) {
    uint64_t key = 0;
    int pieceCount[2] = {0, 0};
    for (int pt = 0; pt < 6; pt++) {
        uint64_t bb = board.pieces[pt];
        while (bb) {
            int sq = __builtin_ctzll(bb);
            pieceCount[WHITE]++;
            key ^= Zobrist::pieceKeys[pt][sq];
            bb &= bb - 1;
        }
        bb = board.pieces[pt + 6];
        while (bb) {
            int sq = __builtin_ctzll(bb);
            pieceCount[BLACK]++;
            key ^= Zobrist::pieceKeys[pt + 6][sq];
            bb &= bb - 1;
        }
    }
    return key;
}

int probeWDL(const BitboardBoard& board) {
    uint64_t key = computeKey(board);
    TBEntry* entry = findEntry(key);
    if (!entry) return -2; // not found

    int pieces[TBPIECES];
    int numPieces = 0;
    for (int pt = 0; pt < 12; pt++) {
        uint64_t bb = board.pieces[pt];
        while (bb) {
            int sq = __builtin_ctzll(bb);
            pieces[numPieces++] = pt * 64 + sq;
            bb &= bb - 1;
        }
    }
    std::sort(pieces, pieces + numPieces);

    uint64_t idx = computeIndex(entry, pieces, numPieces, board.occupancy[BOTH]);
    uint8_t wdl = entry->data[idx / 2];
    if (idx & 1) wdl >>= 4;
    wdl &= 0x0F;

    return wdl; // 2=win, 1=cursed-win, 0=draw, -1=blessed-loss, -2=loss
}

int probeDTZ(const BitboardBoard& board) {
    int wdl = probeWDL(board);
    if (wdl == 0) return 0;
    if (wdl == -2) return -1;
    if (wdl == 2) return 1;

    uint64_t key = computeKey(board);
    TBEntry* entry = findEntry(key);
    if (!entry) return -1;

    // DTZ probing withPawn/DtZ tables
    int dtz = computeDTZ(entry, board);
    if (wdl < 0) dtz = -dtz;
    return dtz;
}

bool isDraw(int dtz) const {
    return dtz == 0;
}

bool isWinning(int dtz) const {
    return dtz > 0;
}

bool hasTablebase(const BitboardBoard& board) const {
    int pieceCount = popcount(board.occupancy[BOTH]);
    return pieceCount <= TBPIECES;
}

};