問題描述
我在使用 Turtle 圖形檢查井字遊戲中的獲勝者時遇到了一些問題 (I am having some problems checking the winner in a tic tac toe game using Turtle graphics)
def isWinner (square) :
(square[0] and square[1] and square[2])
(square[3] and square[4] and square[5])
(square[6] and square[7] and square[8])
(square[0] and square[3] and square[6])
(square[1] and square[4] and square[7])
(square[2] and square[5] and square[8])
(square[0] and square[4] and square[8])
(square[2] and square[4] and square[6])
這是我所到之處,但我真的不知道要從這裡走。任何幫助都將不勝感激。:)
參考解法
方法 1:
I think you are trying to send the list square
to the function isWinner
and want to check if the tic‑tac‑toe values match on rows or columns or diagonal.
To do this, you need to change the function as follows:
def isWinner (square):
if (square[0] == square[1] == square[2]) \
or (square[3] == square[4] == square[5]) \
or (square[6] == square[7] == square[8]) \
or (square[0] == square[3] == square[6]) \
or (square[1] == square[4] == square[7]) \
or (square[2] == square[5] == square[8]) \
or (square[0] == square[4] == square[8]) \
or (square[2] == square[4] == square[6]):
return True
else: return False
Assumption here is that square is a list or dictionary and the values in the index or key value represents a O
or X
.
A few examples:
print ('''0,0,0
X,0,X
X,X,X''')
print (isWinner(['0','0','0','X','0','X','X','X','X']))
print ('''X,0,0,
X,0,X,
X,0,X''')
print (isWinner(['X','0','0','X','0','X','X','0','X']))
print ('''X,0,0,
0,X,X,
X,0,0''')
print (isWinner(['X','0','0','0','X','X','X','0','0']))
Output:
#last row has all X. Result = True
0,0,0
X,0,X
X,X,X
True
#first column has all X, so is second column with all 0. Result = True
X,0,0,
X,0,X,
X,0,X
True
#no match row wise, column wise, or diagonal. Result = False
X,0,0,
0,X,X,
X,0,0
False
(by Loui、Joe Ferndz)