示例#1
0
def main():
    test_no = 0
    # test case format: (my_car, other_cars, dimensions)
    test_cases = [([(1, 2), (2, 2)], [[(4, 5), (5, 5)], [(4, 1), (4, 2),
                                                         (4, 3)],
                                      [(2, 4), (2, 5)]], 5, (5, 2)),
                  ([(3, 3), (3, 4)], [[(1, 2), (1, 3)], [(1, 5), (1, 6)],
                                      [(2, 2), (3, 2)], [(1, 4), (2, 4)],
                                      [(2, 6), (3, 6)], [(4, 6),
                                                         (5, 6)]], 6, (3, 6))]

    for my_car, other_cars, dimensions, goal in test_cases:
        test_no += 1
        initial_state = (my_car, other_cars)
        print("\nTest Case: %d, %s" % (test_no, initial_state))

        root = ParkinglotNode(dimensions=dimensions,
                              goal=goal,
                              state=initial_state,
                              path=[])

        print("Root Initial State: %s" % (str(root.state)))

        print("Running A* using the Dominating Heuristic:")
        print(
            "Node: %s\n Total Nodes Examined: %d" %
            (a_star(root, dominating_heuristic, cost_fn, node_count_max=5000)))

        print("Running A* using the Dominated Heuristic:")
        print(
            "Node: %s\n Total Nodes Examined: %d" %
            (a_star(root, dominated_heuristic, cost_fn, node_count_max=5000)))

        del root
示例#2
0
def main():
    # test case structure: ([piles], n, counter)
    test_cases = [([[], [], [4, 5, 1, 2, 6, 7, 10, 9, 3, 8]], 3, 10),
                  ([[2, 11, 4], [3, 12, 6, 1], [7, 8, 9], [10, 5]], 4, 12)]

    test_case = 0

    for state, n, counter in test_cases:
        test_case += 1
        print("\nTest Case: %d, %s" % (test_case, state))

        root = FreeCellNode(counter=counter, n=n,
                            state=state, path=[], root=True)

        print("Running A* using the Dominating Heuristic:")
        try:
            print("Node: %s\n Total Nodes Examined: %d" %
                  (a_star(root, dominating_heuristic, cost_fn, node_count_max=15000)))
        except TypeError:
            print("No Solution Found.")

        print("Running A* using the Dominated Heuristic:")
        try:
            print("Node: %s\n Total Nodes Examined: %d" %
                  (a_star(root, dominated_heuristic, cost_fn, node_count_max=15000)))
        except TypeError:
            print("No solution Found.")

        del root
示例#3
0
    def __init__(self, maze_data, maze_tree, mazeinfo):
        # initialize a dictionary for storing all step distances between
        # significant points in the maze (all goals and the start)
        self.dict = {}

        # get all points to generate distances between
        points = []
        points.append((mazeinfo.startpx, mazeinfo.startpy))
        for cur_point in range(0, len(mazeinfo.endpx)):
            points.append(
                (mazeinfo.endpx[cur_point], mazeinfo.endpy[cur_point]))

        # generate step distances between all points in the points array and store
        for start_point in range(0, len(points)):
            start = points[start_point]
            for end_point in range(0, len(points)):
                maze_copy = []
                maze_copy = createmaze.copy_maze(maze_data)
                root_r = MazeTree.MazeTree()
                maze_tree_copy = root_r.create_tree(maze_copy, mazeinfo,
                                                    mazeinfo.startpx,
                                                    mazeinfo.startpy)
                end = points[end_point]
                endx = []
                endy = []
                endx.append(end[0])
                endy.append(end[1])
                root = maze_tree_copy[start[0]][start[1]]
                goal = (endx, endy)
                val = search.a_star(maze_copy, mazeinfo, maze_tree_copy, root,
                                    goal, False)
                if (end, start) not in self.dict and end != start:
                    self.dict[(start, end)] = val[consts.STEPS_TAKEN_IDX()]
示例#4
0
 def calculate_path(self, treasure_pos):
     if self.algorithm == "dfs":
         return search.dfs(self.maze_grid, self.opponent_start_pos,
                           treasure_pos)
     elif self.algorithm == "bfs":
         return search.bfs(self.maze_grid, self.opponent_start_pos,
                           treasure_pos)
     elif self.algorithm == "a_star":
         return search.a_star(self.maze_grid, self.opponent_start_pos,
                              treasure_pos)
     else:
         return None
