Tr3*_*ger 5 python artificial-intelligence hashtable iterative-deepening minimax
我在 python 中创建了一个连接 4 AI,我为此使用了带迭代深化和 alpha beta 修剪的 minimax。对于更大的深度,它仍然很慢,所以我想实现一个换位表。在阅读它之后,我想我得到了一般的想法,但我还没有完全让它发挥作用。这是我的代码的一部分:(minimax 的最大化部分):
if(isMaximizing):
maxEval = -99999999999
bestMove = None
# cache.get(hash(board)) Here's where i'd check to see if the hash is already in the table
# if so i searched for the best move that was given to that board before.
# loop through possible moves
for move in [3,2,4,1,5,0,6]:
if moves[move] > -1:
# check if time limit has been reached for iterative deepening
if startTime - time.time() <= -10:
timeout = True
return (maxEval, bestMove, timeout)
if timeout == False:
board = makeMove((moves[move],move), True, board) # make the move
eval = minimax(depth - 1, board, False, alpha, beta, cache, zobTable, startTime, timeout)[0]
if eval > maxEval:
maxEval = eval
bestMove = (moves[move]+1,move)
board[moves[move] + 1][move] = '_' # undo the move on the board
moves[move] = moves[move] + 1 # undo the move in the list of legal moves
alpha = max(alpha, maxEval)
if alpha >= beta:
break
# cache.set(hash(board), (eval, value)) Here's where i would set the value and bestmove for the current boardstate
return (maxEval, bestMove, timeout)
Run Code Online (Sandbox Code Playgroud)
现在我正在使用 zobrist 散列方法对板进行散列,并且我正在使用有序的 dict 将散列的板添加到。对于这个哈希键,我已经添加了该板的值和该板的 bestMove。不幸的是,这似乎使算法选择了错误的动作(它以前工作过),有没有人知道应该将棋盘状态放在缓存中的哪个位置,以及应该从缓存中获取它们的位置?
关于您的方法的几点:
如果你想让事情变得更快,用 C 或 C++ 编写高效的代码将比 Python 快得多。通过从 Python 切换到良好的 C/C++ 实现,我发现此类搜索代码的性能提高了 10-100 倍。无论哪种方式,您都应该尝试编写避免在搜索期间分配内存的代码,因为这非常昂贵。也就是说,与添加转置表相比,您可以通过更有效的编码获得更好的回报。
当在博弈树搜索中使用 Zobrist 哈希作为换位表时,您通常不会显式存储状态。您只需检查哈希值是否相等。虽然出错的可能性很小,但仅存储哈希值所需的内存要少得多,并且使用 64 位哈希值,对于您正在进行的搜索类型来说,发生冲突的可能性可能微乎其微。(出现错误的可能性甚至更低。)
当您将值存储在转置表中时,您还需要存储搜索期间使用的 alpha 和 beta 边界。当您在搜索过程中从节点返回值时,它要么是真实值的上限(因为值 = beta),要么是真实值的下限(因为值 = alpha)或节点的实际值(阿尔法 < 值 < 贝塔)。您需要将其存储在转置表中。然后,当您想要重新使用该值时,您必须检查是否可以在给定当前 alpha 和 beta 范围的情况下使用该值。(您可以通过在转置表中找到值后实际执行搜索来验证这一点,看看您从搜索中获得的值是否与表中获得的值相同。)