def main(): start, goals, walls, goals_ls, boxes_ls = read() ## ##Comment out any of the function you don't want to use. For levels 10 ##and higher, only use the rank/unrank implementiation of each search, ##(the name is followed by a 2 if ranking/unranking is used) ## print("\nBestFS") #BestFS no rank/unrank: heuristic can be: boxes, manhattan best_fs(start, goals, walls, boxes, cornered=True, verbose=False) #BestFS with rank/unrank: heuristic can be: boxes, manhattan best_fs2(start, goals, walls, boxes, cornered=True, verbose=False) print("\nA*") #A Star no rank/unrank: heuristic can be: boxes, manhattan a_star(start, goals, walls, boxes, cornered=True, verbose=False) #A Star with rank/unrank: heuristic can be: boxes, manhattan a_star(start, goals, walls, boxes, cornered=True, verbose=False) print("\nA* with is_stuck") #A Star using is_stuck: heuristic can be: boxes, manhattan Astar_stuck(start, goals, walls, boxes, boxes_ls, goals_ls, verbose=False) #A Star using is_stuck and rank/unrank: heuristic can be: boxes, manhattan Astar_stuck2(start, goals, walls, boxes, boxes_ls, goals_ls, verbose=False) print("\nBranch and Bound") #Branch and Bound no rank/unrank: heuristic can be: boxes, manhattan b_bound(start, goals, walls, boxes, cornered=True, verbose=False) #Branch and Bound with rank(no pruning): heuristic can be: boxes, manhattan b_bound2(start, goals, walls, boxes, cornered=True, verbose=False)
def main(argv): fd = parse_arg(argv) start, goal, dimension = readfile(fd) if not isSolvable(start, goal, dimension): print("This puzzle cannot be solved. Try generating another one.") sys.exit() start = Node(start) items = {'1': 'Manhattan Distance', '2': 'Misplaced Tiles', '3': 'Linear Conflict', '4': 'Greedy BFS', '5': 'Dijkstra'} choice = input("Welcome to our n-puzzle program. Please choose between the 3 following heuristics to solve the problem :\n 1: 'Manhattan Distance'\n 2: 'Misplaced Tiles'\n 3: 'Linear Conflict'\n 4: 'Greedy BFS [bonus]'\n 5: 'Dijkstra [bonus]'\n Select your heuristic (1, 2, 3, 4 or 5): ") if choice in items: heuristic = items[choice] else: print("Not a correct value") sys.exit() res, closedlist, openlist, num_moves = a_star(start, goal, heuristic) time_complex = len(closedlist) size_complex = len(openlist) + time_complex for i in res: print("Move", i.g) for l in i.grid: line = [] for n in l: line.append(n) print(*line, sep=' ') print("\n") print("Time complexity: ", time_complex) print("Size complixity: ", size_complex) print("Total number of moves", num_moves)
def path(self, start, end): # h = heuristic.default h = heuristic.manhattan_distance # h = heuristic.max_difference # h = heuristic.min_difference # h = heuristic.avg_difference return a_star(start, end, self.grid, heuristic=h)
def _solve_2D(self, model): """Returns optimal 2D partitioning for winner.""" if self.algorithm == "a_star": initial = [[] for _ in range(model.n_dists)] nodes = list(model.model.flatten()) w_solution = a_star((initial, nodes), model.model, self.winner, model.total_units) w_score = self.score(w_solution[0]) print(w_solution[0]) l_solution = a_star((initial, nodes), model.model, 1 - self.winner, model.total_units) l_score = self.score(l_solution[0]) print(l_solution[0]) return w_score, w_solution, l_score, l_solution raise NotImplementedError
def callingAStar(self): a_star_path = a_star(self.move_list, self.map_size, self.start, self.goal, self.walls, self.pits) #print "a_star_path" toPub = [] for entry in reversed(a_star_path): toPub.append(ast.literal_eval(entry)) step = ast.literal_eval(entry) #print step self.a_pub.publish(step)
def callingAStar(self): a_star_path = a_star( self.move_list, self.map_size, self.start, self.goal, self.walls, self.pits) #print "a_star_path" toPub = [] for entry in reversed(a_star_path): toPub.append(ast.literal_eval(entry)) step = ast.literal_eval(entry) #print step self.a_pub.publish(step)
def path_to_goal_exists(self, agent_name): """ Uses A-Star to check if this agent has a path from it's current position to it's goal""" start = self.agent_positions[agent_name] if agent_name == BoardElement.AGENT_TOP: goal_edge = constants.BOARD_SIZE - 1 else: goal_edge = 0 goal_test = lambda point: point.Y == goal_edge heuristic = lambda point: abs(point.Y - goal_edge) path_length = a_star(self.get_valid_neighbors, start, goal_test, heuristic) return path_length != -1
def gen_walk_path(): #map_pred = Image.open('map_result.bmp') map_pred = Image.open('result.bmp') map_pred = np.array(map_pred) map_pred_1ch = np.zeros((13, 18)) for i in range(0, 13): for j in range(0, 18): map_pred_1ch[i][j] = map_pred[i][j][0] result = a_star(map_pred_1ch, blocks=20) ''' data=np.zeros(shape=(11, 16)) for i in result: data.flat[i]=1 ''' #os.chdir("../") # change directory to where images stored returnList = [result, map_pred] return returnList
def update(self, player): d, route = a_star(Enemy.stage_data, (self.x, self.y), (player.x, player.y)) if d == 'inf': print("route is missing!") return if route is None: print("route is None!") tmp = route[(player.x, player.y)] new_x = player.x new_y = player.y while tmp != (self.x, self.y): if tmp is None: print("tmp is None!") new_x = tmp[0] new_y = tmp[1] tmp = route[tmp] if self.x - new_x == 1: self.direct = 3 if self.x - new_x == -1: self.direct = 1 if self.y - new_y == 1: self.direct = 0 if self.y - new_y == -1: self.direct = 2 if (new_x, new_y) == (player.x, player.y): DataCollector.damaged() AtkEffect.generate(player.x, player.y, player.x, player.y) player.hp -= self.atk return for enemy in RogueLike.enemy_list: if enemy != self: if enemy.x == new_x and enemy.y == new_y: return if not RogueLike.stage.collision(new_x, new_y): self.x = new_x self.y = new_y
def main(): g = Grid(7, 7, obstacles=[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6)]) src = (0, 0) dest = (6, 6) print("Grid visualization: ") print(g) print( "\nLegend:\n\tS = Start\n\tE = End\n\tX = Obstacle\n\t_ = Empty space") print("\nPath by Dijkstra's algorithm:") print(g.plot_path(dijkstra(g, src, dest))) print("\nPath by A* search algorithm:") print(g.plot_path(a_star(g, src, dest)))
def load_tsp(fileName): grid, simple_graph, pacman_position, goal_positions = utils.load_puzzle( fileName) # assume there is another goal underneath pacman's original position. This will not affect how the code runs, but it does make the starting configuration easier to handle goal_positions.append(pacman_position) num_goals = len(goal_positions) # a 2-D array of the shortest distances between each pair of goal positions goal_distances = np.zeros((num_goals, num_goals), dtype=int) for i in range(num_goals): for j in range(i + 1, num_goals): dist = len( astar.a_star(simple_graph, goal_positions[i], goal_positions[j])[0]) - 1 goal_distances[i][j] = dist goal_distances[j][i] = dist # make a high cost to travel from a node to itself, since we do not want this to happen goal_distances[i][i] = 1000 return grid, goal_positions, goal_distances
def notify(self, event): if isinstance(event, CharactorMoveEvent) or isinstance(event, CharactorPlaceEvent) or isinstance(event, ActiveCharactorChangeEvent): self.fov(event.charactor) elif isinstance(event, CalculatePathRequest): goal = self.sector_by_coordinates(event.pos[0]/constants.GRID_SIZE, event.pos[1]/constants.GRID_SIZE) path = a_star(event.start_sector, goal, self) if not path == None: path.append(goal) for index, node in enumerate(path): if index < len(path)-1: new_event = CharactorTurnAndMoveRequest(node.neighbors.index(path[index+1])) self.event_manager.post(new_event) elif isinstance(event, OccupiedSectorAction): event.function(self.charactor_by_coordinates(event.pos[0], event.pos[1])) elif isinstance(event, CharactorPlaceRequest): if not len(self.free_start_sector_indices) == 0: event.charactor.place(self.sectors[self.free_start_sector_indices.pop(0)])
def find_food(board, food_list, head): nearest_food = None shortest_path = None path_length = sys.maxsize for food in food_list: food_path = a_star(head, food, board) if food_path != None and shortest_path == None: shortest_path = food_path nearest_food = food if food_path != None and shortest_path != None and len( shortest_path) > len(food_path): shortest_path = food_path nearest_food = food if shortest_path != None: return shortest_path[1] else: return None
r_t, p_t, y_t = euler_from_quaternion(quat_tmp) origin_cache.append(y_t) res = map_cache.info.resolution map_origin = (int(-origin_cache[0] / res), int(-origin_cache[1] / res)) start_cc = [ int(start_cache[0] / res) + map_origin[0], int(start_cache[1] / res) + map_origin[1], 0 ] goal_cc = [ int(goal_cache[0] / res) + map_origin[0], int(goal_cache[1] / res) + map_origin[1], 0 ] # Running A* generated_path = astar.a_star(start_cc, goal_cc, map_cache) print "Finished running A* algorithm" if generated_path != None and not rospy.is_shutdown(): print "Updated RViz with path" rvizPath(generated_path, map_cache) path = genWaypoints(generated_path, map_cache) waypoints_pub.publish(path) print "Published generated path to topic: [/lab4/waypoints]" print "Waypoints:" tmp_wp_ctr = 0 for waypoint in path.poses: print tmp_wp_ctr, ": [", waypoint.pose.position.x, ", ", waypoint.pose.position.y, "]" tmp_wp_ctr += 1
from idastar import ida_star from astar import a_star def take_input() -> State: with open('input.txt', 'r') as input_file: goal: List[Tuple[int, int, int]] = [] for _ in range(3): goal.append(tuple(map(lambda x: int(x), input_file.readline().split()))) input_file.readline() initial: List[Tuple[int, int, int]] = [] for _ in range(3): initial.append(tuple(map(lambda x: int(x), input_file.readline().split())) ) return State(initial, goal) if __name__ == '__main__': print('Running...') state: State = take_input() sys.stdout = open('outputA.txt', 'w') res = a_star(state) if res is None: print('fail') sys.stdout = open('outputIDA.txt', 'w') res = ida_star(state) if res is None: print('fail')
g = Graph[int, int]() g.insert_vertex(0) g.insert_vertex(1) g.insert_vertex(2) g.insert_vertex(3) g += 4 g.insert_edge(0, 1, 0.5) g.insert_edge(0, 3, 0.5) g.insert_edge(1, 0, 0.5) g.insert_edge(1, 2, 1) g.insert_edge(1, 3, 1) g.insert_edge(1, 4, 1) g.insert_edge(2, 1, 1) g.insert_edge(2, 4, 1.5) g.insert_edge(3, 0, 0.5) g.insert_edge(3, 1, 1) g.insert_edge(3, 4, 2) g.insert_edge(4, 1, 1) g.insert_edge(4, 2, 1.5) g += (4, 3, 2) print(g) print(repr(g)) print(g.dfs(0, lambda x: x)) print(g.bfs(0, lambda x: x), "\n") cd, pd = dijkstra(g, 3, 1) ca, pa = a_star(g, 3, 1) print("\nDijkstra algorithm from node 3 to node 1:\nCost = {0}, path: {1}". format(cd, pd)) print( "A* algorithm from node 3 to node 1:\nCost = {0}, path: {1}\n".format( ca, pa))
import astar import numpy as np # Define a start and goal location start = (0, 0) goal = (4, 4) # Define your grid-based state space of obstacles and free space grid = np.array([ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 0, 0], ]) path, path_cost = astar.a_star(grid, astar.heuristic, start, goal) print(path_cost, path) # S -> start, G -> goal, O -> obstacle s = astar.visualize_path(grid, path, start) print(s)