Connect4四子棋Python代码对角线检测失效问题排查求助
问题排查与修复方案
核心问题分析
你的对角线检测逻辑只覆盖了左上→右下的单一方向,完全漏掉了Connect4中另一种关键的对角线获胜场景:右上→左下的连线。这正是第一个测试用例里的X对角线无法被识别的根本原因。
另外代码还存在一个细节问题:找到获胜者后没有提前终止循环,后续检测可能覆盖正确结果(比如同时存在多种获胜情况时,后检测到的会覆盖先找到的)。
修复后的完整代码
def check_winner(tuples): # 检查水平方向获胜 for row in range(6): for col in range(4): current = tuples[row][col] if current is not None and current == tuples[row][col+1] == tuples[row][col+2] == tuples[row][col+3]: return current # 检查垂直方向获胜 for col in range(7): for row in range(3): current = tuples[row][col] if current is not None and current == tuples[row+1][col] == tuples[row+2][col] == tuples[row+3][col]: return current # 检查左上→右下对角线获胜 for row in range(3): for col in range(4): current = tuples[row][col] if current is not None and current == tuples[row+1][col+1] == tuples[row+2][col+2] == tuples[row+3][col+3]: return current # 新增:检查右上→左下对角线获胜 for row in range(3, 6): for col in range(4): current = tuples[row][col] if current is not None and current == tuples[row-1][col+1] == tuples[row-2][col+2] == tuples[row-3][col+3]: return current # 无获胜者时返回None return None
关键修复点说明
- 补充反方向对角线检测:新增的循环针对右上→左下的对角线,起始行从索引3开始(需要向上走3步到索引0),列范围保持0到3(需要向右走3步到索引6),通过
row-1和col+1的组合实现反向对角线的连线检测。 - 提前返回优化:一旦检测到有效四子连线,立即返回当前玩家,避免无效循环和结果被覆盖的问题;同时增加
current is not None判断,防止空位置被误判。 - 代码简化:将重复的"O"和"X"判断合并为通过
current变量统一检查,减少冗余代码。
内容的提问来源于stack exchange,提问作者Space88
相关产品推荐
相关产品推荐

