如何使用numpy来缩短我的代码,我检查你是否赢了
我需要找到一种方法来使用numpy来适应我的代码,因为它很长很难。我检查diag,horizontle和row,但我需要找到一种方法来缩短它与numpy
def checkHorizontle(board):
global winner
if board[0] == board[1] == board[2] and board[1] != "-":
winner = board[0]
return True
elif board[3] == board[4] == board[5] and board[3] != "-":
winner = board[3]
return True
elif board[6] == board[7] == board[8] and board[6] != "-":
winner = board[6]
return True
def checkRow(board):
global winner
if board[0] == board[3] == board[6] and board[0] != "-":
winner = board[0]
return True
elif board[1] == board[4] == board[7] and board[1] != "-":
winner = board[1]
return True
elif board[2] == board[5] == board[8] and board[2] != "-":
winner = board[2]
return True
def checkDiag(Board):
global winner
if board[0] == board[4] == board[8] and board[0] != "-":
winner = board[0]
return True
elif board[2] == board[4] == board[6] and board[2] != "-":
winner = board[2]
return True
当我试图找到一个解决办法时,我的头脑就决定放弃。我知道你可以用幻方来找到它和numpy乘法函数,但我不知道如何
3条答案
按热度按时间xn1cxnb41#
不需要numpy,你可以使用一个简单的循环:
0md85ypi2#
假设有一个这样的电路板,并想检查
X
是否获胜:您可以对行、列和对角线使用4个测试:
在测试中使用:
如果您想查看是否有玩家获胜:
llew8vvj3#
它很长很硬。。。。我得想办法用numpy缩短它
如果你的目标是让它变短,你不一定需要numpy。另一个想法是将棋盘表示为九个字符的字符串(每个字符是“X”,“O”或“.”),并使用正则表达式来测试是否获胜。
该正则表达式可以是:
示例实施方式: