def test_get_updated_configuration(self): p = Puzzle(utils.board_from_file(file3)) p_copy = copy.deepcopy(p) p2 = p.get_updated_configuration("up") p2_expected = Puzzle(utils.board_from_file(file4)) self.assertEqual(p_copy, p) self.assertEqual(p2_expected, p2)
def changeState(offspring, index): puzzle = Puzzle(offspring.states[index - 1]) for i in range(index, CHROM_LEN): move = offspring.steps[i] puzzle.move(move) offspring.states[i] = puzzle.state.copy() offspring.positions[i] = puzzle.position offspring.manhattanDists[i] = puzzle.manhattanDist
def test_basic_beam_with_low_k(self): puzzle = Puzzle() puzzle.currState = "b42 135 678" move_count = puzzle.solve("beam", "1") # expect the solution to be optimal only because the solution is so short self.assertEqual(4, move_count)
def test_basic_beam_with_high_k(self): puzzle = Puzzle() puzzle.currState = "b42 135 678" move_count = puzzle.solve("beam", "1000") # expect the solution to be optimal since the solution is short and k is high self.assertEqual(4, move_count)
def mutation(offspring): offspring = deepcopy(offspring) for individual in offspring: index = np.random.randint(2, CROSSOVER_LEN) puzzle = Puzzle(individual.states[index - 1]) lastStep = individual.steps[index - 1] moves = puzzle.availMove(lastStep) move = choice(moves) puzzle.move(move) individual.states[index] = puzzle.state.copy() individual.positions[index] = puzzle.position individual.manhattanDists[index] = puzzle.manhattanDist lastStep = move for i in range(index + 1, CHROM_LEN): moves = puzzle.availMove(lastStep) if (individual.steps[i] in moves): move = individual.steps[i] else: move = choice(moves) individual.steps[i] = move puzzle.move(move) individual.states[i] = puzzle.state.copy() individual.positions[i] = puzzle.position individual.manhattanDists[i] = puzzle.manhattanDist lastStep = move return offspring
def ReadPuzzle(filename): puzFile = open(filename, 'r') initialPuzzle = None # Read the header line headerLine = puzFile.readline() # try to split the header line and assure three tokens headerTokens = headerLine.split() if len(headerTokens) == 3: try: # initialie the puzzle return value initialPuzzle = Puzzle() # first number is column count initialPuzzle.numCols = int(headerTokens[0]) # second number is row count initialPuzzle.numRows = int(headerTokens[1]) # final number is wriggler count initialPuzzle.numWrigglers = int(headerTokens[2]) except Exception as e: # If any number parsing fails, just carry on. # We'll return the None puzzle indicating failure print "FAILED to parse puzzle in " + filename print "Exception says " + e.message print "Confirm formatting." return None # Now that we have the number of rows, we can start reading # in puzzle lines currPuzzleLine = 1 for nextLine in puzFile: if currPuzzleLine <= initialPuzzle.numRows: # split the line into tile tokens tiles = nextLine.split() # and append the tiles onto the initial puzzle initialPuzzle.AddLine(tiles) #initialPuzzle.puzzle += tiles else: print "FAILED to parse puzzle in " + filename print "Tried to parse " + str (currPuzzleLine) \ + " but there are only " + str(initialPuzzle.numRows) \ + " according to the header!" del initialPuzzle initialPuzzle = None return initialPuzzle
def test_it_can_switch_correctly(): puzzle = Puzzle() first_element = 2 second_element = 3 board1 = puzzle.board board2 = Helpers.copy_list( board1 ) puzzle.swap( first_element , second_element ) for x in range( 0 , len(board1)-1 ): # Except for the two swaped elements... if (x == first_element or x == second_element): continue # Other elements should be the same assert board1[x] == board2[x]
def main(): parser = argparse.ArgumentParser() parser.add_argument('algorithm') parser.add_argument('board') args = parser.parse_args() initial_board: list = [int(e) for e in args.board.split(",")] goal_board: list = [1, 2, 3, 4, 5, 6, 7, 8, 0] root_puzzle: Puzzle = Puzzle(initial_board, goal_board) solver: Solver = Solver() function_map: dict = { 'bfs': solver.breadth_first_search, 'dfs': solver.depth_first_search, 'idfs': solver.iterative_depth_first_search, 'ast': solver.a_star, 'gfs': solver.best_first_search } start_time: float = time.time() result: tuple = function_map[args.algorithm](root_puzzle) stop_time: float = time.time() export(result, stop_time - start_time)
def get_h(self, puzzle): """ Gets the heuristic score of the moves :param list moves: The list of possible moves :return list scores: The list of scores for each move """ if self.h_option == "1": scores = Puzzle.get_h1(puzzle) elif self.h_option == "2": scores = Puzzle.get_h2(puzzle) elif self.h_option == "3": scores = Puzzle.get_h3(puzzle) else: raise Exception("Invalid heuristic option.") return scores
def get_puzzle_from_file_name(file_name): file_content = PyKit.FileManager.get_string_from_file(file_name) parser = PyKit.Parser(clear_empty_lines=True, clear_comment_lines=True) parsed_lines = parser.parsed_str(file_content) number_founded = list() if not len(parsed_lines): PyKit.error("Empty file.") else: try: n = int(parsed_lines[0]) except ValueError: PyKit.error("There is no size at the beginning of the file.") if n < 3: PyKit.error("Puzzle dimension should be greater then 2.") puzzle = np.zeros((n, n)) del parsed_lines[0] if len(parsed_lines) != n: PyKit.error("There is " + str(len(parsed_lines)) + " lines , must be " + str(n) + " lines, puzzle is not well formatted.") for (index, line) in enumerate(parsed_lines): np_line = np.fromstring(line, dtype=int, sep=" ") if len(np_line) != n: PyKit.error("Line " + str(index + 1) + " is too long or too short, " "must be " + str(n) + " values, puzzle is not well formatted.") for val in np_line: if val > (n * n) - 1 or val < 0: PyKit.error(str(val) + " is greater than " + str(n * n - 1) + " or negative, puzzle is not well " "formatted.") if val in number_founded: PyKit.error(str(val) + " is more then 1 time in the puzzle, puzzle is not well formatted.") number_founded += [val] puzzle[index] = np_line return Puzzle(puzzle, n)
def a_star(puzzle_start, goal, heuristic_used): monotonic_restriction_satisfied = True open_list = PriorityQueue() open_list.put(puzzle_start) open_list_len = 1 closed_list = {} parent_list = {} string_to_matrix_mapping = {} optimal_path_cost = -1 while open_list_len > 0: puzzle_state = open_list.get() open_list_len -= 1 puzzle_configuration_string = ''.join( str(val) for row in puzzle_state.puzzle_configuration for val in row) closed_list[puzzle_configuration_string] = puzzle_state.g_n string_to_matrix_mapping[ puzzle_configuration_string] = puzzle_state.puzzle_configuration if puzzle_state.puzzle_configuration == goal: optimal_path_cost = puzzle_state.g_n break node_h_n = puzzle_state.h_n neighbours = find_neighbours(puzzle_state.puzzle_configuration) for neighbour in neighbours: neighbour_string = ''.join( str(val) for row in neighbour for val in row) # to check for monotonic restriction is satisfied or not neighbour_h_n = h_n(neighbour, goal, heuristic_used) if node_h_n > neighbour_h_n + 1: monotonic_restriction_satisfied = False if neighbour_string not in closed_list: parent_list[neighbour_string] = puzzle_configuration_string closed_list[neighbour_string] = puzzle_state.g_n + 1 open_list.put( Puzzle(neighbour, puzzle_state.g_n + 1, h_n(neighbour, goal, heuristic_used))) open_list_len += 1 elif puzzle_state.g_n + 1 < closed_list[neighbour_string]: parent_list[neighbour_string] = puzzle_configuration_string closed_list[neighbour_string] = puzzle_state.g_n + 1 open_list.put( Puzzle(neighbour, puzzle_state.g_n + 1, h_n(neighbour, goal, heuristic_used))) open_list_len += 1 return closed_list, parent_list, optimal_path_cost, string_to_matrix_mapping, monotonic_restriction_satisfied
def test_it_can_move_correctly_and_raise_appropiate_exception(): puzzle = Puzzle() puzzle.board = [None,None,1,2,3,4,5,6,7,8] puzzle.move(2) assert puzzle.board == [None,1,None,2,3,4,5,6,7,8] puzzle.move(5) assert puzzle.board == [None,1,4,2,3,None,5,6,7,8] with pytest.raises(Exception): puzzle.move(1) assert puzzle.board == [None,1,4,2,3,None,5,6,7,8]
def test_it_count_tries_correctly(): puzzle = Puzzle() puzzle.board = [None,None,1,2,3,4,5,6,7,8] assert puzzle.tries == 0 puzzle.move(2) assert puzzle.tries == 1 puzzle.move(5) assert puzzle.tries == 2 with pytest.raises(Exception): puzzle.move(1) assert puzzle.tries == 2
def random_state(self): count = 0 p = Puzzle() if self.aim is None: self.init_aim() p.state = self.aim # l = p.state i = self.hard b = 0 while i != 0: a = random.randint(0, 3) while (a % 2 == b % 2 and a != b) or (a == b and count == 2): a = random.randint(0, 3) b = a p = self.move(p, a) i = i - 1 return p
def test_if_the_neigbours_are_correct(): puzzle = Puzzle() assert puzzle.are_neigbours(4,1) assert puzzle.are_neigbours(6,9) assert puzzle.are_neigbours(4,1) assert puzzle.are_neigbours(2,3) assert puzzle.are_neigbours(7,8) assert puzzle.are_neigbours(4,5) assert puzzle.are_neigbours(4,7) assert puzzle.are_neigbours(2,1) assert puzzle.are_not_neigbours(8,4) assert puzzle.are_not_neigbours(5,1) assert puzzle.are_not_neigbours(5,1) assert puzzle.are_not_neigbours(3,9) assert puzzle.are_not_neigbours(9,2) assert puzzle.are_not_neigbours(3,5) assert puzzle.are_not_neigbours(4,6)
def run_from_file(filename): command_list = [] puzzle = Puzzle() with open(filename, "r") as file: for line in file: command_list.append(line.strip()) for command in command_list: exec_command(command, puzzle)
def hill_climbing(puzzle_start, goal, heuristic_used): monotonic_restriction_satisfied = True open_list = PriorityQueue() open_list.put(puzzle_start) open_list_len = 1 closed_list = {} parent_list = {} string_to_matrix_mapping = {} optimal_path_cost = -1 while open_list_len > 0: puzzle_state = open_list.get() open_list_len -= 1 puzzle_configuration_string = ''.join( str(val) for row in puzzle_state.puzzle_configuration for val in row) closed_list[puzzle_configuration_string] = puzzle_state.g_n string_to_matrix_mapping[ puzzle_configuration_string] = puzzle_state.puzzle_configuration current_cost = puzzle_state.h_n if puzzle_state.puzzle_configuration == goal: optimal_path_cost = puzzle_state.g_n break node_h_n = puzzle_state.h_n neighbours = find_neighbours(puzzle_state.puzzle_configuration) best_neigbour = None for neighbour in neighbours: neighbour_string = ''.join( str(val) for row in neighbour for val in row) neighbour_h_n = h_n(neighbour, goal, heuristic_used) neighbour_g_n = puzzle_state.g_n + 1 neighbour_cost = neighbour_h_n if neighbour_cost <= current_cost and neighbour_string not in closed_list: best_neigbour_string = neighbour_string best_neigbour = neighbour current_cost = neighbour_cost if node_h_n > neighbour_h_n + 1: monotonic_restriction_satisfied = False if best_neigbour is not None: open_list.put( Puzzle(best_neigbour, puzzle_state.g_n + 1, h_n(best_neigbour, goal, heuristic_used))) open_list_len += 1 parent_list[best_neigbour_string] = puzzle_configuration_string else: optimal_path_cost = -1 break return closed_list, parent_list, optimal_path_cost, string_to_matrix_mapping, monotonic_restriction_satisfied
def resolve(self): states = StateSpace(list()) visited = set() solved = False p = Puzzle(self.puzzle) n = Node(p, None, 0, None) states.states.append(n) while not solved and len(states.states) != 0: n = states.get_new() p = n.puzzle if self.is_solved(p): solved = True else: if p.hash() not in visited: visited.add(p.hash()) states.generate_successors(n) if solved: self.print_solution(n) else: print("The puzzle has no solution")
def h1(puzzle: Puzzle): """ Heuristic #1 Returns the number of tiles out of row + number of tiles out of column """ count = 0 for item, index in puzzle.getPuzzle().items(): if not inCorrectRow(item, index): count += 1 if not inCorrectColumn(item, index): count += 1 return count
def load_puzzle(filename): with open(filename, "rb") as fp: layout = numpy.zeros(25) acc_dict_array = [dict() for i in range(5)] down_dict_array = [dict() for i in range(5)] answer_matrix = numpy.full((5, 5), -1) i = 0 for line in fp: temp_str = line.decode() if i < 5: # line [0, 5) temp_list = temp_str.strip('\r\n').split(' ', 4) layout[i * 5] = int(temp_list[0]) != 36 layout[i * 5 + 1] = int(temp_list[1]) != 36 layout[i * 5 + 2] = int(temp_list[2]) != 36 layout[i * 5 + 3] = int(temp_list[3]) != 36 layout[i * 5 + 4] = int(temp_list[4]) != 36 # b'{:d} {:d} {:D} \r\n' elif i < 10: # line [5, 10) temp_list = temp_str.strip('\r\n').split(' ', 2) acc_dict_array[i - 5] = { 'index': int(temp_list[0]), 'display_index': int(temp_list[1]), 'clue': temp_list[2] } # b'{:d} {:d} {:D} \r\n' elif i < 15: # line [10, 15) temp_list = temp_str.strip('\r\n').split(' ', 2) down_dict_array[i - 15] = { 'index': int(temp_list[0]), 'display_index': int(temp_list[1]), 'clue': temp_list[2] } elif i < 16: # line [15, 16) date = temp_str.strip("\n") elif i < 21: # line [16, 21) temp_list = temp_str.strip('\r\n').split(' ', 4) answer_matrix[(i - 16)][0] = int(temp_list[0]) answer_matrix[(i - 16)][1] = int(temp_list[1]) answer_matrix[(i - 16)][2] = int(temp_list[2]) answer_matrix[(i - 16)][3] = int(temp_list[3]) answer_matrix[(i - 16)][4] = int(temp_list[4]) i += 1 return Puzzle(layout, acc_dict_array, down_dict_array, date, answer_matrix)
def h2(puzzle: Puzzle): tiles = puzzle.getPuzzle() manhattan_distance = 0 for tile, index in tiles.items(): correctIndex = int(tile) - 1 if tile == Puzzle.EMPTY_SLOT: correctIndex = 7 coordinate1 = indexToCoordinates(correctIndex) coordinate2 = indexToCoordinates(index) coordinates = { 'y': coordinate1['y'] - coordinate2['y'], 'x': coordinate1['x'] - coordinate2['x'] } manhattan_distance += coordinates['y']**2 + coordinates['x']**2 return manhattan_distance
def abrirVentanaJuego(root, imagenPath, filas, columnas): global pil_image_tk global arrLabels global imagetk_pieza global miFrameImagen global puzzle ventanaJuego = Toplevel(root) ventanaJuego.title("Puzzle") ventanaJuego.resizable(False, False) ventanaJuego.protocol("WM_DELETE_WINDOW", lambda: onClosing(ventanaJuego)) #CARGAR IMAGEN pil_image = Image.open(imagenPath) pil_image_tk = ImageTk.PhotoImage(pil_image) #CONFIGURAR LAS DIMENSIONES DE LA IMAGEN anchura, altura = pil_image.size #CREAR EL OBJETO PUZZLE puzzle = Puzzle(altura, anchura, int(filas), int(columnas), pil_image) arrLabels = [[0 for x in range(puzzle.columnas)] for y in range(puzzle.filas)] imagetk_pieza = [[0 for x in range(puzzle.columnas)] for y in range(puzzle.filas)] #FRAME DE LA IMAGEN miFrameImagen = Frame(ventanaJuego, width=anchura, height=altura) miFrameImagen.pack(side="left") #label_image = Label(miFrameImagen, image=pil_image_tk) for f in range(puzzle.filas): for c in range(puzzle.columnas): nparray_pieza = puzzle.piezas_rompecabezas_blanco[f][c] pil_pieza = Image.fromarray(nparray_pieza) imagetk_pieza[f][c] = ImageTk.PhotoImage(pil_pieza) arrLabels[f][c] = Label(miFrameImagen, image=imagetk_pieza[f][c]) arrLabels[f][c].grid(row=f, column=c) ventanaJuego.bind("<Button-1>", lambda event: intercambiarPiezas(event, root))
def move(self, p, d): s = Puzzle() s.state = p.state[:] pos = s.state.index(0) if d == 1: if (pos - self.m) >= 0: s.state[pos], s.state[pos - self.m] = s.state[pos - self.m], s.state[pos] elif d == 2: if pos % self.m != 0: s.state[pos], s.state[pos - 1] = s.state[pos - 1], s.state[pos] elif d == 3: if (pos + self.m) <= self.m**2 - 1: s.state[pos], s.state[pos + self.m] = s.state[pos + self.m], s.state[pos] else: if (pos + 1) % self.m != 0: s.state[pos], s.state[pos + 1] = s.state[pos + 1], s.state[pos] return s
def parse_map(map): first = True puzzle = [] for line in map: line_util = line.split('#')[0] if line_util == None or line_util == "": continue if first is not True: puzzle.append(parse_line(line_util)) if (len(puzzle) > env.size): log.error("parsing map. Too many lines") sys.exit(1) else: first = False parse_line(line_util) if (len(puzzle) < env.size): log.error("parsing map. Not Enought Lines") sys.exit(1) parse_map_value(puzzle) return Puzzle(puzzle)
def create_puzzle(argv): puzzle = Puzzle(argv.sf, argv.num_h_ver) b = parse_map(argv.file_name) puzzle.size_matr = int(math.sqrt((len(b) + 1) / 2)) can_i_do_it(b, puzzle.size_matr) # проверим возможность решения ch = make_children(b.split("/"), puzzle.size_matr) # для исходного состояния рождаем детей(макс 4) puzzle.complexity_in_size += len(ch) puzzle.must_be_str = str(must_be(puzzle.size_matr)).split('/') # и добавляем всех в список открытых вершин A = Node(puzzle.size_matr, None, b.split("/"), 0, puzzle.sf, argv.num_h_ver, puzzle) if puzzle.must_be_str == A.node: print("Init state is equal to goal state") sys.exit() for c in ch: ch_c = Node(puzzle.size_matr, A, c, 1, puzzle.sf, argv.num_h_ver, puzzle) puzzle.q.put((ch_c.f, ch_c)) puzzle.sp_z[A] = A.par puzzle.closed_set = set(["/".join(A.node)]) puzzle.b = b return puzzle
def search(self): """ Performs a dept first search on the puzzle """ # While open is not empty while len(self.open) != 0: # Remove leftmost state from open current_puzzle = self.open[0] self.open.remove(current_puzzle) self.closed.append(current_puzzle) # Write to txt file pos = current_puzzle.index(0) Puzzle.write_to_txt(dfs_output, Puzzle.get_tile_letter(pos), current_puzzle) print("Puzzle: " + str(current_puzzle)) if not Puzzle.is_puzzle_solved(current_puzzle): # Generate children of a possible_moves = Puzzle.get_possible_moves(current_puzzle) children = [] for move in possible_moves: child = Puzzle.move(move, current_puzzle) children.append(child) # Remove child if it is in the open or closed list to_remove = [] for child in children: if child in self.open: to_remove.append(child) elif child in self.closed: to_remove.append(child) for r in to_remove: children.remove(r) # Put remaining children on left end of open self.open = children + self.open else: return
from Puzzle import Puzzle puzzle = Puzzle([0, 2, 3, 4, 5, 6, 7, 8]) puzzle.display_state() # print(puzzle.get_list_of_moves()) #print(puzzle.get_dict_of_moves_with_cost()) # print(puzzle.get_list_of_possible_states()) print(puzzle.get_dict_of_possible_states_with_cost()) # print(puzzle.test_move(1,0)) # puzzle.display_state() # puzzle.perform_move(1,0) # puzzle.display_state()
print "" print str(newSearchNode.state.puzzle) print "====" print str(newSearchNode) if __name__ == "__main__": from Puzzle import Puzzle from Wriggler import Wriggler # Test goal state determination goalWriggler = Wriggler() goalWriggler.head.pos = (1, 2) goalWriggler.tail.idNumber = 0 goalWriggler.tail.pos = (2,2) puzz = Puzzle() puzz.numCols = 3 puzz.numRows = 3 state = State(puzz, [goalWriggler]) agent = Agent(SearchNode(state, None, None, 0)) if not agent.currentSearchNode.ContainsGoalState(): print "FAILED to detect goal state" print "TESTING SEARCH NODE GEN:" TestSearchNodeGen() print "" print "TESTING THE FRONTIER" print "" TestFrontierExpand()
4. Large Heuristic (h(n) > h*(n)). 5. Displaced tiles heuristic with blank tile cost included. 6. Manhattan distance heuristic with blank tile cost included''') choice1 = int(input('''Enter choice 1 for comparison: ''')) choice2 = int(input('Enter choice 2 for comparison: ')) if check(choice1) or check(choice2): print("Invalid choice bc.") else: table = PrettyTable([ "Heuristic", "No. states explored", "No. states on the optimal path", "Optimal path cost", "Time taken (secs)", "Monotonic restriction satisfied" ]) start_temp = deepcopy(start) # 1st choice puzzle_start = Puzzle(start, 0, h_n(start, goal, choice1)) start = timeit.default_timer() closed_list, parent_list, optimal_path_cost, string_to_matrix_mapping, monotonic_satisfied = a_star( puzzle_start, goal, choice1) stop = timeit.default_timer() table.add_row([ choices[choice1], len(closed_list.keys()), optimal_path_cost + 1, optimal_path_cost, stop - start, monotonic_satisfied ]) set1 = set(closed_list.keys()) # 2nd choice start = start_temp puzzle_start = Puzzle(start, 0, h_n(start, goal, choice2)) start = timeit.default_timer()
def main(): nSolutions = int(input("How many solutions should the puzzle have? ")) nEmpty = int(input("How many empty cells do you want? ")) if (nEmpty <= 45): print("Generating and saving initial puzzle...") p = Puzzle(nSolutions, nEmpty) p.empty() filNam = str(p.puzzleID()[0]) + "-" + str(p.puzzleID()[1]) + ".txt" out = open(filNam, 'a') json.dump(p.getPuzzle(), out) print("Now adding more puzzles...") n = 0 i = 1 while (n < 50): print("Trying new puzzle " + str(i)) fullBoard = copyListOfLists(p.getOriginalBoard()) emptyBoard = copyListOfLists(p.getPuzzle()) board = createMoreSudoku(fullBoard, emptyBoard) F = createSudoku(board) if (exactly_n_models(F, p.puzzleID()[0])): json.dump(board, out) n += 1 print("Another puzzle added: " + str(n) + " puzzles this session out of " + str(i) + " tried") i += 1 else: print("Generating and saving 50 puzzles with your preferences...") for i in range(50): print("Generating puzzle " + str(i + 1) + " of 50...") p = Puzzle(nSolutions, nEmpty) p.empty() filNam = str(p.puzzleID()[0]) + "-" + str(p.puzzleID()[1]) + ".txt" out = open(filNam, 'a') json.dump(p.getPuzzle(), out)
class Game: def __init__(self, master): self.master = master self.app_frame = tkinter.Frame(self.master, bg='white') self.app_frame.pack(fill=tkinter.BOTH, expand=True) self.create_game() self.build_grid() self.update_board() def create_game(self): self.puzzle = Puzzle() self.create_select_mover() def update_board(self): self.push_button = [None for i in range(10)] for i in range(1, len(self.puzzle.board)): x = int((i - 1) / 3) y = int((i - 1) % 3) self.push_button[i] = tkinter.Button(self.app_frame, text=self.puzzle.board[i], command=self.select_mover[i]) self.push_button[i].grid(row=x, column=y, sticky='news') self.check_for_victory() def check_for_victory(self): if self.puzzle.won(): messagebox.showinfo('GAME OVER!', 'Player1 Won!') self.create_game() self.update_board() def build_grid(self): self.app_frame.columnconfigure(0, weight=1) self.app_frame.columnconfigure(1, weight=1) self.app_frame.columnconfigure(2, weight=1) self.app_frame.rowconfigure(0, weight=1) self.app_frame.rowconfigure(1, weight=1) self.app_frame.rowconfigure(2, weight=1) self.app_frame.rowconfigure(3, weight=1) def create_select_mover(self): self.select_mover = { 1: self.move1, 2: self.move2, 3: self.move3, 4: self.move4, 5: self.move5, 6: self.move6, 7: self.move7, 8: self.move8, 9: self.move9, } def move1(self): try: self.puzzle.move(1) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move2(self): try: self.puzzle.move(2) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move3(self): try: self.puzzle.move(3) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move4(self): try: self.puzzle.move(4) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move5(self): try: self.puzzle.move(5) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move6(self): try: self.puzzle.move6(1) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move7(self): try: self.puzzle.move(7) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move8(self): try: self.puzzle.move(8) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board() def move9(self): try: self.puzzle.move(9) except Exception: messagebox.showinfo('Invalid Move', "you can't move this tile.") self.update_board()
def create_game(self): self.puzzle = Puzzle() self.create_select_mover()
def test_checkGoal(self): goodGoal = [1, 2, 3, 4, 5, 6, -1, 7, -1, 8, 9, 10, 0, 11, 12, 13, -1, 14, -1, 15, 16, 17, 18, 19, 20] puzzle2 = Puzzle(goodGoal, puzzleGoal) self.assertTrue(puzzle2.checkGoal())
def test_h2n(self): goodGoal = [1, 2, 3, 4, 5, 7, -1, 6, -1, 8, 9, 10, 0, 11, 12, 13, -1, 14, -1, 15, 16, 17, 18, 19, 20] puzzle2 = Puzzle(goodGoal, puzzleGoal) self.assertEquals(8, puzzle2.h2n())
import sys from time import sleep from Puzzle import Puzzle path = raw_input("Enter filepath location of sudoku puzzle: ") try: puzzle = Puzzle(path) except: print sys.exc_info()[0] exit(0) puzzle.displayPuzzle() print "Number of empty cells: {}".format(puzzle.getEmptyCount()) print "\n\n" # My idea here was to try one method first until it got stuck, then I # implemented a second method to try until stuck, then back to the first. # puzzle is done once solved or both methods get stuck while not puzzle.isDone(): while not puzzle.methodOneStuck: puzzle.setMethodOneStuck(True) for x in range(9): for y in range(9): possible = puzzle.getPossibleSet(x, y) if possible is not None and len(possible) == 1: # if I found something to place, set that value, update all possibilities # and set the stuck methods to false until the next run, so it only exits # if stuck for two runs in a row puzzle.setMethodOneStuck(False) puzzle.setMethodTwoStuck(False)
def calcRate(self): if self.rate < 0: p = Puzzle(self.puzzle_list[:]) p.applyMoves(self.moves) self.rate = p.calcRate()
def main(): nSolutions = int(input("How many solutions should the puzzle have? ")) nEmpty = int(input("How many empty cells do you want? ")) if (nEmpty <= 45): print("Generating and saving initial puzzle...") p = Puzzle(nSolutions, nEmpty) p.empty() filNam = str(p.puzzleID()[0]) + "-" + str(p.puzzleID()[1]) + ".txt" out = open(filNam, 'a') json.dump(p.getPuzzle(), out) print("Now adding more puzzles...") n = 0 i = 1 while(n < 50): print("Trying new puzzle " + str(i)) fullBoard = copyListOfLists(p.getOriginalBoard()) emptyBoard = copyListOfLists(p.getPuzzle()) board = createMoreSudoku(fullBoard, emptyBoard) F = createSudoku(board) if (exactly_n_models(F, p.puzzleID()[0])): json.dump(board, out) n+= 1 print("Another puzzle added: " + str(n) + " puzzles this session out of " + str(i) + " tried") i += 1 else: print("Generating and saving 50 puzzles with your preferences...") for i in range(50): print("Generating puzzle " + str(i + 1) + " of 50...") p = Puzzle(nSolutions, nEmpty) p.empty() filNam = str(p.puzzleID()[0]) + "-" + str(p.puzzleID()[1]) + ".txt" out = open(filNam, 'a') json.dump(p.getPuzzle(), out)