How to create a formula that checks who won a tic-tac-toe game without lots of if statements?
<p>I have the following code and feel it could be more efficient. Meaning this is 3x3 board and could be done manually but what if it were a 30x30 board or bigger?</p>

<pre><code>x = [[1, 2, 0],[2, 1, 0],[2, 1, 0]]

for y in range (3):
    if ((x[0][0] == x[1][0] == x[2][0] == y) or

    (x[0][1] == x[1][1] == x[2][1] == y) or

    (x[0][2] == x[1][2] == x[2][2] == y) or

    (x[0][0] == x[0][1] == x[0][2] == y) or

    (x[1][0] == x[1][1] == x[1][2] == y) or

    (x[2][0] == x[2][1] == x[2][2] == y) or

    (x[0][0] == x[1][1] == x[2][2] == y) or

    (x[0][2] == x[1][1] == x[2][0] == y)):

        if y==1:
            print('Player 1 won!!!')
        if y==2:
            print('Player 2 won!!!')
        if y==0:
            print('Nobody won')
</code></pre>

<p>Is there a way to make the condition part better?</p>

<p>If you don't mind about importing numpy, this would work for any square grid and any number of player:</p>

<pre><code>import numpy as np

def check(arr):
    def check_one_dim(arr):
        for player in np.arange(Nplayer)+1:
        # instead of Nplayer you could write arr.max()
            arrtest = arr == player
            s = arrtest.astype(int).prod(axis=0)
            t = arrtest.diagonal().astype(int).prod()
            if (s == 1).any() or t == 1:
                return player
        else:
            return 0
    return max(check_one_dim(arr), check_one_dim(arr[::-1].T))

Nplayer = 2
x = np.array([[1, 2, 0],[2, 1, 0],[2, 1, 0]])
winner = check(x)
if winner &gt; 0:
    print("Player {}").format(winner)
else:
    print("No winner")
</code></pre>

<p>I am not sure it is faster, but there is less "ifs" :)</p>

python