python - 极小极大递归超时
问题描述
我正在尝试为 pacman 游戏编写 minimax 算法。我的递归有问题 - 有时我的算法“有效”(它不会崩溃,但仍然返回错误的值),然后有时它会崩溃并给我一个递归错误,说超出了最大递归深度。有人可以阐明我在这里做错了什么吗?谢谢!
def minimax(self, gamestate, depth, agent):
if depth == self.depth or gamestate.isWin() or gamestate.isLose():
return self.evaluationFunction(gamestate), Directions.STOP
best_move = None
if agent == 0: ## Pacman is max
best_val = float('-inf')
else: ## ghosties are min
best_val = float('inf')
actions = gamestate.getLegalActions(agent)
for action in actions:
next_agent = agent + 1 ## quit moving me! ## this goes here to set next_agent to be same as agent each iteration, because it also gets changed below
successor = gamestate.generateSuccessor(agent, action) ## generate successors gamestate (ie new board)
if next_agent == gamestate.getNumAgents():
next_agent = 0 ## Once we reach the last agent, set back to 0
depth += 1 ## increment depth
v = self.minimax(successor, depth, next_agent)
## here is where we set the max and min values based on the agent
if agent == 0: ## pacman - max
if v > best_val:
best_val = v
best_move = action
else: ## ghost - min
if v < best_val:
best_val = v
best_move = action
return best_move, best_val
解决方案
推荐阅读
- c++ - 从 JSON 字符串 C++ 读取时出现字符串下标超出范围错误
- r - 如何将 addDraw 创建的多边形存储在变量中作为 sf 数据
- javascript - 函数完成后如何在 HTML 中显示 javascript 结果
- filter - 领域过滤器问题
- javascript - 运行依赖项的 package.json 中的脚本
- laravel - Laravel Google Compute Engine - 排队的作业不起作用
- azure-pipelines - Azure Build Pipelines - 作业以随机顺序运行
- c# - 使用边框上的子控件调整无边框 WinForm 的大小
- sql - 从sql server中的字符串中提取所有十进制值
- python - 将 Cython 头文件导入 C 代码并用 Xcode 编译