def main(): try: with open(sys.argv[1],"r") as f: #membaca nama file sebagai argumen program mat = [[int(num) for num in line if num!="\n"] for line in f] f.close() xawal, yawal = map(int, input("Masukkan point awal maze (format= x <spasi> y): ").split()) xakhir, yakhir = map(int, input("Masukkan point akhir maze (format= x <spasi> y): ").split()) mazemat = copy.deepcopy(mat) print("\nMatriks yang diinput: ") bfs.out(mat) print("\n\nDengan BFS: ") bobot = bfs.bfs(xawal,yawal,xakhir,yakhir,mat) bfs.out(mat) print("\nJalur yang ditempuh: ") bfs.jalur(bobot,xawal,yawal,xakhir,yakhir,mat) for i in range(len(mat)): for j in range(len(mat[i])): if (mat[i][j]==8): print(0, end=" ") elif (mat[i][j]==5): print(" ", end=" ") else: print(mat[i][j], end=" ") print() print("\nAda sebanyak",bfs.jumlah(mat),"langkah") print("\n\nDengan A*: ") ast.aStar(mazemat,xawal,yawal,xakhir,yakhir) except IndexError: print("Tidak ditemukan jalur yang tepat\nStarting point ataupun ending point salah") except FileNotFoundError: print("File not found")
def run(): filename = "boards/board-2-4.txt" board = loadBoard(filename) A, B = findAB(board) open, closed = aStar.aStar(board, A, B) c = board[B[0]][B[1]] global boardtest boardtest = visualize(filename) #print boardtest for node in open: if node.char != 'A' and node.char != 'B': boardtest[node.location[0]][node.location[1]] = '*' for node in closed: if node.char != 'A' and node.char != 'B': boardtest[node.location[0]][node.location[1]] = 'x' while c.parent != None: c = c.parent if c.char != 'A': boardtest[c.location[0]][c.location[1]] = 'o' for line in boardtest: asd = '' for char in line: asd += str(char) print asd
def executeAStar(self, msg): astart = aStar.aStar() time.sleep(.25) astart.justDoIt(self.pose.position, msg.pose.position) self.path = astart.getPath() print self.path astart.wayPoints()
def playGame(self): val = None if not self.isValid(): print("This board has no solution") return while not self.isSolved() and val != "solve": os.system('cls' if os.name == 'nt' else 'clear') print(self) print(f'Total moves: {len(self.swapHistory)}') print("type (solve) to view the solution") val = input(f'select tile to move (1 -> {self.size -1}): ') try: if val == "solve": copy = Board(presetList=self.slots.copy(), heuristic=1) copy.swapHistory.clear() solver = aStar('v', copy) solution = solver.run() solution.printHistory() return else: val = int(val) i = self.slots.index(val) j = self.slots.index(0) self.swap(i, j) except: pass os.system('cls' if os.name == 'nt' else 'clear') print(self) print('complete!')
def aStarSearch(): global endX global endY grid, x, y = buildGrid() seen, path = aStar.aStar(grid, (x, y), (endX, endY)) path.remove(path[-1]) seen.remove(seen[0]) colourBoard(seen, path)
def executeAStar(self, msg): astart = aStar.aStar() time.sleep(.25) astart.justDoIt(self.pose.position, msg.pose.position) self.path = astart.getPath() print self.path wayPoints = astart.wayPoints() print wayPoints for pnt in wayPoints: nPose = Pose() nPose.position = pnt nPose.orientation = self.pose.orientation self.navToPose(nPose) print 'lol gotem who needs to actually drive amirite'
def main(): maze = [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 1, 1, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]] map_file = open("maps/arena2.map", "r") maze = make_maze_from_file(map_file) map_file.close() g = buildVisGraph(maze, True) # origin = (1, 1) # destination = (2, 7) # origin = vg.Point(45.0, 5.0) # destination = vg.Point(6.0, 28.0) origin = (91, 2) destination = (219, 191) # origin = (40, 1) # destination = (8, 79) add_missing_edges(g, origin, destination, maze) start_node = Node(None, origin) start_node.h = euclidean_distance(origin, destination) start_node.f = start_node.g + start_node.h end_node = Node(None, destination) print("starting astar") start_time = time.time() path = aStar(maze, start_node, end_node, g) # path = dijkstra(g.visgraph, origin, destination, maze) # path = g.shortest_path(origin, destination) # print(path) print("--- %s seconds ---" % (time.time() - start_time)) for point in path: maze[point[1]][point[0]] = 6 maze[origin[1]][origin[0]] = 2 maze[destination[1]][destination[0]] = 3 root = Tk() my_gui = CellGrid(root, len(maze), len(maze[0]), 5, maze) root.mainloop()
def executeAStar(self, msg): # create new aStar object astart = aStar.aStar() rospy.sleep(.25) # search for best path astart.justDoIt(self.pose.position, msg) # get shortest path and waypoints from aStar self.path = astart.getPath() wayPoints = astart.wayPoints() wpPub = Path() wpPub.poses = wayPoints wpPub.header.frame_id = 'map' # publish path to /waypoints topic self.wp_pub.publish(wpPub) # for each waypoint, run navToPose to get to it for pose in wayPoints: self.navToPose(pose) # stop the robot self.stopTurtle() # search for next frontier using bfs from aStar goal (aka current point now) self.doBFS(msg)
def getMap(self, data): #check if the we know the goal and position if hasattr(self, "posx") and hasattr(self, "posy") and hasattr( self, "goalx") and hasattr(self, "goaly"): m = data.data #m is a 2d array to be passed to the A* print("MAP: " + m) #run the astar algo on the occupancy grid path = aStar.aStar((self.posy, self.posx), (goaly, goalx), occupancyGrid, free=255) #convert the y,x tuples to poses poses = [] for i in path: p = Pose() Pose.position.x = i[0] Pose.position.y = i[1] poses.append(p) pa = PA() pa.poses = poses self.pub.publish(pa) else: print("Unknown start/stop")
def main(): g = nx.Graph() g.add_node((0, 0), fuel=3) g.add_node((0, 3), fuel=3) g.add_node((3, 0), fuel=2) g.add_node((3, 3), fuel=5) g.add_node((6, 0), fuel=0) # add edges to g for node in g.nodes: add_edges(g, node) g.remove_edge((0, 0), (6, 0)) origin = (0, 0) destination = (6, 0) start_node = Node(None, origin, 3) start_node.h = euclidean_distance(origin, destination) start_node.f = start_node.g + start_node.h end_node = Node(None, destination, 0) start_time = time.time() path = aStar(None, start_node, end_node, g) print("--- %s seconds ---" % (time.time() - start_time)) prev_node = None solution_edges = [] for node in path: if prev_node is not None: solution_edges.append((prev_node, node)) prev_node = node print(node) # draw the graph pos = {} nodes_labels = {} for node in g.nodes: pos[node] = node nodes_labels[node] = g.nodes[node]['fuel'] edge_labels = {} for edge in g.edges: edge_labels[edge] = round(g[edge[0]][edge[1]]['weight'], 2) nx.draw_networkx_nodes(g, pos, nodelist=[start_node.position], node_size=500, node_color='g') nx.draw_networkx_nodes( g, pos, nodelist=[ node for node in g.nodes if node not in [start_node.position, end_node.position] ], node_size=500) nx.draw_networkx_nodes(g, pos, nodelist=[end_node.position], node_size=500, node_color='r') nx.draw_networkx_edges(g, pos, edgelist=solution_edges, alpha=1, width=4, edge_color='r') nx.draw_networkx_edges( g, pos, edgelist=[edge for edge in g.edges if edge not in solution_edges], alpha=1, width=4) nx.draw_networkx_labels(g, pos, nodes_labels, font_size=10) nx.draw_networkx_edge_labels(g, pos, edge_labels, label_pos=0.4, font_size=8) plt.axis('on') plt.show()
def run(): filename = "Scenarios/expert-2.txt" state = loadBoard(filename) x = aStar.aStar(State(state)) g = GUI.GUI(x) g.show_solution(x)
def main(): #for arg in sys.argv: iterations = 2 # default if len(sys.argv) == 2: iterations = int(sys.argv[1]) print("Iterations: ") print(iterations) init() #------------------------------- # Initialisation #------------------------------- nbLignes = game.spriteBuilder.rowsize nbColonnes = game.spriteBuilder.colsize print("lignes", nbLignes) print("colonnes", nbColonnes) players = [o for o in game.layers['joueur']] nbPlayers = len(players) # on localise tous les états initiaux (loc du joueur) initStates = [o.get_rowcol() for o in game.layers['joueur']] print("Init states:", initStates) # on localise tous les objets ramassables (les restaurants) goalStates = [o.get_rowcol() for o in game.layers['ramassable']] print("Goal states:", goalStates) nbRestaus = len(goalStates) # on localise tous les murs wallStates = [w.get_rowcol() for w in game.layers['obstacle']] print("Wall states:", wallStates) # on liste toutes les positions permises allowedStates = [(x,y) for x in range(nbLignes) for y in range(nbColonnes)\ if (x,y) not in (wallStates + goalStates)] dansRestaus = {r: [] for r in range(nbRestaus)} taux = [0 for i in range(nbRestaus)] gain = [0 for i in range(nbPlayers)] restau = [0] * nbPlayers posPlayers = initStates #------------------------------- # Placement aleatoire des joueurs, en évitant les obstacles #------------------------------- for i in range(iterations): for j in range(nbPlayers): x, y = random.choice(allowedStates) players[j].set_rowcol(x, y) game.mainiteration() posPlayers[j] = (x, y) #------------------------------- # chaque joueur choisit un restaurant #------------------------------- for j in range(nbPlayers): if j % 2 == 0: c = strategie.strategie_aleatoire(nbRestaus) elif j == 1 or j == 3 or j == 5: c = strategie.strategie_tetu(j, nbRestaus) else: c = strategie.strategie_restaurant_proche( posPlayers[j], goalStates) restau[j] = c dansRestaus[c].append(j) #------------------------------- # Boucle principale de déplacements #------------------------------- for j in range(nbPlayers): pos_restau = goalStates[restau[j]] chemin = aStar.aStar(posPlayers[j], pos_restau, wallStates) print(chemin) while posPlayers[j] != pos_restau: row, col = queue.heappop(chemin) players[j].set_rowcol(row, col) print("Position du joueur : ", j, row, col) game.mainiteration() posPlayers[j] = (row, col) if (row, col) == pos_restau: game.mainiteration() print("Le joueur ", j, " est arrivé") break for i in range(nbRestaus): if len(dansRestaus[i]) == 1: j = dansRestaus[i][0] gain[j] += 1 elif len(dansRestaus[i]) > 1: j = random.choice(dansRestaus[i]) gain[j] += 1 taux[i] = len(dansRestaus[i]) / nbPlayers print("Taux du restaurant ", i, " : ", taux[i]) dansRestaus = {r: [] for r in range(nbRestaus)} for i in range(len(gain)): print("Le gain du joueur ", i, " est : ", gain[i] / iterations) pygame.quit()
# print mouseGrid pygame.draw.rect(screen, [255, 0, 0], (gridpos[0] * blockSize, gridpos[1] * blockSize, blockSize, blockSize)) mainGrid.show() neigh = mainGrid.neighbors(gridpos) for n in neigh: pygame.draw.rect(screen, [238, 198, 6], (n[0] * blockSize, n[1] * blockSize, blockSize, blockSize)) #start = mouseGrid start = (0, 0) end = [5, 7] a = aStar(mainGrid, start, end) pygame.draw.rect(screen, [255, 0, 233], (end[0] * blockSize, end[1] * blockSize, blockSize, blockSize)) # print mouseGrid print aStar.heuristic(a, start) print aStar.Start(a) pygame.display.flip()
import cv2 import numpy as np from constants import * from recognition import Digitizer from aStar import aStar if __name__ == "__main__": d = Digitizer() d.set_src_img(cv2.imread('frame_tests/fs.jpg', 1)) d.digitize_source() a = aStar() pm, p = a.a_star(d.source_mask, 18, 0, d.startPos[1], d.startPos[0], d.endPos[1], d.endPos[0]) cv2.imshow("laberint resolt", np.clip(pm * 255, 0, 255).astype('uint8')) check_result = cv2.addWeighted(d.source_img_g.astype('uint8'), 0.5, np.clip(pm * 255, 0, 255).astype('uint8'), 0.5, 1) cv2.imshow("laberint resolt sobre original", check_result) #d.get_ball_pos(cv2.imread('tg4.jpg', 0)) cv2.waitKey()
def main(): satelites, objetos = lecturaFichero() # Valores estáticos de los satelites datosEnergia = [[], []] for i in range(len(satelites)): datosEnergia[i].append(satelites[i][1][0]) # Observar datosEnergia[i].append(satelites[i][1][1]) # Transmitir datosEnergia[i].append(satelites[i][1][2]) # Girar datosEnergia[i].append(satelites[i][1][3]) # Uds nuevas de Energia datosEnergia[i].append(satelites[i][1][4]) # Total capacidad Bateria # --Creamos los nodos Inical y Final -- nBandas = 4 # Bandas que existen en el problema horas = 12 # Horas totales que pueden los satelites obtener y enviar datos # Matrices de observables obsInicial = np.zeros(shape=(nBandas, horas), dtype="int") # Añadir observables a la matriz de observables for i in range(len(objetos)): obsInicial[objetos[i][0]][objetos[i][1]] = i + 1 # Crear Satelites y sat1 = satelite(0, datosEnergia[0][4], [0, 1], [], "IDLE", obsInicial) sat2 = satelite(1, datosEnergia[1][4], [2, 3], [], "IDLE", obsInicial) # Crear nodo Inicial nodoIncial = nodo(None, obsInicial, sat1, sat2, 0, 0, None) if (heuristicaSeleccionada == 1): nodoIncial.evaluarh1() elif (heuristicaSeleccionada == 2): nodoIncial.evaluarh2() nodoIncial.evaluar() # Creo el nuevo A estrella aEstrella = aStar(nodoIncial, datosEnergia, heuristicaSeleccionada) aEstrella.crearNodos(nodoIncial) # INICIA EL ALGORITMO inicioAlgoritmo = time.time() aEstrella.algoritmo() finAlgoritmo = time.time() # FINALIZA EL ALGORITMO noTengoPadre = True actualNode = aEstrella.nodoFinal listaNodos = [] while noTengoPadre != False: listaNodos.insert(0, actualNode) #aEstrella.printEstado(actualNode) if actualNode.nodoRaiz == None: break else: actualNode = actualNode.nodoRaiz salidaInfo = "" for nodoActual in listaNodos: salidaInfo = salidaInfo + str( nodoActual.coste ) + ". SAT 1 " + nodoActual.sat1.operacion + " " + nodoActual.sat1.objeto + ", SAT 2 " + nodoActual.sat2.operacion + " " + nodoActual.sat2.objeto + "\n" print(salidaInfo) f = open("problema.prob.output", "w") f.write(salidaInfo) f.close() tiempoEjecucionAlgoritmo = finAlgoritmo - inicioAlgoritmo escribirFichero(tiempoEjecucionAlgoritmo, aEstrella.costeTotal, aEstrella.profunidad, aEstrella.nodosExpandidos)
#from tkinter import * from aStar import aStar #from drawResult import * from file import readFile, writeFile inputFileName = raw_input( "Enter the input file name (press Enter to default to \"input.txt\"): " ) or "input.txt" outputFileName = raw_input( "Enter the output file name (press Enter to default to \"result.txt\"): " ) or "result.txt" enviro, startList, rendev = readFile(inputFileName) print("Loaded data from {0}.".format(inputFileName)) solutions, visited = aStar(enviro, startList, rendev) print("Successfully computed solutions.") writeFile("result.txt", rendev, solutions) print("Wrote solutions to {0}.".format(outputFileName)) print("Exiting...") print(visited) pic = Tk() pic = frame_grid(visited, len(enviro), len(enviro[0]))
def setMove(self): return aStar(self.player.body[0], self.apple.pos, self.player.direction, self.player.body, self.height, self.width, self.shortest)
def doAStar(map, startNode, goalNode): print('A* algorithm') # Start the search map, numberOfOpenNodes, numberOfClosedNodes = aStar(map, startNode, goalNode) printMap(map, numberOfOpenNodes, numberOfClosedNodes)