【发布时间】:2021-12-29 04:22:37
【问题描述】:
我正在编写一个连接 4 游戏以及一个极小极大算法来进行对抗。我目前正在编写和实现 minimax 算法。现在我只是想把所有可能的棋盘状态打印到一定深度,我认为这是算法的难点。然后,我将编写算法中确定是最大化还是最小化的部分,并且从那里它应该或多或少地完成。这是我目前所拥有的,我已经注释了代码以解释每一行的作用
#I realize there will need to be an argument here determining whether to maximize or minimize, I
#will implement that after this works.
def minimax(board,depth):
#when I reach my target depth, return the board and print it
if depth == 0:
printboard(board)
return board
#For all of my possible moves, set the move, recursively call minimax until it hits target depth
#at which point the board state will be printed, and then undo the last set move so that the
#for loop can continue from previous board state
for move in possiblemoves(board):
setmove(move, board, turn)
minimax(board,depth - 1)
setmove(move, board, -1)
#call the fuction on an empty board, and do a depth of 2
minimax(board,2)
当我调用这个函数时,第一个板输出看起来很正常
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
['X', ' ', ' ', ' ', ' ', ' ', ' ']
['X', ' ', ' ', ' ', ' ', ' ', ' ']
但第二个状态,应该是第一列和第二列底部的 X。我不确定这个问题是从哪里来的,但我认为它正在删除第一个动作,而不是第二个动作,因为第二个棋盘状态看起来像
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', ' ', ' ', ' ', ' ', ' ', ' ']
[' ', 'X', ' ', ' ', ' ', ' ', ' ']
如果您对如何修复此算法以输出适当数量的棋盘状态有任何建议,我们将不胜感激!
【问题讨论】:
-
请参阅here,了解基于 minimax 的井字游戏示例。棋盘规则和游戏规则不同,但方法应按原样应用
-
您显示的代码看起来可以工作,所以问题可能出在您未显示的代码中。见minimal reproducible example。
标签: python algorithm matrix artificial-intelligence minimax