Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zobrist hashing #45

Merged
merged 5 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ arrayvec = "0.7"

[dev-dependencies]
iai = "0.1"
rand = "0.8"

[build-dependencies]
rand = { version="0.8", features=["std_rng"] }

[package.metadata.docs.rs]
all-features = true
Expand Down
65 changes: 59 additions & 6 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ use std::io;
use std::io::Write;
use std::path::Path;

use rand::prelude::*;


mod color;
mod util;
mod types;
Expand Down Expand Up @@ -96,9 +99,9 @@ fn dump_slice<W: Write, T: Clone + LowerHex>(w: &mut W, name: &str, tname: &str,
writeln!(w, "];")
}

fn dump_table<W: Write, T: Clone + LowerHex>(w: &mut W, name: &str, tname: &str, table: &[[T; 64]; 64]) -> io::Result<()> {
fn dump_table<W: Write, T: Clone + LowerHex, const ROWS: usize, const COLS: usize>(w: &mut W, name: &str, tname: &str, table: &[[T; COLS]; ROWS]) -> io::Result<()> {
writeln!(w, "#[allow(clippy::unreadable_literal)]")?;
write!(w, "static {}: [[{}; 64]; 64] = [", name, tname)?;
write!(w, "static {}: [[{}; {}]; {}] = [", name, tname, COLS, ROWS)?;
for row in table.iter() {
write!(w, "[")?;
for column in row.iter().cloned() {
Expand All @@ -110,12 +113,18 @@ fn dump_table<W: Write, T: Clone + LowerHex>(w: &mut W, name: &str, tname: &str,
}

fn main() -> io::Result<()> {
// generate attacks.rs
let out_dir = env::var("OUT_DIR").expect("got OUT_DIR");
let dest_path = Path::new(&out_dir).join("attacks.rs");
let mut f = File::create(&dest_path).expect("created attacks.rs");

// generate attacks.rs
let attacks_path = Path::new(&out_dir).join("attacks.rs");
let mut f = File::create(&attacks_path).expect("created attacks.rs");
generate_basics(&mut f)?;
generate_sliding_attacks(&mut f)
generate_sliding_attacks(&mut f)?;

// generate zobrist.rs
let zobrist_path = Path::new(&out_dir).join("zobrist.rs");
let mut f = File::create(&zobrist_path).expect("error creating zobrist.rs");
generate_zobrist(&mut f)
}

fn generate_basics<W: Write>(f: &mut W) -> io::Result<()> {
Expand Down Expand Up @@ -168,3 +177,47 @@ fn generate_sliding_attacks<W: Write>(f: &mut W) -> io::Result<()> {

dump_slice(f, "ATTACKS", "u64", &attacks)
}

// inspiration from this implementation taken from: https://github.com/sfleischman105/Pleco
fn generate_zobrist<W: Write>(f: &mut W) -> io::Result<()> {
let seed = 0x30b3_1137_bb45_7b1b_u64;
let mut rnd = StdRng::seed_from_u64(seed);

let mut piece_square :[[u64; 16]; 64] = [[0; 16]; 64];

// generate random values for the piece-square table
for row in piece_square.iter_mut() {
for col in row.iter_mut() {
*col = rnd.gen::<u64>();
}
}

dump_table(f, "PIECE_SQUARE", "u64", &piece_square)?;


// generate random values for enpassant
let mut enpassant :[u64; 8] = [0; 8];

for file in enpassant.iter_mut() {
*file = rnd.gen::<u64>();
}

dump_slice(f, "ENPASSANT", "u64", &enpassant).expect("Error dumping enpassant slice");


// generate random values for castling
let mut castle :[u64; 4] = [0; 4];

for castle in castle.iter_mut() {
*castle = rnd.gen::<u64>();
}

dump_slice(f, "CASTLE", "u64", &castle).expect("Error dumping castle slice");


// generate two random values: side & no-pawns
writeln!(f, "const SIDE :u64 = 0x{:x}_u64;", rnd.gen::<u64>());
// writeln!(f, "const NO_PAWNS :u64 = 0x{:x}_u64;", rnd.gen::<u64>());

Ok( () )
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ mod movelist;
mod magics;
mod perft;
mod util;
mod zobrist;

pub mod attacks;
pub mod bitboard;
Expand Down
4 changes: 2 additions & 2 deletions src/position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ impl Chess {

impl Default for Chess {
fn default() -> Chess {
Chess {
Chess {
board: Board::default(),
turn: White,
castles: Castles::default(),
Expand Down Expand Up @@ -514,7 +514,7 @@ impl Position for Chess {
fn play_unchecked(&mut self, m: &Move) {
do_move(&mut self.board, &mut self.turn, &mut self.castles,
&mut self.ep_square, &mut self.halfmoves,
&mut self.fullmoves, m);
&mut self.fullmoves, m);
}

fn castles(&self) -> &Castles {
Expand Down
29 changes: 29 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,19 @@ impl Piece {
}
}

// we implement Into instead of From (or TryFrom) because we only need one-way conversion
// Piece -> usize
impl Into<usize> for Piece {
#[inline(always)]
fn into(self) -> usize {
if self.color == Color::Black {
self.role as usize + 8_usize
} else {
self.role as usize
}
}
}

/// Information about a move.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[repr(align(4))]
Expand Down Expand Up @@ -383,6 +396,22 @@ impl CastlingSide {
pub fn rook_to(self, color: Color) -> Square {
Square::from_coords(self.rook_to_file(), color.backrank())
}

// used for zobrist hashing
#[inline(always)]
pub fn to_usize(self, color: Color) -> usize {
if color == Color::White {
match self {
CastlingSide::KingSide => 0,
CastlingSide::QueenSide => 1,
}
} else {
match self {
CastlingSide::KingSide => 2,
CastlingSide::QueenSide => 3
}
}
}
}

/// `Standard` or `Chess960`.
Expand Down
Loading