From c9d9bddf3df97ef7987c9824747ec1602522b542 Mon Sep 17 00:00:00 2001 From: Aargh Rai Date: Sat, 18 Jul 2026 18:45:15 +0530 Subject: zobrist hashing --- src/engine/moves/magic.c | 14 +------------ src/engine/transposition_table.c | 44 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 src/engine/transposition_table.c (limited to 'src/engine') diff --git a/src/engine/moves/magic.c b/src/engine/moves/magic.c index 43f4a32..74b2c72 100644 --- a/src/engine/moves/magic.c +++ b/src/engine/moves/magic.c @@ -1,4 +1,5 @@ #include "engine/magic.h" +#include "random.h" #include #include #include @@ -8,19 +9,6 @@ static magic_t bishop_table[64]; static bitboard_t *rook_attacks_flat; static bitboard_t *bishop_attacks_flat; -static u64 rng_state = 1070399; - -static u64 random_u64(void) { - rng_state ^= rng_state << 13; - rng_state ^= rng_state >> 7; - rng_state ^= rng_state << 17; - return rng_state; -} - -static u64 random_magic(void) { - return random_u64() & random_u64() & random_u64(); -} - static bitboard_t compute_rook_mask(int sq) { bitboard_t mask = 0; int rank = sq / 8, file = sq % 8; diff --git a/src/engine/transposition_table.c b/src/engine/transposition_table.c new file mode 100644 index 0000000..1afbc81 --- /dev/null +++ b/src/engine/transposition_table.c @@ -0,0 +1,44 @@ +#include "engine/transposition_table.h" + +void transposition_table_init() { + for (int i = 0; i < PIECE_TYPE_COUNT; i++) { + for (int j = 0; j < 64; j++) { + zobrist_keys.piece[i][j] = random_u64(); + } + } + for (int i = 0; i < CASTLE_COUNT; i++) { + zobrist_keys.castle[i] = random_u64(); + } + for (int i = 0; i < TURN_COUNT; i++) { + zobrist_keys.turn[i] = random_u64(); + } + for (int i = 0; i < 64; i++) { + zobrist_keys.en_passant[i] = random_u64(); + } +} + +u64 zobrist_hash(position_t position) { + u64 output = 0; + for (int i = 0; i < 64; i++) { + int piece_type = find_piece_on_square(&position, i); + output ^= zobrist_keys.piece[piece_type][i]; + } + + if (position.castling & WHITE_SHORT_CASTLE) { + output ^= zobrist_keys.castle[0]; + } + if (position.castling & WHITE_LONG_CASTLE) { + output ^= zobrist_keys.castle[1]; + } + if (position.castling & BLACK_SHORT_CASTLE) { + output ^= zobrist_keys.castle[2]; + } + if (position.castling & BLACK_LONG_CASTLE) { + output ^= zobrist_keys.castle[3]; + } + + output ^= zobrist_keys.turn[position.turn]; + output ^= zobrist_keys.en_passant[position.passantable_file]; + + return output; +} -- cgit v1.2.3