如何为我的Connect 4现有代码编写胜利条件检测函数
适配现有代码的Connect 4胜利条件检测实现
现有代码规则对齐
你的代码已实现的棋盘逻辑为后续检测提供了明确的适配基础:
- 棋盘为6行7列的二维列表结构,索引规则为
board[行索引][列索引] - 行索引5对应棋盘最底部,行索引0对应棋盘最顶部,落子时从最底部向上遍历找空位
- 空位标记为
., 两名玩家的落子标识分别为x(玩家1)、o(玩家2)
可直接嵌入的胜利检测函数
该函数完全匹配现有代码的索引规则,无需修改原有落子、打印逻辑即可直接运行:
def check_win(tokentype): # 检查水平方向连续4个同色棋子 for row in range(6): for col in range(4): if board[row][col] == tokentype and board[row][col+1] == tokentype and board[row][col+2] == tokentype and board[row][col+3] == tokentype: return True # 检查垂直方向连续4个同色棋子 for col in range(7): for row in range(3): if board[row][col] == tokentype and board[row+1][col] == tokentype and board[row+2][col] == tokentype and board[row+3][col] == tokentype: return True # 检查左上到右下的主对角线方向连续4个同色棋子 for row in range(3): for col in range(4): if board[row][col] == tokentype and board[row+1][col+1] == tokentype and board[row+2][col+2] == tokentype and board[row+3][col+3] == tokentype: return True # 检查右上到左下的副对角线方向连续4个同色棋子 for row in range(3, 6): for col in range(4): if board[row][col] == tokentype and board[row-1][col+1] == tokentype and board[row-2][col+2] == tokentype and board[row-3][col+3] == tokentype: return True return False
嵌入方式
直接在原有游戏循环的落子、打印步骤后加入检测判断即可,同步补充基础的列范围校验、游戏终止逻辑,调整后的完整循环片段为:
tokenTypes = ['x', 'o'] game_over = False while not game_over: # 玩家1落子流程 column = int(input("Player 1, what column do you want to place your token in? ")) while column < 1 or column >7: column = int(input("请输入1-7范围内的列号:")) placement(tokenTypes[0]) printboard() if check_win(tokenTypes[0]): print("玩家1获胜!") game_over = True break # 玩家2落子流程 column = int(input("Player 2, what column do you want to place your token in?")) while column <1 or column >7: column = int(input("请输入1-7范围内的列号:")) placement(tokenTypes[1]) printboard() if check_win(tokenTypes[1]): print("玩家2获胜!") game_over = True break
适配说明
- 检测逻辑覆盖Connect 4规则中所有可能形成4连的方向,不存在漏判
- 棋盘规模仅为6行7列,该检测逻辑运算量极低,不会影响游戏运行流畅度
内容的提问来源于stack exchange,提问作者uselessglobble
相关产品推荐
相关产品推荐

