zorbristHash.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from PRNG import *
  2. #zobrist hashing class
  3. class hashTable():
  4. def __init__(self, seed = time.time_ns()):
  5. self.constVal = [0,1,2,3,4,5,6,7,8,9,10,11]
  6. self.pieceChar = 'PRBNQKprbnqk'
  7. self.random_val = PRNG.LCG(maxn = 768, seedn = seed, m = 18446744073709551557, a = 2774243619903564593)
  8. self.table = []
  9. self.black_move = PRNG.LCG(maxn = 1, seedn = 4829959, m = 18446744073709551557, a = 2774243619903564593)[0]
  10. self.hashTbl = {}
  11. #initiating zobrist hash values, one for each
  12. #piece and every location
  13. def init_zobrist(self):
  14. self.table = []
  15. for i in range(64):
  16. self.table.append([])
  17. for j in range(12):
  18. self.table[i].append(None)
  19. for i in range(64):
  20. for j in range(12):
  21. self.table[i][j] = self.random_val[i*12 + j]
  22. #hashing algorithm for board
  23. def hash(self, board, colour):
  24. h = 0
  25. if colour == 'black':
  26. h = h ^ self.black_move
  27. p = 0
  28. for i in range(128):
  29. if (i & 0x88) == 0:
  30. if board.board[i] != None:
  31. j = self.constVal[self.pieceChar.index(board.board[i].character)]
  32. h = h ^ self.table[p][j]
  33. p += 1
  34. return h
  35. #adding items to the lookup table
  36. def append(self, board, colour, score, FEN, hashVal = None):
  37. content = [board, score, FEN]
  38. if hashVal == None:
  39. hashVal = self.hash(board, colour)
  40. if hashVal not in self.hashTbl:
  41. self.hashTbl[hashVal] = content
  42. else:
  43. if self.hashTbl[hashVal][2] == content[2]:
  44. return
  45. replace = self.hashTbl[hashVal]
  46. replace = (replace[0], replace[1], replace[2], hashVal + 1)
  47. self.append(board, colour, score, FEN, hashVal = hashVal + 1)
  48. #fetching from lookup table
  49. def find(self, content, colour, hashVal = None):
  50. if hashVal == None:
  51. hashVal = self.hash(content, colour)
  52. if hashVal in self.hashTbl:
  53. if len(self.hashTbl[hashVal]) == 4:
  54. if self.hashTbl[2] == self.hashTabl[2]:
  55. return self.hashTbl[hashVal]
  56. return self.find(content, hashVal + 1)
  57. else:
  58. return self.hashTbl[hashVal]