Python编写井字棋游戏第4、113、130行出现TypeError报错求解
错误根源
你遇到的TypeError是传入insertLetter的pos参数为None导致的,问题根因来自两处代码错误:
- IsWinner函数逻辑完全失效:当前代码第一行就执行return,后续所有获胜条件判断永远不会执行,且所有获胜条件之间没有用
or连接。只有第一行(位置1、2、3)全为对应字母时函数返回True,其他所有情况函数默认返回None。后续电脑落子逻辑中判断获胜的条件全部失效,最终导致computerMove函数无显式返回值,默认返回None,传入insertLetter触发类型错误。 - isBoardFull函数缩进错误:else块缩进层级少于if块,直接运行会先报缩进语法错误。
修复方案
- 修正IsWinner函数,将所有获胜条件用
or连接后统一返回:
def IsWinner(b,l): return (b[1] == l and b[2] == l and b[3] == l) or \ (b[4] == l and b[5] == l and b[6] == l) or \ (b[7] == l and b[8] == l and b[9] == l) or \ (b[1] == l and b[4] == l and b[7] == l) or \ (b[2] == l and b[5] == l and b[8] == l) or \ (b[3] == l and b[6] == l and b[9] == l) or \ (b[1] == l and b[5] == l and b[9] == l) or \ (b[3] == l and b[5] == l and b[7] == l)
- 对齐isBoardFull函数的缩进,也可简化逻辑:
def isBoardFull(board): # 索引0永远为空,空格数<=1说明9个有效位置已填满 return board.count(' ') <= 1
- 可在
computerMove函数末尾加一行兜底返回return 0,避免极端场景下无返回值的问题。
内容的提问来源于stack exchange,提问作者Sumit
相关产品推荐
相关产品推荐

