""" Evaluate a tictactoe board """ def evaluate_board(board): """ Test the board for the 8 possible winning combinations and return the winner as soon as it's found. """ status = _check_horizontals(board[:]) if status: return status status = _check_verticals(board[:]) if status: return status status = _check_diagonal(_left_rotate(board[:])) if status: return status status = _check_diagonal(_right_rotate(board[:])) if status: return status return "no winner" def _check_horizontals(board): status = None for row in board: if row[0] == row[1] == row[2]: if row[0] is not None: return f'{row[0]} wins' return status def _check_verticals(board): transposed_board = _transpose_board(board) return _check_horizontals(transposed_board) def _check_diagonal(board): status = _check_verticals(board) if status: return status def _right_rotate(board): """ 'rotates' the top and center rows so that a diagonal winnder can be evaluated as a vertical winner the top-left to bottom-right diagonal is being evaluated in this rotation """ rotated_board = board rotated_board[0] = _rotate_board(2, board[0][:]) rotated_board[1] = _rotate_board(1, board[1][:]) return rotated_board def _left_rotate(board): """ 'rotates' the center and bottom rows so that a diagonal winner an be evaluated as a vertical winner the top-right to bottom-left diagonal is being evaluated in this rotation """ rotated_board = board rotated_board[1] = _rotate_board(1, board[1][:]) rotated_board[2] = _rotate_board(2, board[2][:]) return rotated_board def _rotate_board(positions, row): for _ in range(positions): row.pop(0) for _ in range(positions): row.append(None) return row def _transpose_board(board): new_board = [[None, None, None], [None, None, None], [None, None, None]] for row_i, row in enumerate(board): for cell_i, value in enumerate(row): new_board[cell_i][row_i] = value return new_board