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

Python开发Connect4游戏:负对角线胜利检测问题求助

Connect4负对角线胜利检测修复及代码优化

问题根源

你的负对角线检测逻辑存在两个核心问题:

  1. 索引方向错误:你测试的负对角线是行递减、列递增的方向(如(3,4)→(2,5)→(1,6)→(0,7)),但代码中check_negat_diag用的是row+j, col-j(行递增、列递减),读取的单元格和测试位置完全不匹配。
  2. 循环范围覆盖不全:原嵌套循环的范围只适配正对角线、横向和纵向的起始点,没有针对性覆盖负对角线的有效起始位置(需要从第4行及以下开始,才能向上取3个连续单元格)。

另外,代码中用list作为变量名会覆盖Python内置的list类型,属于不良编码习惯。

修复后的代码

board = [[' ' for j in range(8)] for i in range(8)]

def check_win(game_board, player):
    """
    Check if a player has won the game of Connect 4 on the given game board.

    Parameters:
    -----------
    game_board: list of lists
        The game board represented as a matrix of characters. Each element of the matrix represents a cell on the board,
        which can be empty (' '), or occupied by a player ('X' or 'O').
    player: str
        The player to check for a win. Must be either 'X' or 'O'.

    Returns:
    --------
    bool
    """
    rows = len(game_board)
    cols = len(game_board[0])
    win_sequence = [player] * 4

    # 检测横向胜利(同一行连续4个)
    for row in range(rows):
        for col in range(cols - 3):
            if game_board[row][col:col+4] == win_sequence:
                print("You have 4 in a row (horizontal)")
                return True

    # 检测纵向胜利(同一列连续4个)
    for col in range(cols):
        for row in range(rows - 3):
            column_slice = [game_board[row+j][col] for j in range(4)]
            if column_slice == win_sequence:
                print("You have 4 in a row (vertical)")
                return True

    # 检测正对角线胜利(行+1,列+1)
    for row in range(rows - 3):
        for col in range(cols - 3):
            diag_slice = [game_board[row+j][col+j] for j in range(4)]
            if diag_slice == win_sequence:
                print("You have 4 in a row (positive diagonal)")
                return True

    # 检测负对角线胜利(行-1,列+1)
    for row in range(3, rows):
        for col in range(cols - 3):
            diag_slice = [game_board[row-j][col+j] for j in range(4)]
            if diag_slice == win_sequence:
                print("You have 4 in a row (negative diagonal)")
                return True

    return False

# 测试负对角线胜利情况
board[3][4] = board[2][5] = board[1][6] = board[0][7] = "X"
print(check_win(board, "X"))  # 会打印胜利信息并返回True

可读性优化建议

  • 变量名规范化:将columns改为cols,避免使用list等Python内置类型名作为变量名,改用diag_slice、column_slice等具名变量。
  • 拆分逻辑模块:将四个方向的检测拆分为独立代码块,每个模块对应一种胜利类型,逻辑更清晰,便于单独调试。
  • 预定义胜利序列:提前创建win_sequence = [player]*4,避免重复计算,简化代码判断逻辑。
  • 利用列表切片:横向检测直接使用game_board[row][col:col+4],比列表推导式更简洁高效。
  • 添加类型提示:给函数参数和返回值添加类型提示(如def check_win(game_board: list[list[str]], player: str) -> bool:),增强代码可读性。
  • 删除冗余判断:循环范围已确保索引不会越界,无需保留原列表推导式中的0 <= ...边界判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:37:50