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>Your solution doesn't work, so efficiency is a secondary issue.  Try:</p>

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

<p>You'll get two answers:</p>

<pre><code>Nobody won
Player 2 won!!!
</code></pre>

<p>When checking for no winners, you can't assume all zero in a row or a column means nobody won.  (Though that does work for diagonals.)</p>

<p>Here's an approach that should evaluate any N x N square:</p>

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

def winner(board):

    length = len(board)

    if all(x == board[0][0] for x in (x[dim][dim] for dim in range(1, length))):
        return board[0][0]

    if all(x == board[0][length - 1] for x in (x[dim][length - dim - 1] for dim in range(1, length))):
        return board[0][length - 1]

    for row in range(length):
        if board[row][0]:
            if all(x == board[row][0] for x in board[row][1:]):
                return board[row][0]

    for col in range(length):
        if board[0][col] and all(x == board[0][col] for x in (x[row][col] for row in range(1, length))):
            return board[0][col]

    return 0

y = winner(x)

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

<p>Though you'll clearly need to fully test it before relying on it!</p>

python