井字棋Minimax算法无法识别败局及截图走步错误问题咨询
问题修复方案
1. 修正截图识别中的玩家标记拼写错误
在get_board方法中,你误将玩家标记写成了数字"0",但类定义中玩家标记是字母"O",这会导致player_move无法正确同步屏幕棋盘到内部棋盘,AI基于错误的棋盘状态计算走法,必然会选择错误位置。
修改代码:
def get_board(self): for key in self.dict_click_pos.keys(): pixel_color = pyautogui.screenshot().getpixel((self.dict_click_pos[key][0], self.dict_click_pos[key][1])) if pixel_color == dunkel: self.screen_board[key] = "O" # 将"0"改为"O" elif pixel_color == hell: self.screen_board[key] = "X" else: self.screen_board[key] = " "
2. 优化computer_move中的初始值设置
当前bestMove初始值为0,但棋盘位置的key范围是1-9,极端情况下会导致点击不存在的位置;同时初始值设置逻辑可能让AI忽略低评分但必须选择的阻止走法。修改为以下逻辑:
def computer_move(self): self.player_move() bestScore = -800 bestMove = None # 先获取第一个合法空位作为初始备选 for key in self.board.keys(): if self.board[key] == " ": bestMove = key break # 遍历所有空位计算最优走法 for key in self.board.keys(): if self.board[key] == " ": self.board[key] = self.computer score = self.minimax(self.board, False) self.board[key] = " " if score > bestScore: bestScore = score bestMove = key pyautogui.click(self.dict_click_pos[bestMove][0], self.dict_click_pos[bestMove][1])
3. 验证Minimax算法的评估逻辑(可选)
可以在computer_move的循环内添加打印,确认AI是否正确识别玩家的获胜威胁:
# 在computer_move的循环中添加 score = self.minimax(self.board, False) print(f"位置{key}的评分: {score}")
通过打印结果可直观验证AI是否正确计算出各走步的风险,确保优先选择能阻止玩家获胜的位置。
4. 修复has_won函数(可选)
当前has_won始终返回False,会导致外层循环无限运行。若需要正常结束游戏,可修改为:
def has_won(self): if self.check_win(self.board, self.player): print(f"{self.player} 获胜!") return True if self.check_win(self.board, self.computer): print(f"{self.computer} 获胜!") return True if self.check_draw(self.board): print("平局!") return True return False
内容的提问来源于stack exchange,提问作者xL1miT3
相关产品推荐
相关产品推荐

