Python - Determine Tic-Tac-Toe Winner
<p>I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)</p>

<p>I have written the following function to do so:</p>

<blockquote>
  <p>This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardcoding.</p>
</blockquote>

<pre><code>def iswinner(board, decorator):
    win = True
    for row in range(len(board)):
        for col in range(len(board)):
            if board[row][col] == decorator:
                win = True
            else:
                win = False
                break
</code></pre>

<p>Where "board" is a 2D array of size n^2 and "decorator" is the "X" or "O" value</p>

<p>What I hope to accomplish is that the function loops through the 2D array's rows. Then loops through the values in each row. If that element matches the "decorator" then it continues and checks the next but if it doesn't, then it breaks from the first loop and goes to the next row. It does this until it finds n elements in the same row. Then it would give a bool value of True otherwise False.</p>

<p>The code doesn't seem to do that and even when I checked with the following "board" it gave me an output of "True"</p>

<blockquote>
<pre><code>check_list = [['O', 'X', 'X'],
              ['O', 'X', 'O'],
              ['O', 'X', 'X']]
</code></pre>
</blockquote>

<p>Thank you so much!</p>

<p>Best,
Seyed</p>

<p>One way to do this would be to create a set (a generator function would be even better) of all the possible index combinations to check for the win.  Then loop through those index combinations and check if they all contain the same value, if so, then it's a win.</p>

<pre><code>def win_indexes(n):
    # Rows
    for r in range(n):
        yield [(r, c) for c in range(n)]
    # Columns
    for c in range(n):
        yield [(r, c) for r in range(n)]
    # Diagonal top left to bottom right
    yield [(i, i) for i in range(n)]
    # Diagonal top right to bottom left
    yield [(i, n - 1 - i) for i in range(n)


def is_winner(board, decorator):
    n = len(board)
    for indexes in win_indexes(n):
        if all(board[r][c] == decorator for r, c in indexes):
            return True
    return False
</code></pre>

python arrays loops boolean break