【发布时间】:2020-04-20 17:39:04
【问题描述】:
我正在尝试实现一个极小极大算法来创建一个与玩家玩井字游戏的机器人。 gui 功能在另一个文件中并且工作正常。每当轮到机器人移动时,gui 文件都会使用下面提到的代码调用该文件。 我已经在注释中包含了每个函数的作用,我相信除了 minimax() 之外的所有函数都有效 每当我运行脚本时,都会显示此错误: "RecursionError: 比较中超出了最大递归深度"
如果有不清楚的地方发表评论,我会尽力简化它。 谢谢你的帮助
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
o_counter = 0
x_counter = 0
for i in board:
for j in i:
if j == 'X':
x_counter += 1
elif j == 'O':
o_counter += 1
if x_counter == 0 and o_counter == 0:
return 'O'
elif x_counter > o_counter:
return 'O'
elif o_counter > x_counter:
return 'X'
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
action = []
for i in range(3):
for j in range(3):
if board[i][j] is None:
action.append([i, j])
return action
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
p = player(board)
i, j = action
board[i][j] = p
return board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
if board[0][0] == board[1][1] == board[2][2]:
return board[0][0]
elif board[0][2] == board[1][1] == board[2][0]:
return board[0][2]
else:
for i in range(3):
if board[i][0] == board[i][1] == board[i][2]:
return board[i][0]
elif board[0][i] == board[1][i] == board[2][i]:
return board[0][i]
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) == 'X' or winner(board) == 'O' :
return True
else:
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == 'X':
return 1
elif winner(board) == 'O':
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
return_action = [0, 0]
available_actions = actions(board)
score = 0
temp_board = board
for action in range(len(available_actions)):
temp_score = 0
i, j = available_actions[action]
temp_board[i][j] = player(temp_board)
if winner(temp_board) == 'X' or winner(temp_board) == 'O':
temp_score += utility(temp_board)
else:
minimax(temp_board)
if temp_score > score:
score = temp_score
return_action = action
return available_actions[return_action]
【问题讨论】:
-
顺便说一句,让程序持续跟踪轮到谁可能会更好,而不是每次都从棋盘状态重新计算出来。
标签: python recursion artificial-intelligence minimax