Exemplo n.º 1
0
    def solve(x_in, window):
        pop, trial = Puzzle(), Puzzle()
        trial.init(x_in, "")
        trial.depth = 0
        q = PriorityQueue()
        q.put(copy.deepcopy(trial))
        is_searched = {trial.id: True}
        if trial.is_target():
            return trial.path

        while not q.empty():
            window.update()
            pop = q.get()
            sx = int(pop.space % Puzzle.N)
            sy = int(pop.space / Puzzle.N)
            for r in range(4):
                tx = sx + Puzzle.dx[r]
                ty = sy + Puzzle.dy[r]
                if tx < 0 or ty < 0 or tx >= Puzzle.N or ty >= Puzzle.N:
                    continue
                trial.init(pop.x, pop.path)
                trial.set_depth(pop.depth + 1)
                trial.swap(trial.space, ty * Puzzle.N + tx)
                if trial.id not in is_searched.keys():
                    is_searched[trial.id] = True
                    trial.path = trial.path + Puzzle.dir[r]
                    if trial.is_target():
                        return trial.path
                    q.put(copy.deepcopy(trial))
Exemplo n.º 2
0
def main():
    #First show one execution of a puzzle to solve
    pz = Puzzle('12375846 ')
    print('Solving the following puzzle and printing steps:')
    print(pz)
    jigsaw = JigsawPlay(pz)
    steps = jigsaw.solve('fair', True)
    for step in steps:
        print(Puzzle(step))

    #Now time everything and plot the graph
    number_executions = 10
    puzzles = generate_puzzles(number_executions)
    fair_lambda = Timer(lambda: time_solve_puzzle('fair', puzzles, False))
    fair_score = fair_lambda.timeit(number=1)
    weak_lambda = Timer(lambda: time_solve_puzzle('weak', puzzles, False))
    weak_score = weak_lambda.timeit(number=1)
    bad_lambda = Timer(lambda: time_solve_puzzle('bad', puzzles, False))
    bad_score = bad_lambda.timeit(number=1)
    good_lambda = Timer(lambda: time_solve_puzzle('good', puzzles, False))
    good_score = good_lambda.timeit(number=1)

    print ('Fair evaluation execution time: ', fair_score)
    print ('Weak evaluation execution time: ', weak_score)
    print ('Bad evaluation execution time: ', bad_score)
    print ('Good evaluation execution time: ', good_score)


    plt.plot(['bad', 'weak', 'fair', 'good'], [bad_score, weak_score, fair_score, good_score])
    plt.title('A* evaluation timing')
    plt.ylabel('Duration')
    plt.show()
Exemplo n.º 3
0
def main(puzzleFile, method, timeLimit):

	puzzleSize = 3

	#print(puzzleSize)	#debug
	problem = Puzzle()
	problem.loadFile(open(puzzleFile, 'r'), puzzleSize)
	solution = Puzzle()
	solution.loadFile(open('solution.txt', 'r'), puzzleSize)
	solver = None

	if method == 'BFS':
		solver = PuzzleAgent(weights.bfsWeight)
	elif method == 'A*':
		solver = PuzzleAgent(weights.aStarWeight)
	elif method == 'GREEDY':
		solver = PuzzleAgent(weights.manhattanWeight)
	elif method == 'UNIFORM':
		solver = PuzzleAgent(weights.uniformWeight)
	else:
		print('Invalid method')
		return

	#problem.printState()	#debug

	solution = solver.solve(problem, solution, timeLimit)

	while solution:
		solutionStep = solution.pop()
		solutionStep.printState()
Exemplo n.º 4
0
 def get_children(self, node):
     child_list = set()
     dim = node.state.shape[0]
     i, j = map(np.int, np.where(node.state == 0))
     if (j > 0):
         child = node.state.copy()
         child[i, j] = node.state[i, j - 1]
         child[i, j - 1] = 0
         p = Puzzle(child)
         child_list.add(p)
     if (j < dim - 1):
         child = node.state.copy()
         child[i, j] = node.state[i, j + 1]
         child[i, j + 1] = 0
         p = Puzzle(child)
         child_list.add(p)
     if (i > 0):
         child = node.state.copy()
         child[i, j] = node.state[i - 1, j]
         child[i - 1, j] = 0
         p = Puzzle(child)
         child_list.add(p)
     if (i < dim - 1):
         child = node.state.copy()
         child[i, j] = node.state[i + 1, j]
         child[i + 1, j] = 0
         p = Puzzle(child)
         child_list.add(p)
     return child_list
