python - 极小极大的评估函数
问题描述
大家好,我目前正在学习 CS50AI 课程。第一个任务是创建一个带有 minimax 函数的 tictactoe AI。我的问题是:据我了解,必须对游戏的位置进行静态评估。我试图用伪代码写这样的东西:
If next move is a winning move:
return 10 point
elif opponent is going to win stop him:
return 8 point
之类的事情。但是当我检查其他 minvalue - max value 函数时,没有这样的事情。
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
currentactions = actions(board)
if player(board) == X:
vT = -math.inf
move = set()
for action in currentactions:
v, count = maxvalue(result(board,action), 0)
if v > vT:
vT = v
move = action
else:
vT = math.inf
move = set()
for action in currentactions:
v, count = minvalue(result(board,action), 0)
if v < vT:
vT = v
move = action
print(count)
return move
def maxvalue(board, count):
"""
Calculates the max value of a given board recursively together with minvalue
"""
if terminal(board): return utility(board), count+1
v = -math.inf
posactions = actions(board)
for action in posactions:
vret, count = minvalue(result(board, action), count)
v = max(v, vret)
return v, count+1
def minvalue(board, count):
"""
Calculates the min value of a given board recursively together with maxvalue
"""
if terminal(board): return utility(board), count+1
v = math.inf
posactions = actions(board)
for action in posactions:
vret, count = maxvalue(result(board, action), count)
v = min(v, vret)
return v, count+1
这是 sikburn 的 tictactoe 实现的 max - min 函数。我无法理解最大值或最小值函数会产生什么结果。任何人都可以澄清我的逻辑吗?顺便说一句,terminal()
函数检查游戏是否结束(有赢家或平局),并且result()
函数将棋盘和动作作为输入并返回结果棋盘。感谢所有的帮助。
解决方案
在utility
函数中(未包含在您的代码中),您可能将 1 分配给 X 胜利,-1 分配给 O 胜利,否则为 0。该minimax
函数递归调用所有可能的移动minvalue
,maxvalue
直到游戏结束,无论是平局还是胜利。然后它调用utility
以获取值。两者minvalue
并maxvalue
保证 X 和 O 将始终选择最佳可能的移动。
不要忘记检查板是否是终端,None
如果是终端,则在继续之前,在minimax
函数中返回。
交换minvalue
和maxvalue
函数的调用minimax
:对于 X,调用minvalue
(因为 X 想知道 O 下一步行动)和对于 O,调用maxvalue
(出于相同的原因)。
如果您想在每次迭代中查看评估,您可以在返回这些值之前在and函数的末尾打印类似f"Minvalue: {v}, Iteration: {count+1}"
and的内容。我认为这会更容易理解。f"Maxvalue: {v}, Iteration: {count+1}"
minvalue
maxvalue
我 hppe 我澄清了你的疑虑。
推荐阅读
- android - Xamarin Forms 更新到 3.1 后,“LinkAssemblies”任务意外失败
- kubernetes - Kubernetes 中的 Ansible AWX RabbitMQ 容器无法使用 nxdomain 从 k8s 获取节点
- c# - Vector3.Slerp() 没有完成它必须做的事情就停止了
- ruby - watir 中的 HTML 块和内联元素文本选择
- r - 使用 lapply 过滤多个数据集
- python - Python numpy.where: TypeError: 只有整数标量数组可以转换为标量索引;在字典列表中
- php - 在 Codeigniter 中上传图片时出错
- css - 角度的递归引导面包屑
- django - 如何使用单独的应用程序文件夹运行本地 Django 站点?
- android - 启动完成不工作