我正在尝试制作一个国际象棋引擎,其基本思想是,当我点击一个按钮时,计算机就会移动。这是我的密码:
def alphabeta(board, node, depth, a, b, maximizer):
if depth == 0:
return evaluate.node(node)
if maximizer == True:
value = -10**3 # Number that's smaller than what the evaluation algorithm can return
for child in board.get_all_nodes(node):
m = alphabeta(board, child, depth-1, a, b, False)
value = max(value, m)
a = max(a, value)
if a >= b:
break
return value
else:
value = 10**3 # Number that's bigger than what the evaluation algorithm can return
for child in board.get_all_nodes(node):
m = alphabeta(board, child, depth - 1, a, b, True)
value = min(value, m)
b = min(b, value)
if a >= b:
break
return value
问题是,这段代码返回的是对可能的最佳移动的评估,而不是移动树本身。如果不再次运行整个函数,我将如何找到最佳移动
有两种方法可以处理此问题:
创建另一个看起来类似于
alphabeta
的函数getbestmove
,但当它获得最佳值时,它还将相应的child
(move)赋值给一个新变量bestnode
。它不返回值,而是返回bestnode
。不要让这个函数递归地调用本身,而是alphabeta
,对于更深层的搜索级别,您不需要记住最佳移动你总是会打电话给
getbestmove
以获得最佳移动。。。不再需要从getbestmove
外部直接调用alphabeta
调整
alphabeta
,使其以元组的形式返回值和相应的移动。当深度为0时,您没有移动,因此最好的移动是None
。递归调用应该从返回的元组(值部分)提取第一个值,最外层的alphabeta
调用可以从返回的元组的第二部分获得最佳移动您甚至可以扩展它来跟踪搜索树中的“最佳路径”
相关问题 更多 >
编程相关推荐