Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type
- TZobristHash = record
- translation: array[#0..#127] of Int8;
- table: array[0..63] of array [0..11] of Int64;
- wtm: Int64;
- end;
- TState = array [0..127] of char;
- EBoardIndex = (a1,b1,c1,d1,e1,f1,g1,h1, wck, wcq, bck, bcq, ep, wtm,wkng,bkng,
- a2,b2,c2,d2,e2,f2,g2,h2, __a2,__b2,__c2,__d2,__e2,__f2,__g2,__h2,
- a3,b3,c3,d3,e3,f3,g3,h3, __a3,__b3,__c3,__d3,__e3,__f3,__g3,__h3,
- a4,b4,c4,d4,e4,f4,g4,h4, __a4,__b4,__c4,__d4,__e4,__f4,__g4,__h4,
- a5,b5,c5,d5,e5,f5,g5,h5, __a5,__b5,__c5,__d5,__e5,__f5,__g5,__h5,
- a6,b6,c6,d6,e6,f6,g6,h6, __a6,__b6,__c6,__d6,__e6,__f6,__g6,__h6,
- a7,b7,c7,d7,e7,f7,g7,h7, __a7,__b7,__c7,__d7,__e7,__f7,__g7,__h7,
- a8,b8,c8,d8,e8,f8,g8,h8, __a8,__b8,__c8,__d8,__v0,__v1,__v2,__v3);
- const
- BOARD_INDICES: set of EBoardIndex = [a1..h1, a2..h2, a3..h3, a4..h4, a5..h5, a6..h6, a7..h7, a8..h8];
- // Initialize Zobrist keys with random values
- procedure TZobristHash.Init();
- var
- i, j: Integer;
- begin
- for i:=0 to 63 do
- for j:=0 to 11 do
- Self.table[i, j] := Random($7FFFFFFFFFFFFFFF);
- Self.wtm := Random($7FFFFFFFFFFFFFFF);
- translation['K'] := 0;
- translation['Q'] := 1;
- translation['R'] := 2;
- translation['B'] := 3;
- translation['N'] := 4;
- translation['P'] := 5;
- translation['k'] := 6;
- translation['q'] := 7;
- translation['r'] := 8;
- translation['b'] := 9;
- translation['n'] := 10;
- translation['p'] := 11;
- end;
- // Calculate the Zobrist key for a given position
- function TZobristHash.Hash(board: TState): Int64;
- var
- i: EBoardIndex;
- x: Int32;
- begin
- Result := 0;
- for i in BOARD_INDICES do
- if board[i] <> '.' then
- begin
- x := Int8(i) - (Int8(i) div 16) * 8;
- Result := Result xor Self.table[x, self.translation[board[i]]];
- end;
- end;
- function TZobristHash.Update(hash: Int64; i: Int32; p:Char): Int64;
- var x: Int32;
- begin
- x := Int8(i) - (Int8(i) div 16) * 8;
- Result := hash xor self.table[x, self.translation[p]];
- end;
- var
- z: TZobristHash;
- str: string =
- 'RNB.Q.NR'+ #1#1#1#1#0#1#0#0 +
- 'PPPKPPBP'+ #0#0#0#0#0#0#0#0 +
- '...P..P.'+ #0#0#0#0#0#0#0#0 +
- '........'+ #0#0#0#0#0#0#0#0 +
- '........'+ #0#0#0#0#0#0#0#0 +
- '...bpq..'+ #0#0#0#0#0#0#0#0 +
- 'ppppnppp'+ #0#0#0#0#0#0#0#0 +
- 'rnb.k..r'+ #0#0#0#0#0#0#0#0;
- s: TState;
- h: Int64;
- begin
- MemMove(str[1], s[0], 128);
- z.Init();
- h := z.Hash(s);
- WriteLn('The Board hash => ', h);
- // let's move a pawn from a6 to a7
- WriteLn h := z.Update(h, Int8(a6), 'p'); // xor out the pawn at a6
- WriteLn h := z.Update(h, Int8(a7), 'p'); // xor in a pawn at a7
- WriteLn h := z.Update(h, Int8(a7), 'p'); // xor out the pawn at a7
- WriteLn h := z.Update(h, Int8(a6), 'p'); // xor in a pawn at a6
- // ^ should be back to previous state, cheap hashing!
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement