Python井字棋check_win函数失效求助:无法检测胜负
问题诊断与修复方案
你的井字棋获胜检测完全失效,核心原因是all_wins定义错误,同时存在几处逻辑小bug,下面逐一说明并修复:
1. 核心问题:all_wins的定义逻辑错误
你初始化all_wins时,直接取了初始user_input的切片并额外用列表包裹,导致两个致命问题:
- 切片是静态副本:后续
user_input更新时,all_wins里的内容不会同步变化,永远是初始的空格字符串。 - 结构错误:每个获胜组合被包装成单元素列表(比如
[" "]),而非三个独立字符的列表,j.count(player)永远不可能等于3。
正确的all_wins应该定义为获胜位置的索引组合,这样每次检测时可以动态从当前棋盘取值:
# 定义所有获胜的索引组合(每行、每列、两条对角线) all_wins = [ [0,1,2], [3,4,5], [6,7,8], # 行 [0,3,6], [1,4,7], [2,5,8], # 列 [0,4,8], [2,4,6] # 对角线 ]
2. 修复check_win函数逻辑
基于上面的索引组合,修改函数动态获取当前棋盘对应位置的字符,判断是否全部为当前玩家标记:
def check_win(player): global loop_counter for combo in all_wins: # 取出当前组合的三个位置字符 chars = [user_input[i] for i in combo] if all(c == player for c in chars): print(f"{player} wins") loop_counter += 1 return # 找到获胜组合后直接返回,无需继续遍历
3. 其他需要修正的小bug
(1)坐标范围判断错误
原代码0 < coor1 and coor2 < 4只限制了coor2的上限,coor1的上限没约束,改为:
if 0 < coor1 < 4 and 0 < coor2 < 4:
(2)单元格占用判断逻辑错误
原代码elif user_input[...] == "X" or "O"是语法错误,"O"本身为布尔真,条件永远成立,改为:
elif user_input[pos] in ("X", "O"):
(3)输入处理重复问题
原代码捕获ValueError后再次调用input(),会导致后续逻辑跳过一次输入处理,改为直接continue让循环重新获取输入:
except ValueError: print("You should enter numbers!") continue
修复后的完整代码
user_input = " " # 9 empty spaces, representing the empty grid def board(): print("---------") print("|", user_input[0], user_input[1], user_input[2], "|") print("|", user_input[3], user_input[4], user_input[5], "|") print("|", user_input[6], user_input[7], user_input[8], "|") print("---------") # 定义所有获胜的索引组合 all_wins = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def check_win(player): global loop_counter for combo in all_wins: chars = [user_input[i] for i in combo] if all(c == player for c in chars): print(f"{player} wins") loop_counter += 1 return board() turn_counter = 1 loop_counter = 0 while loop_counter < 1: user_step = input() try: new_step_list = [int(x) for x in user_step.split(" ")] except ValueError: print("You should enter numbers!") continue # 确保输入是两个坐标 if len(new_step_list) != 2: print("Please enter two coordinates separated by space!") continue coor1, coor2 = new_step_list try: pos = (coor1 - 1) * 3 + (coor2 - 1) if 0 < coor1 < 4 and 0 < coor2 < 4: if user_input[pos] == " ": list_of_chars = list(user_input) list_of_chars[pos] = "X" if turn_counter % 2 == 1 else "O" user_input = "".join(list_of_chars) turn_counter += 1 elif user_input[pos] in ("X", "O"): print("This cell is occupied! Choose another one!") continue else: print("Coordinates should be from 1 to 3!") continue except IndexError: print("Coordinates should be from 1 to 3!") continue check_win("X") check_win("O") # 检查平局 if " " not in user_input: print("Draw") loop_counter += 1 board()
内容的提问来源于stack exchange,提问作者ivanmol05
相关产品推荐
相关产品推荐

