def test_one_node(self): """Graph with a unique vertice.""" node_1 = (0, 0) graph = {node_1: {"neighbors": []}} path, distance = a_star(graph, node_1, node_1) self.assertEqual(path, [(0, 0)]) self.assertEqual(distance, 0.0)
def test_two_nodes(self): node_1 = (0, 0) node_2 = (0, 1) graph = {node_1: {"neighbors": [node_2]}, node_2: {"neighbors": [node_1]}} path, distance = a_star(graph, node_1, node_2) self.assertEqual(path, [(0, 0), (0, 1)]) self.assertEqual(distance, 1.0)
def test_three_nodes_2(self): """Tres nodos encadenados en linea recta.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (2, 0) graph = {node_1: {"neighbors": [node_2]}, node_2: {"neighbors": [node_3]}, node_3: {"neighbors": [node_2]}} path, distance = a_star(graph, node_1, node_3) self.assertEqual(path, [(0, 0), (1, 0), (2, 0)]) self.assertEqual(distance, 2.0)
def test_three_nodes_1(self): """Tres nodos equidistantes.""" node_1 = (0, 0) node_2 = (0, 1) node_3 = (1, 0) graph = { node_1: {"neighbors": [node_2, node_3]}, node_2: {"neighbors": [node_1, node_3]}, node_3: {"neighbors": [node_1, node_2]}, } path, distance = a_star(graph, node_1, node_2) self.assertEqual(path, [(0, 0), (0, 1)]) self.assertEqual(distance, 1.0)
def test_four_nodes_1(self): """Grafo de 4 nodos, todos interconectados.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (0, 1) node_4 = (1, 1) graph = { node_1: {"neighbors": [node_2, node_3, node_4]}, node_2: {"neighbors": [node_1, node_3, node_4]}, node_3: {"neighbors": [node_1, node_2, node_4]}, node_4: {"neighbors": [node_2, node_3, node_1]}, } path, distance = a_star(graph, node_1, node_4) self.assertEqual(path, [(0, 0), (1, 1)]) self.assertEqual(round(distance, 5), 1.41421)
def test_four_nodes_2(self): """Grafo de 4 nodos, interconectados como un cuadrado.""" node_1 = (0, 0) node_2 = (1, 0) node_3 = (0, 1) node_4 = (1, 1) graph = { node_1: {"neighbors": [node_2, node_3]}, node_2: {"neighbors": [node_1, node_4]}, node_3: {"neighbors": [node_1, node_4]}, node_4: {"neighbors": [node_2, node_3]}, } path, distance = a_star(graph, node_1, node_4) self.assertEqual(path, [(0, 0), (1, 0), (1, 1)]) self.assertEqual(distance, 2.0)
def ai_control(ai): is_running = True is_paused = False while is_running: for event in ai.get(): if event.type == EXIT: is_running = False break elif event.type == PAUSE: is_paused = not is_paused if is_running and (not is_paused): """ #Mensagens de depuração evt = pygame.event.Event(pygame.USEREVENT, {"action" : PRINT_G, "value" : ai.G}) pygame.event.post(evt) """ #Localiza fantasmas da grade pht = find_phantoms(ai.G) for p in pht: #copia e marca a grade G = copy_g(ai.G, p) #encontra menor caminho para o pacman res = a_star.a_star(G) if res != None: caminho = [] pi = res['pi'] t = res['t'] a_star.gera_caminho(caminho, pi, t); #envia decisao da AI if len(caminho) > 1: evt = pygame.event.Event(pygame.USEREVENT, {"action" : MOVE_P, "value" : caminho[1], "origin" : p, "dest": t}) pygame.event.post(evt) time.sleep(ai.speed)
def test_six_nodes(self): """Ejemplo copiado de la Wikipedia.""" node_1 = (1, 0) node_2 = (0, 1) node_3 = (2, 1) node_4 = (2, 3) node_5 = (4, 2) node_6 = (3, 0) graph = { node_1: {"neighbors": [node_2, node_3, node_6]}, node_2: {"neighbors": [node_1, node_3, node_4]}, node_3: {"neighbors": [node_1, node_2, node_4, node_6]}, node_4: {"neighbors": [node_2, node_3, node_5]}, node_5: {"neighbors": [node_4, node_6]}, node_6: {"neighbors": [node_1, node_3, node_5]}, } path, distance = a_star(graph, node_1, node_5) self.assertEqual(path, [(1, 0), (3, 0), (4, 2)]) self.assertEqual(round(distance, 5), 4.23607)
def main(): parser = argparse.ArgumentParser() optns = parser.parse_args() start = None goal = None lines = [] for y, line in enumerate(line.rstrip('\n') for line in sys.stdin): for x, char in enumerate(line): pos = x, y if char == 'G': goal = pos elif char == 'S': start = pos lines.append(line) def neighbours(pos): for x in range(pos[0]-1, pos[0]+2): for y in range(pos[1]-1, pos[1]+2): if (x, y) == pos: continue if y not in range(len(lines)): continue if x not in range(len(lines[y])): continue if lines[y][x] not in '. SG': continue yield x, y def estimate_cost(pos, goal): return math.sqrt((pos[0]-goal[0])**2 + (pos[1]-goal[1])**2) def dist(a, b): assert max(map(abs, map(operator.sub, a, b))) == 1 ret = estimate_cost(a, b) if lines[b[1]][b[0]] != '.': ret *= 2 return ret path = set(a_star.a_star(start, goal, neighbours, estimate_cost, dist)) for y, line in enumerate(lines): for x, char in enumerate(line): print('X' if (x, y) in path and char not in 'SG' else char, end='') print()
if map_index == 0: source = (3, 5) target = (2, 18) elif map_index == 1: source = (0, 1) target = (34, 20) elif map_index == 2: source = (3, 9) target = (30, 9) elif map_index == 3: source = (0, 10) target = (15, 1) directions = ["vertical", "horizontal"] direction_index = input("Enter preferred direction for jump point search: \n0 for vertical, \n1 for horizonal \n") direction = directions[direction_index] dijkstra_path = nx.dijkstra_path(graph, source, target) graph_constructor.draw_path(graph, dijkstra_path, "Dijkstra") a_star_path = a_star.a_star(graph, source, target) graph_constructor.draw_path(graph, a_star_path, "A Star") jps_path = a_star_jps.a_star_jps(graph, source, target, direction) graph_constructor.draw_path(graph, jps_path, "Jump Point Search")
def handle_client(self, socket, data, mask): if mask & selectors.EVENT_READ: received = socket.recv(1024) if received: self.incoming += received.decode("ascii") self.last_read = self.tick if len(self.incoming) > 0 and self.incoming[-1] == "\n": split = self.incoming.split("\n") if len(split) > 1: for line in split: words = line.split(" ") if words[0] == "add": id = int(words[1]) position = (float(words[2]), float(words[3]), float(words[4])) self.nodes[id] = Node(id, position) print(f"Added node {id}") # print(f"Created node {id} at position {position}") elif words[0] == "neighbor": id1 = int(words[1]) id2 = int(words[2]) if id1 not in self.nodes: print( f"{id1} not in nodes, could not link to {id2}" ) elif id2 not in self.nodes: print( f"{id2} not in nodes, could not link to {id1}" ) else: self.nodes[id1].neighbors.append( self.nodes[id2]) print(f"Linked node {id1} and {id2}") elif words[0] == "simplify": self.navmesh = Navmesh(0, self.nodes) print(f"Simplified navmesh") elif words[0] == "visualize": self.navmesh.visualize() print(f"Visualizing navmesh") elif words[0] == "path": path_id = int(words[1]) start = int(words[2]) end = int(words[3]) if start in self.nodes and end in self.nodes: starttime = time.time() path = a_star(self.nodes[start], self.nodes[end]) self.outgoing = f"path {path_id}" if path != False: for node in path: self.outgoing = f"{self.outgoing} {node.id}" self.outgoing = self.outgoing + "\r\n" print( f"Completed path in {time.time() - starttime}" ) else: self.outgoing = f"error {path_id}" print( f"Error completing path (a_star = false)" ) else: self.outgoing = f"error {path_id}" print(f"Error completing path") self.incoming = "" else: # kill the server on disconnect self.selector.unregister(self.socket) self.socket.close() if self.outgoing != "": socket.send(self.outgoing.encode("ascii")) self.outgoing = ""
def main(): # setting grid dimensions x = 18 y = 17 # make variables containing the grid coordinates and the route scheme (netlist) route = GridMatrix(x, y) matrix = a_star(x, y, "grid_2.txt") routes = route.read_routes("g_scheme_3_grid_2.txt") routes_lijstje = [] Total_routes = 0 # draw every line in the grid for i in range(len(routes)): i = matrix.new_line(routes[i][0],routes[i][1], i+1) routes_lijstje.append(i) Total_routes += len(i) # if the routes cross at some point, try to solve it using a sort of hillclimber loops = 0 crosses = look_for_crosses(routes_lijstje) best_cross = count_for_crosses(routes_lijstje) best_lines = list(routes_lijstje) best_layers = list(matrix.layers) # infinite loop till solution (no crosses) is found while crosses != [] : # get the last best known grid routes_lijstje = best_lines matrix.layers = best_layers loops += 1 # if you tried 10 times a different approach to find a solution (also in this way an infinite loop is improbable) if (loops%10) == 0: if crosses == []: break # take 4 random routes of the list rand = randrange(len(routes_lijstje) - 1) rand2 = randrange(len(routes_lijstje) - 1) rand3 = randrange(len(routes_lijstje) - 1) rand4 = randrange(len(routes_lijstje) - 1) # take 1 of the remaining crosses cross_length = randrange(len(crosses)) #make sure you do not take away the same line if rand == rand2: rand2 += 1 rand2 = rand2%(len(routes_lijstje) - 1) if rand3 == rand: rand3 += 2 rand3 = rand3%(len(routes_lijstje) - 1) elif rand3 == rand2: rand3 += 1 rand3 = rand3%(len(routes_lijstje) - 1) if rand4 == rand: rand4 -= 1 rand4 = rand4%(len(routes_lijstje) - 1) elif rand4 == rand2: rand3 += 2 rand3 = rand4%(len(routes_lijstje) - 1) elif rand4 == rand3: rand4 += 1 rand4 = rand4%(len(routes_lijstje) - 1) # pop the 5 lines out of the grid and try to re-arange them matrix.delete_line(routes_lijstje[rand]) matrix.delete_line(routes_lijstje[rand2]) matrix.delete_line(routes_lijstje[rand3]) matrix.delete_line(routes_lijstje[rand4]) matrix.delete_line(routes_lijstje[crosses[cross_length][0]]) newline = matrix.new_line(routes[crosses[cross_length][0]][0],routes[crosses[cross_length][0]][1], crosses[cross_length][0] + 1) newline1 = matrix.new_line(routes[rand][0],routes[rand][1], rand + 1) newline2 = matrix.new_line(routes[rand2][0],routes[rand2][1], rand2 + 1) newline3 = matrix.new_line(routes[rand3][0],routes[rand3][1], rand3 + 1) newline4 = matrix.new_line(routes[rand4][0],routes[rand4][1], rand4 + 1) routes_lijstje.pop(rand) routes_lijstje.insert(rand, newline1) routes_lijstje.pop(rand2) routes_lijstje.insert(rand2, newline2) routes_lijstje.pop(rand3) routes_lijstje.insert(rand3, newline3) routes_lijstje.pop(rand4) routes_lijstje.insert(rand4, newline4) routes_lijstje.pop(crosses[cross_length][0]) routes_lijstje.insert(crosses[cross_length][0], newline) count_cross = count_for_crosses(routes_lijstje) else: # take one cross of the grid aand pop the lines and reroute them rand = randrange(len(routes_lijstje) - 1) cross_length = randrange(len(crosses)) matrix.delete_line(routes_lijstje[crosses[cross_length][1]]) matrix.delete_line(routes_lijstje[crosses[cross_length][0]]) newline = matrix.new_line(routes[crosses[cross_length][0]][0],routes[crosses[cross_length][0]][1], crosses[cross_length][0] + 1) newline1 = matrix.new_line(routes[crosses[cross_length][1]][0],routes[crosses[cross_length][1]][1], crosses[cross_length][1] + 1) routes_lijstje.pop(crosses[cross_length][1]) routes_lijstje.insert(crosses[cross_length][1], newline1) routes_lijstje.pop(crosses[cross_length][0]) routes_lijstje.insert(crosses[cross_length][0], newline) count_cross = count_for_crosses(routes_lijstje) crosses = look_for_crosses(routes_lijstje) temp_total = 0 for i in routes_lijstje: temp_total += len(i) if count_cross < best_cross: best_cross = count_cross best_lines = list(routes_lijstje) best_layers = list(matrix.layers) Total_routes = temp_total elif count_cross == best_cross and temp_total < Total_routes: best_cross = count_cross best_lines = list(routes_lijstje) best_layers = list(matrix.layers) Total_routes = temp_total if loops == 500: break counter = 0 # check for empty last layer empty = 0 for i in best_layers: count = 0 for j in i: d = sum(j) if d == 0: count += 1 if count == y: empty += 1 # pop the empty layers if empty > 0: for i in range(1, empty+1): best_layers.pop(length_l - i) # count the layers and print the layers for column in best_layers: counter += 1 for row in column: print if isinstance(row, int): sys.stdout.write("%03d " % (row)) sys.stdout.write(" ") sys.stdout.flush() else: row = str(row) sys.stdout.write(row) print # results print counter, best_cross, Total_routes
import numpy as np from manhatten import calculateManhattenDistance from disposition import calculateDispositionSum from tree import Node import helper from a_star import a_star initial_state = np.array([[7, 2, 4], [5, 0, 6], [8, 3, 1]]) goal_state = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) if (initial_state.shape != goal_state.shape): print("initial and goal shape must be equal") exit(1) # TODO: assert that all numers between 0-9 exist in both matrixes n = 3 nn = 9 root = Node(arr=initial_state, name="root", h=0, g=0, parent=None) goal = Node( arr=goal_state, name="goal", h=0, g=0, ) solution = a_star(root, goal, calculateManhattenDistance) print("found solution :)", solution.name, solution.g)
# # Debug # for i in neighs: # print(i.last_node() + " " + str(i.f())) # print("-------------------") # time.sleep(1) return neighs if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("input", help="Input file name") parser.add_argument("output", help="Output file name") args = parser.parse_args() board_str = "" with open(args.input) as input_file: board_str = input_file.read() start_state = list(map(int, board_str.split())) start = chain15(start_state) end = chain15((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0)) result = a_star.a_star(start, end.last_node()) with open(args.output, 'w') as output_file: print(str(len(result.history)), file=output_file) for node in result.history: print(str(node), file=output_file) print("-------------------------", file=output_file) print(str(result), file=output_file)
def monotonic_abstraction(node): res = a_star(HeuristicGraph(), node, trivial_heuristic) if res == None: return math.inf return len(res[1])
test_grid = { 'size': 12, 'obstacles': [(3, 0), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 6), (5, 6), (6, 6)], 'start': (0, 0), 'end': (11, 11) } g = Graph(test_grid) p = g.make_obs() #Testing Dijkstra #_,_,path = dijkstra(test_grid) #Testing A* path = a_star.a_star(test_grid) ''' #Display to terminal for v in path: p[v] = 111 #print v print p ''' #Plot o_x, o_y = zip(*test_grid['obstacles']) p_x, p_y = zip(*path) plt.plot(o_x, o_y, 'rs', ms=50) plt.plot(p_x, p_y, lw=5) #Maximize window
pygame.mixer.music.load('res/gameMusic1.mp3') pygame.mixer.music.play(-1) #positions must be divisible by tile dimensions (32) # enemy1=Enemy(200,240) player=Player(32*2,32*4) while True: # screen.fill([255,255,255]) screen.blit(background,(0,0)) if total_frames % 6*FPS == 0: print(len(Enemy.List)) Enemy.spawn(total_frames,FPS) Enemy.update(screen,player) player.movement() Projectile.projectile_physics(screen) a_star(screen,player,total_frames,FPS) player_input(screen,player) Tile.draw_tiles(screen) utils.text_to_screen(screen,"Health: {0}".format(player.health),0,0) #utils.text_to_screen(screen,"This is your font",250,250,50) player.draw_player(screen) pygame.display.flip() #generate display clock.tick(FPS) #Pygame to set FPS total_frames += 1 if player.health<=0: sleep(2.5) screen.blit(pygame.image.load('res/endgame.jpg'),(0,0)) pygame.display.update() break sleep(4)
import sys from a_star import a_star from models.puzzle import Puzzle, criteria puzzle = Puzzle(sys.argv[1]) print(a_star(puzzle, criteria))
path.append(array[len(array) - 1]) return path if __name__ == '__main__': # load the map gmap = OccupancyGridMap.from_png('among-us-edges-fixed-ai1.png', .05) # set a start and an end node (in meters) start_node = (15, 12) ##AMONG US: Where we are goal_node = (22, 7) ##AMONG US: Where the task is :) # run A* path, path_px = a_star(start_node, goal_node, gmap, movement='4N') gmap.plot() if path: # plot resulting path in pixels over the map plot_path(path_px) else: print('Goal is not reachable') # plot start and goal points over the map (in pixels) start_node_px = gmap.get_index_from_coordinates( start_node[0], start_node[1]) goal_node_px = gmap.get_index_from_coordinates(goal_node[0], goal_node[1])