我目前正在进行一个项目,需要实现一个Minimax算法来创建一个井字游戏。在某个点上,我在比较元组和浮点数,虽然我知道这实际上是无法完成的,但我不知道这个问题从何而来,也不知道如何修复。如果有人能帮助我理解那将是非常棒的。谢谢!
这是我的代码
import copyX = "X"O = "O"EMPTY = Nonedef initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]]def player(board): Xboard_count = board[0].count(X) + board[1].count(X) + board[2].count(X) if Xboard_count % 2 == 1: return 0 else: return Xdef actions(board): """ Returns set of all possible actions (i, j) available on the board. """ move = [] for i in range(3): for j in range(3): if board[i][j] == EMPTY: move.append((i, j)) return movedef result(board, move): """ Returns the board that results from making move (i, j) on the board. """ if move not in actions(board): raise Exception("this action is not a valid action") dcopb = copy.deepcopy(board) dcopb[move[0]][move[1]] = player(board) return dcopbdef winner(board): """ Returns the winner of the game, if there is one. """ for x in range(3): if board[x][0] == board[x][1] == board[x][2] != EMPTY: return board[x][0] for y in range(3): if board[0][y] == board[1][y] == board[2][y] != EMPTY: return board[0][y] if board[0][0] == board[1][1] == board[2][2] != EMPTY: return board[0][0] if board[2][0] == board[1][1] == board[0][2] != EMPTY: return board[2][0] else: return Nonedef terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board) == X: return True elif winner(board) == O: return True for x in range(3): for y in range(3): if board[x][y] is None: return False return True ('si winner est égal à X :\n' ' return True\n' ' si winner est égal à 0\n' ' return true \n' ' \n' ' si le nombre de cases vides == 0\n' ' return true\n' ' else:\n' ' 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 if winner(board) == 0: return -1 else: return 0def minimax(board): """ Returns the optimal action for the current player on the board. """ if terminal(board): return None if player(board) == X: v = v = float('-inf') for move in actions(board): temp = MinValue(result(board, move)) if temp > v: v = temp best = move else: v = float('inf') for move in actions(board): temp = MaxValue(result(board, move)) if temp < v: v = temp best = move return best def MaxValue(board): if terminal(board): return utility(board), None v = float('-inf') for move in actions(board): v = max(v, MinValue(result(board, move))) returndef MinValue(board): if terminal(board): return utility(board), None v = float('inf') for move in actions(board): v = min(v, MaxValue(result(board, move))) return v
我得到了这个确切的错误消息
TypeError: ‘>’ not supported between instances of ‘tuple’ and ‘float’
回答:
首先,MinValue和MaxValue函数存在问题,它们有时会返回两个值而不是一个值。
然后,出现了同样的TypeError,这次是在比较NoneType变量和浮点数时出现了问题。结果发现只是一个小错误,因为我的MaxValue函数没有返回任何值。