示例#5
0
def update(g):
    game = g
    draw(game)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game.running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            game.dragging = True
            pos = pygame.mouse.get_pos()
            frame_radius = game.node_radius + 5
            left, top = pos[0] - frame_radius, pos[1] - frame_radius
            mousePos = pygame.Rect(left, top, frame_radius * 2, frame_radius * 2)
            if game.creatingWalls:
                mousePos = pygame.Rect(left, top, 50, 50)
            check(mousePos, game)

        elif event.type == pygame.MOUSEMOTION:
            if game.dragging:
                pos = pygame.mouse.get_pos()
                frame_radius = game.node_radius + 5
                left, top = pos[0] - frame_radius, pos[1] - frame_radius
                mousePos = pygame.Rect(left, top, 50, 50)
                check(mousePos, game)
        elif event.type == pygame.MOUSEBUTTONUP:
            game.dragging = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                if game.creatingWalls:
                    for node in game.graph.nodes:
                        if node.isWall:
                            game.graph.adjacency[node.num, :] = 0
                            game.graph.adjacency[:, node.num] = 0

                    game.findingPath = True
                    game.graph = a_star(game.graph, update, game, alpha)
            elif event.key == pygame.K_c:
                return Game(cell_radius, rows, columns)
    pygame.display.update()
    game.clock.tick(60)

    return game
示例#6
0
def update(g):
    game = g
    draw(game)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game.running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            chosenNode = check(pos, game)

            if game.choosingStart:
                chosenNode.isStart = True
            elif game.choosingGoal:
                chosenNode.isGoal = True
            elif game.currentNode is not None and not game.currentNode == chosenNode:
                game.graph.adjacency[game.currentNode.num, chosenNode.num] = 1
                game.graph.adjacency[chosenNode.num, game.currentNode.num] = 1

            game.currentNode = chosenNode

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:  # d press
                game.currentNode = None
            elif event.key == pygame.K_s:  # s press
                game.choosingStart = True
            elif event.key == pygame.K_g:  # g press
                game.choosingGoal = True
            elif event.key == pygame.K_RETURN:  # enter press
                if game.graph.hasGoal and game.graph.hasStart:
                    game.findingPath = True  # start finding path
                    game.graph = a_star(game.graph, update, game, 0.8)
            elif event.key == pygame.K_c:  # c press
                return Game(10)  # clear graph

        elif event.type == pygame.KEYUP:
            game.choosingStart = False
            game.choosingGoal = False

    pygame.display.update()
    pathGame.clock.tick(60)
    return game
 def do_algorithm(self):
     if self.treasure_set:  # Can't find path to null position.
         if self.algorithm == "dfs":
             self.opponent_path = search.dfs(self.maze_grid, self.opponent_start_pos,
                                             self.treasure_pos)
         elif self.algorithm == "bfs":
             self.opponent_path = search.bfs(self.maze_grid, self.opponent_start_pos,
                                             self.treasure_pos)
         elif self.algorithm == "a_star":
             self.opponent_path = search.a_star(self.maze_grid, self.opponent_start_pos,
                                                self.treasure_pos)
         # Path is found
         if self.opponent_path is not None:
             self.path_started = True
             # Already started so disable key.
             # You might be surprised how important this is!
             self.screen.onkey(None, "s")
             self.start_or_continue_path()
         else:
             self.reset()  # Goal unreachable.
示例#8
0
def solve(args: argparse.Namespace) -> None:
    problem_ = rules.EightPuzzle.initialize_random(
        iterations=args.iterations,
        width=args.width,
        height=args.height)
    print(problem_)

    print("\nSearching for solution ..")
    solution_ = search.a_star(problem_, heuristics.manhattan_distance)

    print("\nFound following solution:")
    print()
    path = flatten_solution(solution_)
    for action, state in path:
        if action:
            print(action.name)
            print()
        print(state)
        print()

    _, state = path[-1]
    assert state.goal_test()
