我在使用海龟图形检查井字游戏中的获胜者时遇到了一些问题


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]) 

我就到这里了,但我真的不知道该怎么走。任何帮助都会很感激。:)

我认为您正试图将列表square发送给函数isWinner,并想检查井字游戏值是否在行或列或对角线上匹配。

要做到这一点,您需要更改函数如下:

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

这里假设square是一个列表或字典,索引或键值中的值代表OX

几个例子:

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']))

输出:

#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

相关内容

最新更新