基于Minimax算法的井字棋AI不合理走法问题求助
井字棋Minimax算法问题修复方案
核心问题分析
1. 评分逻辑完全倒置
当前代码中,minimax函数设定X获胜返回1、O获胜返回-1,但AI扮演的是O角色。Minimax算法里,AI作为最大化玩家应追求更高分数,对手X作为最小化玩家追求更低分数,这一倒置逻辑会让AI主动规避自身胜利,反而帮助X获胜,是最关键的错误。
2. make_best_move中Minimax调用参数错误
为AI(O)计算最优落子时,落子O后应模拟对手X的回合,但代码中固定传入player="O",导致递归逻辑混乱,无法正确模拟双方决策过程。
3. Depth参数逻辑不合理
初始调用make_best_move时传入depth=-1,递归中每次depth+1,该参数永远无法触发终止条件,虽井字棋递归深度有限不会栈溢出,但不符合Minimax深度控制的常规逻辑。
修复后的完整代码
import random class TicTacToe: def __init__(self): """Initialize with empty board""" self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def show(self): """Format and print board""" print(""" {} | {} | {} ----------- {} | {} | {} ----------- {} | {} | {} """.format(*self.board)) def clearBoard(self): self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def whoWon(self): if self.checkWin() == "X": return "X" elif self.checkWin() == "O": return "O" elif self.gameOver() == True: return "Nobody" def availableMoves(self): """Return empty spaces on the board""" moves = [] for i in range(0, len(self.board)): if self.board[i] == " ": moves.append(i) return moves def getMoves(self, player): """Get all moves made by a given player""" moves = [] for i in range(0, len(self.board)): if self.board[i] == player: moves.append(i) return moves def makeMove(self, position, player): """Make a move on the board""" if self.board[position] == " ": self.board[position] = player return True elif self.board[position] != " " and player is " ": self.board[position] = player return True else: print("Invalid Move") return False def checkWin(self): """Return the player that wins the game""" combos = ([0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]) for player in ("X", "O"): positions = self.getMoves(player) for combo in combos: win = True for pos in combo: if pos not in positions: win = False if win: return player def gameOver(self): """Return True if X wins, O wins, or draw, else return False""" if self.checkWin() != None: return True for i in self.board: if i == " ": return False return True def minimax(self, player=None): # 修复评分逻辑:AI是O,O获胜返回1,X获胜返回-1,平局0 win = self.whoWon() if win == "X": return -1 if win == "O": return 1 if self.gameOver(): return 0 if player == "O": # AI(O)为最大化玩家,追求最高分数 best = -9999 for i in self.availableMoves(): self.board[i] = player score = self.minimax(player=changePlayer(player)) self.board[i] = " " best = max(best, score) return best else: # X为最小化玩家,追求最低分数 best = 9999 for i in self.availableMoves(): self.board[i] = player score = self.minimax(player=changePlayer(player)) self.board[i] = " " best = min(best, score) return best def changePlayer(player): """Returns the opposite player given any player""" if player == "X": return "O" else: return "X" def make_best_move(board, player): bestMove = -1 bestScore = -9999 # 为AI(O)寻找最高分数的落子 for i in range(0, 9): if board.board[i] == " ": board.board[i] = player # 落子后模拟对手X的回合 moveVal = board.minimax(player=changePlayer(player)) board.board[i] = " " if moveVal > bestScore: bestScore = moveVal bestMove = i print("The value of the best Move is :", bestScore) print() return bestMove # 游戏运行逻辑 if __name__ == '__main__': game = TicTacToe() game.show() while game.gameOver() == False: isValid = False while not isValid: person_move = int(input("You are X: Choose number from 1-9: ")) isValid = game.makeMove(person_move - 1, "X") game.show() if game.gameOver() == True: break print("Computer choosing move...") ai_move = make_best_move(game, "O") print(f"ai move:{ai_move}") game.makeMove(ai_move, "O") game.show() print("Game Over. " + game.whoWon() + " Wins")
修复要点说明
- 修正评分逻辑:将O获胜评分改为1,X获胜改为-1,确保AI主动追求胜利,对手尽量规避失败。
- 调整Minimax调用参数:落子O后传入
changePlayer(player)(即X),正确模拟双方交替决策过程。 - 移除冗余depth参数:井字棋最多9步,递归深度有限,无需额外深度限制,简化逻辑。
- 明确玩家决策逻辑:O作为最大化玩家取分数最大值,X作为最小化玩家取分数最小值,契合Minimax算法核心思想。
内容的提问来源于stack exchange,提问作者Devology Tasks
相关产品推荐
相关产品推荐

