检查tic-tac-toe - NumPy / Python的获胜者

时间:2017-10-18 04:08:23

标签: python numpy

我想检查一个井字游戏中所有可能的赢家条件,我该如何以功能方式重写?

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

1 个答案:

答案 0 :(得分:4)

使用anyall -

的组合
mask = board==player
out = mask.all(0).any() | mask.all(1).any()

要考虑diagonal个,请多做一些工作 -

out |= np.diag(mask).all() | np.diag(mask[:,::-1]).all()