zobrist.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use rand::prelude::*;
  2. use movegen::{PieceType};
  3. use bitboard::Square;
  4. pub type Hash = u64;
  5. pub struct ZobristTable {
  6. board: [[Hash; 12]; 64],
  7. en_passant: [Hash; 8],
  8. castling_rights: [Hash; 4],
  9. turn: Hash,
  10. }
  11. impl ZobristTable {
  12. pub fn new() -> Self {
  13. let mut zt = ZobristTable {
  14. board: [[0; 12]; 64],
  15. en_passant: [0; 8],
  16. castling_rights: [0; 4],
  17. turn: 0
  18. };
  19. let seed: [u8; 32] =
  20. [0x3f, 0x64, 0x5, 0x48, 0xef, 0x2d, 0xcb, 0x8e,
  21. 0xe6, 0x67, 0xc, 0x90, 0xcf, 0x10, 0x2d, 0x1e,
  22. 0x32, 0xb5, 0xbf, 0xe3, 0xf, 0x95, 0x8c, 0xf1,
  23. 0xbc, 0xe7, 0xb5, 0x76, 0x16, 0x4a, 0x17, 0x39];
  24. let mut rng = StdRng::from_seed(seed);
  25. for piece in &mut zt.board {
  26. for sq in piece {
  27. *sq = rng.next_u64();
  28. }
  29. }
  30. for file in &mut zt.en_passant {
  31. *file = rng.next_u64();
  32. }
  33. for cr in &mut zt.castling_rights {
  34. *cr = rng.next_u64();
  35. }
  36. zt.turn = rng.next_u64();
  37. return zt;
  38. }
  39. pub fn piece_hash(&self, piece_type: PieceType, side: bool, sq: Square) -> Hash {
  40. self.board[sq as usize][piece_type as usize + if side { 6 } else { 0 }]
  41. }
  42. pub fn en_passant_hash(&self, file: u8) -> Hash {
  43. self.en_passant[file as usize]
  44. }
  45. pub fn castling_rights_hash(&self, cr: u8) -> Hash {
  46. self.castling_rights[cr as usize]
  47. }
  48. pub fn all_castling_rights_hash(&self, cr: [bool; 4]) -> Hash {
  49. let mut val: Hash = 0;
  50. for i in 0..4 {
  51. if cr[i] {
  52. val ^= self.castling_rights[i as usize]
  53. }
  54. }
  55. val
  56. }
  57. pub fn turn_hash(&self) -> Hash {
  58. self.turn
  59. }
  60. }