即使语句为True,我的函数也没有返回True

时间:2019-04-07 22:44:39

标签: python

我正在做我的第一个里程碑项目,如果满足获胜条件,我将无法使函数返回True。如果在板上连续3次看到“ X”或“ O”标记(井字棋),则函数应返回True。谁能澄清为什么它不返回True或False?

我首先将代码写为

return (board[7] == mark and board[8] == mark and board[9] == mark)

,但不会返回True。因此,我尝试对所有可能的获胜结果使用if和else语句,但我仍然无法使它返回True。只有当我用打印替换了return时,它才起作用。该函数接受两个参数,Board和Mark。

委员会是一个列表,出于测试目的,我使用了test_board = ['#','X','O','X','O','X','O','X','O','X']

我正在使用Visual Studio代码和终端来运行我的代码。

def win_check(board, mark):
    return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across top
            (board[4] == mark and board[5] == mark and board[6] == mark) or # across middle
            (board[1] == mark and board[2] == mark and board[3] == mark) or # across bottom
            (board[7] == mark and board[4] == mark and board[1] == mark) or # down left
            (board[8] == mark and board[5] == mark and board[2] == mark) or # down middle
            (board[9] == mark and board[6] == mark and board[3] == mark) or # down right
            (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
            (board[9] == mark and board[5] == mark and board[1] == mark))   # diagonal 

然后我尝试使用if和else语句:

def win_check(board, mark):
    if (board[7] == mark and board[8] == mark and board[9] == mark):
      return True # across the top
    elif(board[4] == mark and board[5] == mark and board[6] == mark):
      return True # across the middle
    elif(board[1] == mark and board[2] == mark and board[3] == mark):
      return True # across the bottom
    elif(board[7] == mark and board[4] == mark and board[1] == mark):
      return True # down the middle
    elif(board[8] == mark and board[5] == mark and board[2] == mark):
      return True # down the middle
    elif(board[9] == mark and board[6] == mark and board[3] == mark):
      return True # down the right side
    elif(board[7] == mark and board[5] == mark and board[3] == mark):
      return True # diagonal
    elif(board[9] == mark and board[5] == mark and board[1] == mark):
      return True # diagonal
    else :
      return False

如果获胜条件为True,我希望输出为True

0 个答案:

没有答案