You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python基于minimax算法的井字棋AI运行报错如何解决?

问题根因
  • 核心bug出在generate_possible_moves方法:你遍历位置索引时用了range(8),只会生成0~7共8个数字,漏掉了井字棋的最后一个位置索引8。
    当场上仅剩8号位置可落子时,该函数会返回空列表,此时minmax函数会走到非胜负、非平局的逻辑分支,生成的scores列表为空,调用max(scores)/min(scores)时就触发了ValueError: max() arg is an empty sequence报错。
  • 额外潜在问题:你自定义了RunTimeError异常类,但play_move方法中判断游戏结束时抛出的是Python内置的RuntimeError(大小写不一致),属于代码不规范问题,不会触发本次报错但建议同步修复。
修复方案

修改generate_possible_moves方法的遍历范围即可,可选修正异常类型:

def generate_possible_moves(self) -> list:
    '''Returns a list with all possible move indexes'''
    moves = []
    # 把range(8)改成range(9),覆盖0~8全部9个位置
    for num in range(9):
        if num not in self.moves_stack:
            moves.append(num)
    return moves

如果要修正异常类型,把play_move里的对应代码修改即可:

if self.game_state != 'RUNNING':
    # 改成你自定义的RunTimeError
    raise RunTimeError('Game already terminated')

内容的提问来源于stack exchange,提问作者Random_Pythoneer59

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 20:36:02