1 
2 // hash.c
3 
4 // includes
5 
6 #include "board.h"
7 #include "hash.h"
8 #include "piece.h"
9 #include "random.h"
10 #include "square.h"
11 #include "util.h"
12 
13 // variables
14 
15 static uint64 Castle64[16];
16 
17 // prototypes
18 
19 static uint64 hash_castle_key_debug (int flags);
20 
21 // functions
22 
23 // hash_init()
24 
hash_init()25 void hash_init() {
26 
27    int i;
28 
29    for (i = 0; i < 16; i++) Castle64[i] = hash_castle_key_debug(i);
30 }
31 
32 // hash_key()
33 
hash_key(const board_t * board)34 uint64 hash_key(const board_t * board) {
35 
36    uint64 key;
37    int colour;
38    const uint8 * ptr;
39    int sq, piece;
40 
41    ASSERT(board_is_ok(board));
42 
43    // init
44 
45    key = 0;
46 
47    // pieces
48 
49    for (colour = 1; colour <= 2; colour++) { // HACK
50       for (ptr = board->list[colour]; (sq=*ptr) != SquareNone; ptr++) {
51          piece = board->square[sq];
52          key ^= hash_piece_key(piece,sq);
53       }
54    }
55 
56    // castle flags
57 
58    key ^= hash_castle_key(board_flags(board));
59 
60    // en-passant square
61 
62    sq = board->ep_square;
63    if (sq != SquareNone) key ^= hash_ep_key(sq);
64 
65    // turn
66 
67    key ^= hash_turn_key(board->turn);
68 
69    return key;
70 }
71 
72 // hash_piece_key()
73 
hash_piece_key(int piece,int square)74 uint64 hash_piece_key(int piece, int square) {
75 
76    ASSERT(piece_is_ok(piece));
77    ASSERT(square_is_ok(square));
78 
79    return random_64(RandomPiece+piece_to_12(piece)*64+square_to_64(square));
80 }
81 
82 // hash_castle_key()
83 
hash_castle_key(int flags)84 uint64 hash_castle_key(int flags) {
85 
86    ASSERT((flags&~0xF)==0);
87 
88    return Castle64[flags];
89 }
90 
91 // hash_castle_key_debug()
92 
hash_castle_key_debug(int flags)93 static uint64 hash_castle_key_debug(int flags) {
94 
95    uint64 key;
96    int i;
97 
98    ASSERT((flags&~0xF)==0);
99 
100    key = 0;
101 
102    for (i = 0; i < 4; i++) {
103       if ((flags & (1<<i)) != 0) key ^= random_64(RandomCastle+i);
104    }
105 
106    return key;
107 }
108 
109 // hash_ep_key()
110 
hash_ep_key(int square)111 uint64 hash_ep_key(int square) {
112 
113    ASSERT(square_is_ok(square));
114 
115    return random_64(RandomEnPassant+square_file(square));
116 }
117 
118 // hash_turn_key()
119 
hash_turn_key(int colour)120 uint64 hash_turn_key(int colour) {
121 
122    ASSERT(colour_is_ok(colour));
123 
124    return (colour_is_white(colour)) ? random_64(RandomTurn) : 0;
125 }
126 
127 // end of hash.cpp
128 
129