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>You can just make a set of each row, and check its length. If it contains only one element, then the game has been won.</p>

<pre><code>def returnWinner(board):
    for row in board:
        if len(set(row)) == 1:
            return row[0]
    return -1
</code></pre>

<p>This will return "O" if there is a full line of "O", "X" if there is a line of "X", and -1 otherwise.</p>

<p>Below is the code of a full Tic-Tac-Toe checker, it should not be hard to understand, but do not hesitate to ask:</p>

<pre><code>import numpy as np

def checkRows(board):
    for row in board:
        if len(set(row)) == 1:
            return row[0]
    return 0

def checkDiagonals(board):
    if len(set([board[i][i] for i in range(len(board))])) == 1:
        return board[0][0]
    if len(set([board[i][len(board)-i-1] for i in range(len(board))])) == 1:
        return board[0][len(board)-1]
    return 0

def checkWin(board):
    #transposition to check rows, then columns
    for newBoard in [board, np.transpose(board)]:
        result = checkRows(newBoard)
        if result:
            return result
    return checkDiagonals(board)


a = [['X', 'A', 'X'],
     ['A', 'X', 'A'],
     ['A', 'X', 'A']]

print(checkWin(a))
</code></pre>

<p>Note that this works regardless of the symbols you choose to put in your tic-tac-toe ("O" &amp; "X" is as fine as "bloop" &amp; "!"), and for any size of grid, as long as it is a square.</p>

python arrays loops boolean break