简化Python如果声明

时间:2015-01-14 20:53:27

标签: python if-statement terminal tic-tac-toe

我是python的初学者,我正在终端创建一个双人tic tac toe游戏。总的来说,这段代码需要139行,(这下面是我遇到问题的代码的相关部分),然而,这个CheckWin函数占用了大约40行代码,我认为这相当于金额相当多这段代码中的行,并考虑到它执行一些基本的功能。基本上,在游戏中,此功能检查行,列或对角线是否具有三个X或三个O,如果是,则将X分配给获胜者,将O分配给获胜者。无论如何,这是代码。

X = "X"
O = "O"
empty = " " 
S = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

def CheckWin(S):
    global winner
    winner = ""
    if S[0] == S[1] == S[2] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[3] == S[4] == S[5] != empty:
        if S[3] == X:
            winner = X
        if S[3] == O:
            winner = O
    if S[6] == S[7] == S[8] != empty:
        if S[6] == X:
            winner = X
        if S[6] == O:
            winner = O
    if S[0] == S[3] == S[6] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[1] == S[4] == S[7] != empty:
        if S[1] == X:
            winner = X
        if S[1] == O:
            winner = O
    if S[2] == S[5] == S[8] != empty:
        if S[2] == X:
            winner = X
        if S[2] == O:
            winner = O
    if S[0] == S[4] == S[8] != empty:
        if S[0] == X:
            winner = X
        if S[0] == O:
            winner = O
    if S[2] == S[4] == S[6] != empty:
        if S[2] == X:
            winner = X
        if S[2] == O:
            winner = O

基本上,我需要帮助使功能更加简单。但是,我不想消除X,O和赢家变量,也不想用列表S消除列表索引方法。尽管如此,有没有办法简化所有这些If语句,保留这些内容?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:0)

您的代码会查找“三人”的职位;你可能还有一个包含这个信息的对象:

trios = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))

然后CheckWin会遍历每一个三人组,做那个检查你正在做的事情,并且如果三重奏匹配则返回胜利者。这样,CheckWin将少于10行代码。

我不想全力以赴,因为我相信你能做到这一点:)

此外,CheckWin中不需要名为“winner”的全局变量;让CheckWin返回获胜者(或“”),并将结果存储在函数本身之外的变量中 即。

winner = CheckWin(S)

答案 1 :(得分:0)

您是否尝试过使用循环?

X, O = 'X', 'O'
S    = [X,O,X,O,X,O,O,X,O] # Test values
def CheckWin(S):
    index      = 0
    has_winner = False
    while index < len(S):
        print index
        if index <= 6: # after this point you won't find a winner (or you run this after every turn?)
            if (index % 3 == 0 and S[index] == S[index + 1] and S[index] == S[index + 2]): # horizontals
                has_winner = True
            elif index < 3: # verticals and diagonals (you only need the first row to know this)
                if (S[index] == S[(index + 3)] and S[index] == S[index + 6]) or \
                   (index == 0 and S[index] == S[4] and S[index] == S[8]) or \
                   (index == 2 and S[index] == S[4] and S[index] == S[6]):
                    has_winner = True
        if has_winner: # I'm using this to prevent duplicating code above (one if less)
            if S[index] in [X,O]:
                return S[index]
        index += 1
    return has_winner # If we have a winner but the X or O criterion isn't met, it returns False
winner = CheckWin(S)