I am trying to create a chess engine. I was told that we can generate unique key for any chess position by hashing individual piece keys. Its like a particular piece on a particular square has an unique 64 bit key. Then we are supposed to XOR the piece keys for every piece present in the position.
Ignoring the castling and the en Passant square information about a chess position, here is how I was told to generate a position key(in C language)
typedef unsigned long long U64;
#define RAND_64 ( (U64) rand() + \
(U64) rand() << 15 + \
(U64) rand() << 31 + \
(U64) rand() << 45 \
)
Here is how the piece keys are generated from RAND 64 declared above...
int index, index2;
U64 pieceKeys[12][64]; // For 12 pieces on every possible square.
for(index = 0; index<12; index++) {
for(index2 = 0; index2<64; index2++) {
pieceKeys[index][index2] = RAND_64;
}
}
My question is that here isn't there a possibility of generating the same piece key for 2 pieces on 2 squares. If that happens then there will be ambiguity when we create the position key by XOR ing the piece keys.
Am I right? If so then how can I solve this potential problem?
There are only 6 different types of chess pieces and then there is black and white. Use 1 bit for black or white and 3 bits for the piece type and 7 bits for the square number, e.g.:
// square numbes are 0x0000 thru 0x007F
#define BLACK 0x0080
#define WHITE 0x0000
#define KING 0x0100
#define QUEEN 0x0200
#define ROOK 0x0400
#define BISHOP 0x0800
#define KNIGHT 0x1000
#define PAWN 0x2000
#define PIECE_MASK 0x3F00
#define SQUARE_MASK 0x007F
and use bit masking to determine them:
int color= board[x][y] & BLACK; // non zero if black; zero if white
int is_king= board[x][y] & KING;
int squarenum= board[x][y] & SQUARE_MASK;
int piece= board[x][y] & PIECE_MASK;
switch (piece>>8) {
case 1: //King
case 2: //Queen
case 4: //Rook
case 8: //Bishop
case 16://Knight
case 32://Pawn
}