''' :author: Aaron Cass ''' def create(rows = None): """ Creates a tictactoe board with given cell values. If no initial cell values are given, creates an empty tictactoe board. :param cells: A list of 3 3-character strings, where each character is either 'X', 'O', or ' '. Each of the 3-character strings represents a row of the tictactoe board. :return: a tictactoe board with those values """ board = [] if rows is None: empty_row = [' ', ' ', ' '] for i in range(3): board.append(empty_row) else: for i in range(3): row = [] for j in range(3): row.append(rows[i][j]) board.append(row) return board def place_piece(board, i, j, piece): """ Places a piece (either 'X' or 'O') on the board. :param board: The board to modify :param i: The row in which to place a piece (0, 1, or 2) :param j: The column in which to place a piece (0, 1, or 2) :param piece: The piece to place ('X' or 'O') """ board[i][j] = piece def clear_cell(board, i, j): """ Clears a cell on the tictactoe board. :param board: The board to modify :param i: The row with the cell to clear :param j: The column with the cell to clear """ place_piece(board, i, j, ' ') def _row_as_string(row): str = '' for column in row[:-1]: str += column + ' | ' str += row[-1] return str def as_string(board): """ Produces a string representation of a board, returns it. :param board: The board to show :return: The string version of the board. """ result = '' for row in board[:-1]: result += _row_as_string(row) result += '\n----------\n' result += _row_as_string(board[-1]) result += '\n' return result def show(board): """ Prints the board. :param board: The tictactoe board to print """ print(as_string(board)) def _three_in_row(board, player, start_x, start_y, dx, dy): """ Determines if a player has three in a row, starting from a starting position (start_x, start_y) and going in the direction indicated by (dx, dy) """ x = start_x; y = start_y for i in range(0,3): if board[y][x] != player: return False x += dx; y += dy return True def _is_winner(board, player): """Returns True if and only if the given player has won""" for i in range(0, 3): if (_three_in_row(board, player, 0, i, 1, 0) or _three_in_row(board, player, i, 0, 0, 1)): return True return (_three_in_row(board, player, 0, 0, 1, 1) or _three_in_row(board, player, 0, 2, 1, -1) ) def get_winner(board): """ Determines if there is a winner and returns the player who has won. :param board: A tictactoe board. :return: 'X' if player X is the winner; 'O' if player O is the winner; None if there is no winner. """ if _is_winner(board, 'X'): return 'X' elif _is_winner(board, 'O'): return 'O' else: return None