Trying to return all the rows, column and diagonals of a 3×3 board of noughts and crosses

I’ve managed to find all the information but i can’t extract it from my for loops as i need to make a program that can determine a winner if it sees three X’s or three O’s in a line. My board is laid out like this:

board = [['X', ' ', 'O'], ['X', 'X', ' '], ['X', ' ', 'X']]
def winner(board):
    """noughts and crosses game and checks if a row or column or diagonal is a winner"""
    for row_number in range(3):
        row_ = board[row_number]
    for col_number in range(3):
        column_ = list(board[0][col_number] + board[1][col_number] + board[2][col_number])
    for selected_diagonal in range(1):
        if selected_diagonal == 0:
            diagonal_0 = list(board[0][0] + board[1][1] + board[2][2])
        diagonal_1 = list(board[0][2] + board[1][1] + board[2][0])
    #total = row_ + column_ + diagonal_0 + diagonal_1
    print(row_)
    print(column_)
    print(diagonal_0)
    print(diagonal_1)
    #print(total)
    #total = total.split('/')
    #total.pop(-1)
    #return [tuple(map(int, sub.split(', '))) for sub in total]

Answer

You should move row_ and column_ initialization outside the loop, otherwise you rewrite these variables inside loop every iteration.

Corrected code down below:

Try it online!

board = [['X', ' ', 'O'], ['X', 'X', ' '], ['X', ' ', 'X']]

def winner(board):
    """noughts and crosses game and checks if a row or column or diagonal is a winner"""
    row_ = []
    for row_number in range(3):
        row_.append(board[row_number])
    column_ = []
    for col_number in range(3):
        column_.append(list(board[0][col_number] + board[1][col_number] + board[2][col_number]))
    for selected_diagonal in range(2):
        if selected_diagonal == 0:
            diagonal_0 = list(board[0][0] + board[1][1] + board[2][2])
        else:
            diagonal_1 = list(board[0][2] + board[1][1] + board[2][0])
    #total = row_ + column_ + diagonal_0 + diagonal_1
    print(row_)
    print(column_)
    print(diagonal_0)
    print(diagonal_1)
    #print(total)
    #total = total.split('/')
    #total.pop(-1)
    #return [tuple(map(int, sub.split(', '))) for sub in total]
    
winner(board)

Leave a Reply

Your email address will not be published. Required fields are marked *