Exemplo n.º 5
0
 def test_manhattan_distance(self):
     puzz = Puzzle()
     puzz.set_state([[1, 2, 3],
                     [4, 7, 5],
                     [6, 8, 0]])
     self.assertEqual(2, puzz.evaluate('fair'))
     puzz = Puzzle(' 13425678')
     self.assertEqual(2, puzz.evaluate('fair'))
Exemplo n.º 6
0
def puzzle(args):
    start = Puzzle(np.array([4, 3, 6, 8, 2, 7, 5, 1, 0]))
    goal = Puzzle(np.array([8, 1, 2, 7, 0, 3, 6, 5, 4]))

    path = BFS(start, goal)

    for s in path:
        print(s[1].board.reshape((3, 3)))
        if s[0]:
            print("ACTION: ", s[0])
Exemplo n.º 7
0
 def test_get_best_fvalue(self):
     p1 = Puzzle([[2, 4, 8], [5, None, 6], [7, 1, 2]], None)
     p1.f = 4
     p2 = Puzzle([[2, 4, 8], [5, None, 6], [7, 1, 2]], None)
     p2.f = 8
     p3 = Puzzle([[2, 4, 8], [5, None, 6], [7, 1, 2]], None)
     p3.f = 3
     open_list = [p1, p2, p3]
     index, puzzle = get_best_fvalue(open_list)
     self.assertEqual(2, index)
     self.assertEqual(p3, puzzle)
Exemplo n.º 8
0
def main_1():
    dim = 3
    goal = Puzzle(
        np.insert(np.arange(1, dim * dim), dim * dim - 1, 0).reshape(dim, dim))
    time1 = []
    time2 = []
    space1 = []
    space2 = []

    for i in range(15):
        while True:
            start = Puzzle(
                np.random.permutation(np.arange(dim * dim)).reshape(
                    (dim, dim)))
            if start.solvable(): break
        t_1 = time.time()
        p1 = Astar('manhattan', start, goal)
        h1 = p1.search()
        t_2 = time.time()
        t_f = t_2 - t_1
        time1.append(t_f)
        space1.append(np.mean([j for i, j in h1]))

        t_11 = time.time()
        p2 = Astar('hamming', start, goal)
        h2 = p2.search()
        t_22 = time.time()
        t_ff = t_22 - t_11
        time2.append(t_ff)
        space2.append(np.mean([j for i, j in h2]))

    a = plt.plot(time1, 'blue')
    b = plt.plot(time2, 'red')
    plt.legend(['Manhattan', 'Hamming'])
    plt.xlabel('puzzle')
    plt.ylabel('tiempo')
    plt.title('Tiempo A*')
    plt.show()

    a = plt.plot(space1, 'blue')
    b = plt.plot(space2, 'red')
    plt.legend(['Manhattan', 'Hamming'])
    plt.xlabel('puzzle')
    plt.ylabel('espacio')
    plt.title('Espacio A*')
    plt.show()

    print(time1)
    print(space1)
    print(time2)
    print(space2)
Exemplo n.º 9
0
def test_solvable():
    """Tests different puzzles to see if they are solvable."""
    p1 = Puzzle(puzzle1)
    p2 = Puzzle(puzzle2)

    print(p1)
    print("Solvable:", p1.is_solvable(), '\n')

    print(p2)
    print("Solvable:", p2.is_solvable(), '\n')

    p3 = Puzzle()
    print(p3)
    print("Solvable:", p3.is_solvable())
