You need to enable JavaScript to run this app. Python井字棋:如何复制列表、调用带返回值函数及简化check_win
优惠活动
大模型
产品
解决方案
定价
更多

Python井字棋:如何复制列表、调用带返回值函数及简化check_win

独立棋盘实例生成方法

Python中列表是可变引用类型,直接执行new_graph = graph仅复制对象内存引用,两个变量指向同一块内存地址,修改任意一个变量都会同步影响另一个。要生成完全独立的棋盘副本,可采用以下两种方式:

  • 逐行浅拷贝(适配当前嵌套列表结构,无需导入额外模块):new_graph = [row.copy() for row in graph]
  • 通用深拷贝(适合任意嵌套结构,需导入copy模块):导入copy后执行new_graph = copy.deepcopy(graph)
check_win函数简化方案

原函数重复书写所有获胜路径的判断逻辑,可通过预定义获胜路径、统一校验规则大幅缩减代码量:

  1. 提前定义所有获胜位置的坐标组合(3行、3列、2对角线共8条路径):
WIN_PATHS = [
    [(0,0), (0,2), (0,4)],  # 顶行
    [(2,0), (2,2), (2,4)],  # 中行
    [(4,0), (4,2), (4,4)],  # 底行
    [(0,0), (2,0), (4,0)],  # 左列
    [(0,2), (2,2), (4,2)],  # 中列
    [(0,4), (2,4), (4,4)],  # 右列
    [(0,0), (2,2), (4,4)],  # 左上到右下对角线
    [(0,4), (2,2), (4,0)],  # 右上到左下对角线
]
  1. 重写判断逻辑,无需区分X/O重复书写判断:
def check_win(new_graph):
    for path in WIN_PATHS:
        cell_vals = [new_graph[r][c] for r, c in path]
        # 三个位置符号一致且非空格,即为获胜
        if cell_vals[0] == cell_vals[1] == cell_vals[2] and cell_vals[0] != ' ':
            winner = "Player 1" if cell_vals[0] == 'X' else "Player 2"
            print(f"{winner} wins!")
            return True
    return False
现有代码其他可优化点
  • place_spot函数的循环逻辑存在缺陷:原代码的while answer != 'good'循环不会重新接收用户输入的位置,输入非法值会直接死循环。可通过位置映射表简化逻辑,同时增加已占用位置校验:
POS_MAP = {
    '1': (0,0), '2': (0,2), '3': (0,4),
    '4': (2,0), '5': (2,2), '6': (2,4),
    '7': (4,0), '8': (4,2), '9': (4,4),
}

def place_spot(symbol, new_graph): 
    while True:
        pos = input("Which spot do you want to place your piece (1-9)? ")
        if pos not in POS_MAP:
            print("Please enter a number (1-9).")
            continue
        r, c = POS_MAP[pos]
        if new_graph[r][c] != ' ':
            print("This spot is already taken, choose another.")
            continue
        new_graph[r][c] = symbol
        break
  • flip_player函数可通过三元表达式简化,无需多分支赋值:
def flip_player(player):
    return 'player2' if player == 'player1' else 'player1'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.30 17:24:03