import random import copy class TicTacToeBoard: def __init__(self, size): self.size = size self.current_mark = "X" # construct a new board that is size by size self.board = [] for i in range(self.size): self.board.append(["_"] * size) def add_mark(self, row, col): new_board = copy.deepcopy(self) new_board.board[row][col] = new_board.current_mark if new_board.current_mark == "X": new_board.current_mark = "O" else: new_board.current_mark = "X" return new_board def next_states(self): # fill in all the empty spaces we find as candidate next states next_states = [] for r in range(self.size): for c in range(self.size): if self.board[r][c] == "_": next_states.append(self.add_mark(r,c)) return next_states def is_goal(self): return self.has_diagonal_win() def has_diagonal_win(self): # check the diagonals if self.is_diagonal_all_mark("X") or \ self.is_diagonal_all_mark("O") or \ self.is_other_diagonal_all_mark("X") or \ self.is_other_diagonal_all_mark("O"): return True return False def is_diagonal_all_mark(self, mark): for i in range(self.size): if self.board[i][i] != mark: return False return True def is_other_diagonal_all_mark(self, mark): for i in range(self.size): if self.board[i][self.size - 1 - i] != mark: return False return True def __str__(self): board_string = " " # add the column indices at the top for i in range(self.size): board_string += str(i) + " " board_string += "\n" for i in range(self.size): board_string += str(i) + " " + str(self.board[i]) + "\n" return board_string def dfs(state): """Recursive depth first search implementation Input: Takes as input a state. The state class MUST have the following returned True) that can be reached from the input state. """ #if the current state is a goal state, then return it in a list if state.is_goal(): return [state] else: # else, recurse on the possible next states result = [] for s in state.next_states(): # append all of the s result += dfs(s) return result # uncomment this code when you're ready to test it out start_state = TicTacToeBoard(3) solutions = dfs(start_state) print("There were " + str(len(solutions)) + " solutions.\n") if( len(solutions) > 0 ): print(solutions[0])