首页 > 解决方案 > 在 Python 中查找井字游戏的结果

问题描述

我正在尝试编写一个函数来显示谁是井字游戏中的赢家。如果 X 是它返回的获胜者X,如果 O 是它返回的获胜者,O并且对于平局,它返回布尔值None 我尝试的内容适用于某些情况,但对于下面给出的测试用例失败请帮助。

def check_winner(tuples):
    for row in range(0, len(tuples)):
        print(tuples[row])
        for col in range(0,3):

            #check for row win
            if tuples[row][0] == tuples[row][1] == tuples[row][2]:
                print("1 ")
                # return tuples[row][0];
            #check for col win
            if tuples[0][col] == tuples[1][col] == tuples[2][col]:
                print("2")
                return tuples[row][0];
            # For diagonal
            if tuples[0][0] == tuples[1][1] == tuples[2][2]:
                return tuples[0][0]
            if tuples[0][2] == tuples[1][1] == tuples[2][0]:
                return tuples[2][0]

对于下面的测试用例

# O wins
test1 = (('X', 'O', 'O'),
        (None, 'O', 'X'),
        ('X', 'O', 'X'))
# X Wins
test2 = (('X', 'X', 'O'),
        (("O", 'X', 'O'),
        ('O', 'X', 'X'))

调用函数

print(check_winner(test1))
print(check_winner(test2))

应该分别返回 O 和 X

标签: pythontuples

解决方案


return tuples[row][0];在第二个 if 语句中返回。tuples[0][col]如果你想返回获胜者的价值,它应该是这样的。

您不需要嵌套 for 循环来检查行和列。您应该检查的每个只有 3 个。

试试这个:

def check_winner(tuples):
    for line in range(3):
            #check for row win
            if tuples[line][0] == tuples[line][1] == tuples[line][2]:
                print("1 ")
                return tuples[line][0];
            #check for col win
            if tuples[0][line] == tuples[1][line] == tuples[2][line]:
                print("2")
                return tuples[0][line];
    # For diagonal
    if tuples[0][0] == tuples[1][1] == tuples[2][2]:
        return tuples[0][0]
    if tuples[0][2] == tuples[1][1] == tuples[2][0]:
        return tuples[2][0]

推荐阅读