示例#9
0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.MOUSEBUTTONDOWN:
          if event.button==1 and mouse_x<95 and mouse_x>45 and mouse_y>5 and mouse_y<35:
            path = search.BFS()

          if event.button==1 and mouse_x<215 and mouse_x>165 and mouse_y>5 and mouse_y<35:
            path = search.DFS()

          if event.button==1 and mouse_x<335 and mouse_x>285 and mouse_y>5 and mouse_y<35:
            path = search.UCS() 

          if event.button==1 and mouse_x<450 and mouse_x>405 and mouse_y>5 and mouse_y<35:
            path = search.a_star()
            
          
          screen.fill(WHITE)
    draw()

    pygame.draw.rect(screen, GREY, [48,5,43,25])
    pygame.draw.rect(screen, GREY, [168,5,43,25])
    pygame.draw.rect(screen, GREY, [288,5,43,25])
    pygame.draw.rect(screen, GREY, [408,5,40,25])
    
    bfstext=font.render('BFS',True, BLACK)
    dfstext=font.render('DFS',True, BLACK)
    ucstext=font.render('UCS',True, BLACK)
    astarttext=font.render('A*',True, BLACK)
    
示例#10
0
    parent = None
    curr = None

    try:
        print('Testing start_goal')
        (start, goal) = maps.gen_start_goal_pair(grid)

        print('Testing Uniform Cost Search')
        ucs = uniform_cost_search(grid, start, goal)
        for (f, g, h, parent, curr) in ucs:
            pass
        print(g[goal])
        # output_image(grid, "ucs.png", start, goal, path(parent, curr))

        print('Testing A* Search')
        astar = a_star(grid, start, goal, manhattan_distance_a)
        for (f, g, h, parent, curr) in astar:
            pass
        print(g[goal])
        # output_image(grid, "a_star.png", start, goal, path(parent, curr))

        print('Testing A* Weighted Search')
        astar_w = a_star(grid, start, goal, diagonal_distance_n, w=2)
        for (f, g, h, parent, curr) in astar_w:
            pass
        print(g[goal])

        # output_image(grid, "a_star_w.png", start, goal, path(parent, curr))
        print('Writing to output file')
        maps.output_file(grid, start, goal,
                         args.output_file + '_' + str(i) + '.txt')
示例#11
0
 def get_path(self, start, end):
     results = search.a_star(self, start, end)
     return results
示例#12
0
# Create a graph based on the maze data
root = MazeTree.MazeTree()
maze_tree = root.create_tree(ascii_maze, mazeinfo, mazeinfo.startpx,
                             mazeinfo.startpy)

# Perform a search on the maze and export solution
if searchtype == "BFS":
    NodesExp_StepsTaken = search.bredth_first(
        ascii_maze, maze_tree[mazeinfo.startpx][mazeinfo.startpy], '.')
elif searchtype == "DFS":
    NodesExp_StepsTaken = search.depth_first(
        ascii_maze, maze_tree[mazeinfo.startpx][mazeinfo.startpy], '.')
elif searchtype == "GREEDY":
    NodesExp_StepsTaken = search.greedy_first(
        ascii_maze, maze_tree[mazeinfo.startpx][mazeinfo.startpy],
        (mazeinfo.endpx, mazeinfo.endpy))
elif searchtype == "ASTAR" and len(mazeinfo.endpx) <= 1:
    NodesExp_StepsTaken = search.a_star(
        ascii_maze, mazeinfo, maze_tree,
        maze_tree[mazeinfo.startpx][mazeinfo.startpy],
        (mazeinfo.endpx, mazeinfo.endpy), True)
elif searchtype == "ASTAR" and len(mazeinfo.endpx) > 1:
    NodesExp_StepsTaken = search.a_star(
        ascii_maze, mazeinfo, maze_tree,
        maze_tree[mazeinfo.startpx][mazeinfo.startpy],
        (mazeinfo.endpx, mazeinfo.endpy), False)

# Output the maze solution to a specified location
outputname = input("Please enter the desired outputfile name (.txt): ")
createmaze.print_maze(ascii_maze, NodesExp_StepsTaken, outputname)
示例#13
0
文件: test.py 项目: pawlactb/CS451

def dominated_heuristic(node):
    return sum([len(pile) for pile in node.state])


