井字棋开发求助:已占用位置仍可落子的问题排查
井字棋重复落子问题修复方案
你的代码存在两个核心问题,导致已标记位置仍能重复落子:
1. runGame方法错误创建新实例
在runGame内部,你重新初始化了Tictactoe实例test,这意味着外部调用runGame时,原实例的made_moves和board完全不会被使用,每次落子都在新实例上操作,自然无法记录已落子位置。
修复代码:
def runGame(self): self.newBoard() # 使用当前实例初始化棋盘 for i in range(9): self.makeMove() self.renderBoard() print("Game Over, it is a draw")
2. made_moves的存储与检查逻辑不匹配
- 你用
self.made_moves += (xcoor,ycoor)时,列表的+=操作会将元组(x,y)拆分为两个独立元素添加,比如落子(0,0)后,made_moves会变成[0, 0],而非预期的[(0, 0)]。 - 后续检查
[xcoor,ycoor] in self.made_moves是在判断一个列表是否存在于存储单个数字的列表中,永远不会匹配,导致重复落子判断失效。
修复代码:
def makeMove(self): marker = "O" xcoor,ycoor = self.getMove() move = (xcoor, ycoor) # 统一用元组存储坐标 # 无需区分首次落子,统一执行检查 if move in self.made_moves: print(f"The position at {move} is already full, please try again.") self.makeMove() # 递归调用让用户重新输入,避免跳过回合 else: self.board[xcoor][ycoor] = marker self.made_moves.append(move) # 用append添加完整元组
额外优化建议
getMove方法需处理非法输入,确保返回有效坐标:
def getMove(self): print("Coordinates must range from 0 to 2, 0 corresponding to the first row/column, onwards") while True: try: xcoor = int(input("What is your x coordinate?")) ycoor = int(input("What is your y coordinate?")) if xcoor in {0,1,2} and ycoor in {0,1,2}: return xcoor,ycoor print("Coordinates must be between 0 and 2, please try again.") except ValueError: print("Please enter valid integer coordinates.")
main方法需定义为类外的普通函数,避免调用报错:
def main(): test = Tictactoe("playerone", "playertwo") test.runGame() if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者n00bcoder_24
相关产品推荐
相关产品推荐

