tinycodinglm / chess /chess-0098.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.59 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 Zobrist hashing with incremental updates for efficient transposition table lookups

Assistant

#include <cstdint>
#include <random>

namespace Zobrist {
uint64_t pieceKeys[12][64]; // [pieceType][square]
uint64_t castlingKeys[16]; // 4-bit castling rights
uint64_t epKeys[8]; // en passant file
uint64_t sideKey; // side to move

markdown
void init() {
    std::mt19937_64 rng(0x5D14312AED46B9A5ULL); // fixed seed for reproducibility
    std::uniform_int_distribution<uint64_t> dist;

    for (int pt = 0; pt < 12; pt++)
        for (int sq = 0; sq < 64; sq++)
            pieceKeys[pt][sq] = dist(rng);

    for (int i = 0; i < 16; i++)
        castlingKeys[i] = dist(rng);

    for (int i = 0; i < 8; i++)
        epKeys[i] = dist(rng);

    sideKey = dist(rng);
}

uint64_t computeFull(const BitboardBoard& board) {
    uint64_t hash = 0;
    for (int pt = 0; pt < 12; pt++) {
        uint64_t bb = board.pieces[pt];
        while (bb) {
            int sq = __builtin_ctzll(bb);
            hash ^= pieceKeys[pt][sq];
            bb &= bb - 1;
        }
    }
    hash ^= castlingKeys[board.castlingRights];
    if (board.enPassantSquare >= 0)
        hash ^= epKeys[board.enPassantSquare % 8];
    if (board.sideToMove == BLACK)
        hash ^= sideKey;
    return hash;
}

// Incremental update helpers
inline uint64_t xorPiece(uint64_t hash, int pt, int sq) {
    return hash ^ pieceKeys[pt][sq];
}

inline uint64_t xorCastling(uint64_t hash, int oldRights, int newRights) {
    return hash ^ castlingKeys[oldRights] ^ castlingKeys[newRights];
}

inline uint64_t xorEP(uint64_t hash, int oldSq, int newSq) {
    uint64_t h = hash;
    if (oldSq >= 0) h ^= epKeys[oldSq % 8];
    if (newSq >= 0) h ^= epKeys[newSq % 8];
    return h;
}

inline uint64_t flipSide(uint64_t hash) {
    return hash ^ sideKey;
}

}