Exemplo n.º 10
0
 def test_init_actual(self):
     testpuzzle = Puzzle(
         'C:\\Users\\Jono-work\\Git\\personal\\nonosolver\\puzzles\\upright.json'
     )
     self.assertEqual(
         testpuzzle.puzzleactual,
         [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Exemplo n.º 11
0
def main():
    """
    args[0] - method, bfs / dfs / astr
    args[1] - search order or heuristic e.g. ldur / rldu / manh / hamm
    args[2] - filename of puzzle file
    args[3] - filename of solution file
    args[4] - filename of additional data file

    """

    args = sys.argv[1:]

    if len(args) == 5:
        initial_puzzle = load_initial_puzzle(args[2])
        print_initial_info(args, initial_puzzle)

        if puzzle_height != 4 or puzzle_width != 4:
            correct_puzzle = generate_correct_state(puzzle_height, puzzle_width)
            Puzzle.correct_state, Puzzle.puzzle_height, Puzzle.puzzle_width = correct_puzzle, puzzle_height, puzzle_width

        first_state = Puzzle(initial_puzzle)
        choose_method(args[0], args[1], first_state, args[3], args[4])

    else:
        print("Wrong number of arguments!")
Exemplo n.º 12
0
    def build(self):
        root = Widget()
        puzzle = Puzzle(resolution=(640, 480), play=True)

        root.add_widget(puzzle)

        return root
Exemplo n.º 13
0
    def test_fit_top_bottom(self, piece4: Piece, piece9: Piece) -> None:
        """A piece with one possible matching side fits 8 ways."""
        assert str(piece4) == "Red-♦♣♧♢"
        assert str(piece9) == "Red-♥♠♤♧"
        expected_orientations = [
            (piece9, False, Turn.TURN_270, piece4, False, Turn.TURN_270),
            (piece9, False, Turn.TURN_270, piece4, True, Turn.TURN_90),
            (piece4, False, Turn.TURN_90, piece9, False, Turn.TURN_90),
            (piece4, False, Turn.TURN_90, piece9, True, Turn.TURN_270),
            (piece9, True, Turn.TURN_90, piece4, False, Turn.TURN_270),
            (piece9, True, Turn.TURN_90, piece4, True, Turn.TURN_90),
            (piece4, True, Turn.TURN_270, piece9, False, Turn.TURN_90),
            (piece4, True, Turn.TURN_270, piece9, True, Turn.TURN_270),
        ]
        expected = [
            Puzzle(1, 2,
                   (OrientedPiece(p1, f1, t1), OrientedPiece(p2, f2, t2)))
            for p1, f1, t1, p2, f2, t2 in expected_orientations
        ]
        assert sorted(expected) == expected
        puzzles = solve_puzzle(1, 2, (piece4, piece9))
        assert puzzles == set(expected)
        assert (str(expected[0]) == """\
┌♠┐
♥R♤
├♣┤
♦R♧
└♢┘\
""")
Exemplo n.º 14
0
def main(puzzle_file):
    """Main function of our program's driver. Times execution and prints results.

    Args:
        puzzle_file: The name of the input file describing the puzzle.
    """

    try:
        with open(puzzle_file) as f:
            puzzle_file = f.read()
    except IOError as e:
        sys.exit(e)

    print(puzzle_file.strip())      # print input file
    start_time = default_timer()    # begin timer

    puzzle_file = puzzle_file.splitlines()

    try:
        # unpack puzzle init values, then pass the remainder as the board
        tree = Tree(Puzzle(*puzzle_file[:7], puzzle_file[7:]))
    except (TypeError, ValueError) as e:
        sys.exit(e)

    # perform A* graph search and print results
    print(tree.astargs())
    print(default_timer() - start_time)
Exemplo n.º 15
0
    def __init__(self, puzzles=[]):
        self.current_puzzle = 0
        self.puzzle_codes = puzzles

        pygame.init()

        # Create a resizable screen area
        self.screen = pygame.display.set_mode((600, 600), pygame.RESIZABLE)

        pygame.scrap.init()

        clock = pygame.time.Clock()

        if self.puzzle_codes:
            self.puzzle = decode_pb(self.puzzle_codes[0])
        else:
            # Randomise first puzzle
            self.puzzle = Puzzle(random.randint(1, 6), random.randint(1, 5))
            self.puzzle.randomise()
            pygame.event.post(
                pygame.event.Event(pygame.KEYDOWN, {"key": pygame.K_r}))

        self.initialise()
        # As soon as the event loop start, begin solving the first puzzle
        pygame.event.post(
            pygame.event.Event(pygame.KEYDOWN, {"key": pygame.K_s}))

        # Start main loop
        self.quit = False
        while not self.quit:
            # Limit frames per second
            clock.tick(30)
            self.process_events()

        pygame.quit()
Exemplo n.º 16
0
 def test_init_fails_pieces_do_not_fit(self, piece1: Piece,
                                       piece2: Piece) -> None:
     with pytest.raises(ValueError) as err:
         Puzzle(2, 1, (OrientedPiece(piece1), OrientedPiece(piece2)))
     assert str(err.value) == (
         "Piece Red-♠♦♡♢ does not fit at col 0, row 0: Edge.EAST is Red-♣♥♤♡"
     )
Exemplo n.º 17
0
def mate(puztuple):
    puza = puztuple[0]
    puzb = puztuple[1]

    distsa = puza.distances
    distsb = puzb.distances
    movesa = puza.movenums
    movesb = puzb.movenums

    n = puza.n

    outmoves = {}

    for x in range(1, n + 1):
        for y in range(1, n + 1):

            if (distsa[(x, y)] > distsb[(x, y)]):
                outmoves[(x, y)] = movesa[(x, y)]
            else:
                outmoves[(x, y)] = movesb[(x, y)]

    babypuz = Puzzle(n)
    babypuz.movenums = outmoves
    babypuz.calculatemindistances()
    babypuz.evaluate()

    return babypuz
Exemplo n.º 18
0
def main():
    goal = [[1, 2, 3], [4, 5, 6], [7, 8, None]]
    board = [[3, 4, 8], [5, None, 6], [7, 1, 2]]
    # board = [[None, 1, 3], [4, 2, 5], [7, 8, 6]] # simple board
    puzzle = Puzzle(board, None)
    depth = 100
    astar(puzzle, goal, depth)
Exemplo n.º 19
0
    def test_fit_left_right(self, piece4: Piece, piece9: Piece) -> None:
        """A piece with one possible matching side fits 8 ways."""
        assert str(piece4) == "Red-♦♣♧♢"
        assert str(piece9) == "Red-♥♠♤♧"
        expected_orientations = [
            (piece4, False, Turn.NO_TURN, piece9, False, Turn.NO_TURN),
            (piece4, False, Turn.NO_TURN, piece9, True, Turn.TURN_180),
            (piece9, False, Turn.TURN_180, piece4, False, Turn.TURN_180),
            (piece9, False, Turn.TURN_180, piece4, True, Turn.NO_TURN),
            (piece9, True, Turn.NO_TURN, piece4, False, Turn.TURN_180),
            (piece9, True, Turn.NO_TURN, piece4, True, Turn.NO_TURN),
            (piece4, True, Turn.TURN_180, piece9, False, Turn.NO_TURN),
            (piece4, True, Turn.TURN_180, piece9, True, Turn.TURN_180),
        ]
        expected = [
            Puzzle(2, 1,
                   (OrientedPiece(p1, f1, t1), OrientedPiece(p2, f2, t2)))
            for p1, f1, t1, p2, f2, t2 in expected_orientations
        ]
        assert sorted(expected) == expected
        puzzles = solve_puzzle(2, 1, (piece4, piece9))
        assert puzzles == set(expected)
        assert (str(expected[0]) == """\
┌♦┬♥┐
♢R♣R♠
└♧┴♤┘\
""")
Exemplo n.º 20
0
 def ast(self,initial_state):
     start = time.time()
     max_level = 0
     frontier = []
     heapq.heapify(frontier)
     initial_puzzle = Puzzle()
     initial_puzzle.fill_from_string(initial_state.split(','))
     heapq.heappush(frontier,initial_puzzle)
     explored = []
     forbidden = SetQueue()
     while heapq.nlargest(1, frontier):
         state = heapq.heappop(frontier)
         state.set_puzzle_id(len(explored))
         explored.append(state)
         if state.is_solved():
             solution = self.get_solution(state,explored,start,max_level)
             self.write_solution_to_file(solution)
             break
         moved_puzzles = self.create_list_of_moved_puzzles(
             state,
             forbidden
         )
         if moved_puzzles and moved_puzzles[0].get_level() > max_level:
             max_level = moved_puzzles[0].get_level()
         for puzzle in moved_puzzles:
             heapq.heappush(frontier,puzzle)
             forbidden.put(puzzle)
Exemplo n.º 21
0
 def dfs(self, initial_state):
     start = time.time()
     max_level = 0
     frontier = SetStack()
     initial_puzzle = Puzzle()
     initial_puzzle.fill_from_string(initial_state.split(','))
     frontier.put(initial_puzzle)
     explored = []
     forbidden = SetQueue()
     forbidden.put(initial_puzzle)
     while not frontier.empty():
         state = frontier.get()
         state.set_puzzle_id(len(explored))
         explored.append(state)
         if state.is_solved():
             solution = self.get_solution(state,explored,start,max_level)
             self.write_solution_to_file(solution)
             break
         moved_puzzles = self.create_list_of_moved_puzzles(
             state,
             forbidden
         )
         if moved_puzzles and moved_puzzles[0].get_level() > max_level:
             max_level = moved_puzzles[0].get_level()
         for puzzle in reversed(moved_puzzles):
             frontier.put(puzzle)
             forbidden.put(puzzle)
Exemplo n.º 22
0
 def test_init_fails_too_many_pieces(self, piece1: Piece,
                                     piece2: Piece) -> None:
     with pytest.raises(ValueError) as err:
         Puzzle(1, 1, (OrientedPiece(piece1), OrientedPiece(piece2)))
     assert (str(
         err.value
     ) == "2 pieces will not fit in a puzzle of size 1 (width 1, height 1)")
Exemplo n.º 23
0
    def generate_new_states(self, state, search_order):
        to_reverse = []
        if state.depth > self.max_depth:
            self.max_depth = state.depth

        for direction in search_order:

            # Check if move is possible in given direction and if depth is lower than max possible depth
            if state.check_if_move_possible(
                    direction) and state.check_if_not_reversed(
                        direction) and state.depth < self.max_depth_possible:
                new_state = Puzzle(state.current_state)
                new_state.solution_string = state.solution_string
                new_state.depth = state.depth
                new_state.previous_direction = direction
                new_state.make_move(direction)

                if new_state.depth > self.max_depth:
                    self.max_depth = new_state.depth

                # If new state is solved, we set params and flag to true
                if new_state.check_if_solved():
                    self.result_string = new_state.solution_string
                    self.end_time = time.perf_counter()
                    self.solution_found = True

                else:
                    to_reverse.append(new_state)

        to_reverse.reverse()
        for single in to_reverse:
            self.frontier.append(single)
            self.number_of_visited += 1
Exemplo n.º 24
0
    def post_initialisations(self):
        """ Do some extra initializations.

        Display the version if a labelVersion is found.
        Set defaults (try to load them from a configuration file):
            - Window size and state (width, height and if maximized)
        Load other saved custom settings.
        """
        # Set previous size and state
        width = settings.get('width', 350)
        height = settings.get('height', 350)
        self.set_title(self.app.localizedname)
        self.resize(width, height)
        if settings.get_bool('maximized', False):
            self.maximize()

        # Load any other settings here.
        if self.app.show_simple:
            self.boxMenu.set_visible(not self.app.show_simple)
            self.boxMenu.set_no_show_all(True)
        if not self.app.show_pieces:
            self.listboxPieces.set_no_show_all(True)
        if not self.app.show_timer:
            self.boxTimer.set_no_show_all(True)
        self.listboxPieces.set_visible(self.app.show_pieces)
        self.imageClock.set_visible(self.app.show_timer)
        self.labelClock.set_visible(self.app.show_timer)
        if self.app.thehistory:  # history passed, user wants replay.
            self.set_sensitive(False)
            self.playing_history = True
            self.puzzle = Puzzle(self.app.puzzle_str, self.app.strings_to_use,
                                 self.app.font_scale, self.app.thehistory)
        else:
            self.start_puzzle()
Exemplo n.º 25
0
def Astar_search(initial_state):
    count = 0
    #lista de noh ja exp´lorados
    explored = []
    #noh inicial
    start_node = Puzzle(initial_state, None, None, 0, True)
    #fila de prioridade
    q = PriorityQueue()
    #adiciono na fila a funcao de avaliacao f=g+h, contador, e meu noh
    # a priridade é pelo menor valor da funcao
    q.put((start_node.evaluation_function, count, start_node))
    #enquanto a fila nao for vazia
    while not q.empty():
        #pego os 3 itens da lista
        node = q.get()
        #seleciono o noh
        node = node[2]
        #adciono o noh a lista de explorados
        explored.append(node.state)
        #verifica se o noh atual é o objetivo
        if node.goal_test():
            return node.find_solution()
        #encontro todos so filhos do meu noh atual
        children = node.generate_child()
        #pra cada filho
        for child in children:
            #se n foi explorado
            if child.state not in explored:
                count += 1
                #adiciona novo noh na fila
                q.put((child.evaluation_function, count, child))
    return
Exemplo n.º 26
0
 def start_puzzle(self):
     self.picker = NumberPicker(self, thelist=self.app.strings_to_use)
     self.picker.set_type_hint(Gdk.WindowTypeHint.DIALOG)
     self.puzzle = Puzzle(self.app.puzzle_str, self.app.strings_to_use,
                          self.app.font_scale)
     self.timer_started = datetime.datetime.utcnow()
     GObject.timeout_add(500, self.show_time_passed)
Exemplo n.º 27
0
def hillclimbing(dim, iters):
    puz = Puzzle(dim)
    puz.printmovenums()
    puz.printdistances()

    initialevaluation = puz.evaluation

    evaluation = puz.evaluation

    for i in range(1, iters + 1):

        swp = puz.swaprandommovenum()

        # Evaluation dropped so revert swap
        if puz.evaluation < evaluation:
            print('\nEvaluation worsened... reverting swap')
            puz.revertswap(swp)
            continue
        else:
            evaluation = puz.evaluation
            print('\nIteration: ', i)
            puz.printswap(swp)
            print('Evaluation: ', evaluation)

            # UNCOMMENT IF YOU WANT FULL DETAILS OF SWAP
            # puz.printmovenums()
            # puz.printdistances()

    print('\n----- RESULTS -----')
    print('Initial Evaluation: ', initialevaluation)
    print('Final Evaluation: ', evaluation)
    return puz
Exemplo n.º 28
0
def breadth_first_search(initial_state):
    #no inicial
    start_node = Puzzle(initial_state, None, None, 0)
    #verifica se o noh é o final
    if start_node.goal_test():
        #se sim volta pra encontrar a solucao
        return start_node.find_solution()
    #fila pra auxilar na vusca do bfs
    q = Queue()
    #inicia com o noh inicial
    q.put(start_node)
    #lista de noh ja explorados
    explored = []
    #enquanto existir nohs na fila
    while not(q.empty()):
        #pega o primeiro noh da fila
        node = q.get()
        #adicionada o noh na lista de explorados
        explored.append(node.state)
        #pego todos on noh filhos do meu noh atual
        children=node.generate_child()
        #pra cada filho na lista eu faço
        for child in children:
            #verifico se o filho encontrado ja foi explorado
            if child.state not in explored:
                #verifico se esse filho é meu objetivo
                if child.goal_test():
                    return child.find_solution()
                #adiciono o filho na lista de noh para explorar
                q.put(child)
    return
Exemplo n.º 29
0
 def test_incomplete_state(self):
     puzzle_input = [x for x in range(9)]
     for _ in range(10):
         while puzzle_input == [1,2,3,4,5,6,7,8,0]:
             random.shuffle(puzzle_input)
         puzzle = Puzzle(puzzle_input)
         self.assertFalse(puzzle.puzzle_check())
Exemplo n.º 30
0
    def swap_solve(self):
        """
        swap solve is the method called when the swap_button is clicked. Once clicked,
        makes sure that the buttons representing the swapping puzzle tiles are
        a valid puzzle. If they are, it initializes the solving algorithm
        and sets the resulting solution set as the input to change from a puzzle
        frame to a soln frame. If the tiles aren't validated, produces an error
        message box.

        Returns
        -------
        None.

        """
        self.swap_btn['state'] = 'disabled'
        self.shift_btn['state'] = 'disabled'
        if Puzzle.validate(self._get_tiles()):
            puzzle = Puzzle(self._get_tiles())
            puzzle = H.heuristic_swap(puzzle)
            soln_set = puzzle.get_soln_states()
            self.master.get_soln_frame(soln_set)
        else:
            #input that's failed validation throws error messagebox
            messagebox.showerror(title="Input error", message=ERROR_MSG)
            self.swap_btn['state'] = 'normal'
            self.shift_btn['state'] = 'normal'