我想检查一个井字游戏中所有可能的赢家条件,我该如何以功能方式重写?
board = numpy.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
player = 1
if any([(board[0, :] == player).all(),
(board[:, 0] == player).all(),
(board[1, :] == player).all(),
(board[:, 1] == player).all(),
(board[2, :] == player).all(),
(board[:, 2] == player).all()]):
print('Win')
答案 0 :(得分:4)
使用any
和all
-
mask = board==player
out = mask.all(0).any() | mask.all(1).any()
要考虑diagonal
个,请多做一些工作 -
out |= np.diag(mask).all() | np.diag(mask[:,::-1]).all()