if __name__ == "__main__":
    # test case structure: ([piles], n, counter)
    test_cases = [([[], [], [4, 5, 1, 2, 6, 7, 10, 9, 3, 8]], 3, 10)]

    test_case = 0

    for state, n, counter in test_cases:
        test_case += 1
        print("\nTest Case: %d" % (test_case))

        root = FreeCellNode(counter=counter,
                            n=n,
                            state=state,
                            path=[],
                            root=True)
        # print(root)

        print("Running A* using the Dominating Heuristic:")
        try:
            print("Node: %s\n Total Nodes Examined: %d" %
                  (a_star(root, dominating_heuristic, cost_fn)))
        except TypeError:
            print("No Solution Found.")
            continue
    When running from the command line, compare every algorithm against
    one of the tests.
    """
    choice = sys.argv[1]
    if choice not in {'little', 'big', 'random'}:
        print('Usage: python3 test.py (little|big|random)')

    start = (0, 0)
    if choice == 'little':
        grid = [[S, N, N, N], [N, M, M, M], [N, R, R, R], [N, N, N, G]]
        goal = (3, 3)
    elif choice == 'big':
        grid = [[S, R, R, R, M, G], [N, R, R, R, M, N], [N, M, R, R, R, N],
                [N, N, N, N, R, N], [N, R, N, N, N, N], [N, R, N, N, N, N]]
        goal = (0, 5)
    elif choice == 'random':
        rows, cols = 10, 10
        goal = (random.randint(0, rows - 1), random.randint(0, cols - 1))
        types = (NORMAL, MOUNTAIN, RIVER)
        grid = [[random.choice(types) for _ in range(rows)]
                for _ in range(cols)]
        grid[start[0]][start[1]] = START
        grid[goal[0]][goal[1]] = GOAL

    # Run each algorithm and visualize the result
    print(visualize('BFS', grid, goal, bfs(grid, start, goal)))
    print(visualize('DFS', grid, goal, dfs(grid, start, goal)))
    print(visualize('Dijkstra’s algorithm', grid, goal, ucs(grid, start,
                                                            goal)))
    print(visualize('A* search', grid, goal, a_star(grid, start, goal)))
示例#15
0
文件: test.py 项目: ralphreid/SANDBOX
            [S, N, N, N],
            [N, M, M, M],
            [N, R, R, R],
            [N, N, N, G]
        ]
        goal = (3, 3)
    elif choice == 'big':
        grid = [
            [S, R, R, R, M, G],
            [N, R, R, R, M, N],
            [N, M, R, R, R, N],
            [N, N, N, N, R, N],
            [N, R, N, N, N, N],
            [N, R, N, N, N, N]
        ]
        goal = (0, 5)
    elif choice == 'random':
        rows, cols = 10, 10
        goal = (random.randint(0, rows-1), random.randint(0, cols-1))
        types = (NORMAL, MOUNTAIN, RIVER)
        grid = [[random.choice(types) for _ in range(rows)] for _ in range(cols)]
        grid[start[0]][start[1]] = START
        grid[goal[0]][goal[1]] = GOAL
    
    # Run each algorithm and visualize the result
    print(visualize('BFS', grid, goal, bfs(grid, start, goal)))
    print(visualize('DFS', grid, goal, dfs(grid, start, goal)))
    print(visualize('Dijkstra’s algorithm', grid, goal, ucs(grid, start, goal)))
    print(visualize('A* search', grid, goal, a_star(grid, start, goal)))

示例#16
0
 tic = time.time()
 bf_solution = bfs(m.start, m.goal_test, m.possible_next_locations)
 toc = time.time()
 if bf_solution is None:
     print("Breadth-first search failed to find solution")
 else:
     bf_path = node_to_path(bf_solution)
     m.mark_path(bf_path)
     print("Path from BFS:")
     print("  Path length: {}".format(len(bf_path)))
     print("  Eval time: %.5f" % (toc - tic))
     print(m)
 m.clear_path()
 heur = euclidean_distance(m.goal)
 tic = time.time()
 astar_solution = a_star(m.start, m.goal_test, m.possible_next_locations,
                         grid_cost, heur)
 toc = time.time()
 if astar_solution is None:
     print("A* search failed to find a solution")
 else:
     astar_path = node_to_path(astar_solution)
     m.mark_path(astar_path)
     print("Path from A* (euclidean):")
     print("  Path length: {}".format(len(astar_path)))
     print("  Eval time: %.5f" % (toc - tic))
     print(m)
 m.clear_path()
 heur = manhattan_distance(m.goal)
 tic = time.time()
 astar_solution = a_star(m.start, m.goal_test, m.possible_next_locations,
                         grid_cost, heur)