def __init__(self): self.env = game() self.env.reset() self.action = -1 done = 0 while True: suc = self.getSuccessors(self.getStartState()) if len(suc) < 1: #print("lose") self.env.setlose() done = True #step = random.randrange(0, 3) #self.env.step(step) else: step = random.choice(suc) self.env.step(step[1]) path = search.dfs(self) for action in path: # do it! render the previous view self.env.render() done = self.env.step(action) # print(env.getFood(), env.getLose(), env.getReward()) if done: break
def registerInitialState(self, state): "This method is called before any moves are made." prob='PositionSearchProblem' problem = PositionSearchProblem(Agent.gameState, start=Agent.point1, goal=Agent.point2, warn=False) self.searchType = getattr(searchAgents, prob) self.solution = search.dfs(problem) self.index = 0
def compare_searches(initial_state, is_goal, goal_state, expander): # time bfs start_bfs = timeit.default_timer() bfs_frontier = bfs(initial_state, is_goal, expander) stop_bfs = timeit.default_timer() # time dfs start_dfs = timeit.default_timer() dfs_frontier = dfs(initial_state, is_goal, expander) stop_dfs = timeit.default_timer() # time ids start_ids = timeit.default_timer() ids_frontier = ids(initial_state, is_goal, expander) stop_ids = timeit.default_timer() # time bd start_bd = timeit.default_timer() bd_frontier = bd(initial_state, goal_state, expander) stop_bd = timeit.default_timer() print(f'\nTime Taken') print(10 * '-') print(f'Breadth first: {stop_bfs-start_bfs}', bfs_frontier) print(f'Depth first: {stop_dfs-start_dfs}', dfs_frontier) print(f'iterative deepening: {stop_ids-start_ids}', ids_frontier) print(f'Bidirectional: {stop_bd-start_bd}', bd_frontier)
def main(): search_type = sys.argv[1] board = sys.argv[2] if search_type == 'bfs': return bfs(EightPuzzle(board)) elif search_type == 'dfs': return dfs(EightPuzzle(board)) return ast(EightPuzzle(board, heuristic=manhattan_distance))
def findPathToClosestDot(self, gameState): "Returns a path (a list of actions) to the closest dot, starting from gameState" # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) "*** YOUR CODE HERE ***" return search.dfs(problem)
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
def findPathToClosestDot(self, gameState): """ Returns a path (a list of actions) to the closest dot, starting from gameState. """ # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) move_set = search.dfs(problem) return move_set
def findPathToClosestDot(self, gameState): "Returns a path (a list of actions) to the closest dot, starting from gameState" # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) "*** YOUR CODE HERE ***" #util.raiseNotDefined() #foods = food.asList() path = search.dfs(problem) return path
def main(): # Example graph generation with dimension and probability g = map.generateMap(150, 0.2) manhattanPath = aStar(g, manhattanH) euclideanPath = aStar(g, euclideanH) bfsPath = bfs(g) dfsPath = dfs(g) bidirectionalBFSPath = bidirectionalBfs(g) # Example for visualizing path for graph g map.visualize(manhattanPath, g) map.visualize(euclideanPath, g) map.visualize(bfsPath, g) map.visualize(dfsPath, g) map.visualize(bidirectionalBFSPath, g) # Part 3 calls with visualization path, graph, og_path, og_graph = GenerateHardMaze.generateHardMazePathLength( ) map.visualize(og_path, og_graph) map.visualize(path, graph) path2, graph2, og_path2, og_graph2 = GenerateHardMaze.generateHardMazeFringeSize( ) map.visualize(og_path2, og_graph2) map.visualize(path2, graph2) path3, graph3, og_path3, og_graph3 = GenerateHardMaze.generateHardMazeNumberOfNodes( ) map.visualize(og_path3, og_graph3) map.visualize(path3, graph3) # Example fire graph generation with dimension and probability fireG = map.generateFireMap(100, 0.3) # Strategies with Flammability rate q q = 0.1 result1 = fire.strategy1(fireG, q) result2 = fire.strategy2(fireG, q) map.printPath(result1[0], result1[1]) print("") map.printPath(result2[0], result2[1]) # Example for visualizing path for fire graph g where the first element # in the result tuple is the path and second element is the final graph. map.visualizeFireMap(result1[0], result1[1]) map.visualizeFireMap(result2[0], result2[1])
def mazeDistanceDFS(point1, point2, gameState): """ Returns the maze distance between any two points, using the search functions you have already built. The gameState can be any game state -- Pacman's position in that state is ignored. Example usage: mazeDistance( (2,4), (5,6), gameState) This might be a useful helper function for your ApproximateSearchAgent. """ x1, y1 = point1 x2, y2 = point2 walls = gameState.getWalls() assert not walls[x1][y1], 'point1 is a wall: ' + str(point1) assert not walls[x2][y2], 'point2 is a wall: ' + str(point2) prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False, visualize=False) return len(search.dfs(prob))
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.
def mazeDistance(point1, point2, gameState): """ Returns the maze distance between any two points, using the search functions you have already built. The gameState can be any game state -- Pacman's position in that state is ignored. Example usage: mazeDistance( (2,4), (5,6), gameState) This might be a useful helper function for your ApproximateSearchAgent. """ x1, y1 = point1 x2, y2 = point2 walls = gameState.getWalls() assert not walls[x1][y1], 'point1 is a wall: ' + str(point1) assert not walls[x2][y2], 'point2 is a wall: ' + str(point2) prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False, visualize=False) return len(search.dfs(prob))
edgecolor='k', facecolor='g')) # start ax.add_patch( Rectangle((goal[1] - 0.5, goal[0] - 0.5), 1, 1, edgecolor='k', facecolor='r')) # goal # Graph settings plt.title(title) plt.axis('scaled') plt.gca().invert_yaxis() if __name__ == "__main__": # Load the map grid, start, goal = load_map('map.csv') # Search bfs_path, bfs_steps = bfs(grid, start, goal) dfs_path, dfs_steps = dfs(grid, start, goal) dij_path, dij_steps = dijkstra(grid, start, goal) aster_path, aster_steps = astar(grid, start, goal) # Show result draw_path(grid, bfs_path, 'BFS') draw_path(grid, dfs_path, 'DFS') draw_path(grid, dij_path, 'Dijkstra') draw_path(grid, aster_path, 'A*') plt.show()
self._grid[location.row][location.column] = Cell.PATH self._grid[self.start.row][self.start.column] = Cell.START self._grid[self.end.row][self.end.column] = Cell.END def delete_path(self, path: List[Location]) -> None: for location in path: self._grid[location.row][location.column] = Cell.EMPTY self._grid[self.start.row][self.start.column] = Cell.START self._grid[self.end.row][self.end.column] = Cell.END if __name__ == '__main__': m: Maze = Maze() # Solve the Maze with DFS dfs_solution: Optional[Node[Location]] = dfs(m.start, m.is_end, m.next_steps) if dfs_solution is None: print(m) print('No solution found with depth-first search.') else: dfs_path: List[Location] = nodes_in_path(dfs_solution) m.print_path(dfs_path) print(m) print( f'Maze can be solved with depth-first search in {len(dfs_path)} steps.\n\n' ) m.delete_path(dfs_path) # Solve the Maze with BFS bfs_solution: Optional[Node[Location]] = bfs(m.start, m.is_end, m.next_steps)
from node import Node from search import dfs node1 = Node('A') node2 = Node('B') node3 = Node('C') node4 = Node('D') node5 = Node('E') node1.adjacencies.append(node2) node1.adjacencies.append(node3) node2.adjacencies.append(node4) node4.adjacencies.append(node5) dfs(node1)
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)))
succ.append((state.result(a), a, 1)) return succ def getCostOfActions(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves """ return len(actions) if __name__ == '__main__': startState = MissionariesCannibalsState() prob = MissionariesCannibalsSearchProblem(startState) # path = search.GraphSearch(prob).findSolution(2) path = search.dfs(prob) curr = startState print('BFS found a path of %d moves: %s' % (len(path), str(path))) curr = startState i = 1 for a in path: curr = curr.result(a) print('After %d move%s: %s' % (i, ("", "s")[i > 1], a)) print(curr) input("Press return for the next state...") # wait for key stroke i += 1
def testDFS(): problem = read_graph(filename='test_cases/extra/g1.txt') dfs(problem)
"env.s.adm", "env.d.turn", "m.error", "p1.state", "p2.state", "t.turn", "admissible", "error", ] var_map = { "env.s.turn": "env.turn_start", "env.s.count": "env.count_start", "env.s.adm": "env.adm_start", "env.d.turn": "env.disturbance_start", "m.error": "m.error_start", "p1.state": "p1.state_start", "p2.state": "p2.state_start", "t.turn": "t.turn_start", "admissible": "env.adm_start", "error": "m.error_start", } time_step = model.get("env.T")[0] del model model = Model(fmu_path, state_vars, actions, var_map, time_step) dfs(model)
import search import numpy as np from tetris_AI import * board = np.append(np.ones(220), np.zeros(10)).reshape(23, 10) search = search.search() search.dfs(["T", "T", 2], board, 5) #kb= Kb() #kb.tell(("T",0,(0,0))) #x = kb.valid_y(2,"T",0) #print(x)
floor = VacuumState(m, n, [initX, initY]) for i in range(dirtNum): dirtX = random.randint(0, m - 1) dirtY = random.randint(0, n - 1) floor.floor[dirtX][dirtY] = '.' return floor if __name__ == '__main__': vac = createFloor(4, 4, 3) problem = VacuumProblem(vac) startTime = time.time() # path = search.breadthFirstSearch(problem) path = search.dfs(problem) print("Cal: ", time.time() - startTime) curr = vac i = 1 if not isinstance(path, list): print(path) else: print('BFS found a path of %d moves: %s' % (len(path), str(path))) for a in path: curr = curr.result(a) print('After %d move%s: %s' % (i, ("", "s")[i > 1], a)) print(curr) input("Press return for the next state...") # wait for key stroke i += 1
def search_dfs(self, u: V, v: V): node = dfs(u, lambda vertex: True if vertex == v else False, self.neighbors_for_vertex) return node_path(node)
[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)))
from mynode import MyNode from item import INITIAL,DIRECTION,POINT_TABLE from time import sleep,time from sys import argv # ------------------------------------------ main ----------------------------------------- if __name__ == "__main__": #SETUP game_board = board.Board(DIRECTION,INITIAL) initial_board = np.copy(game_board.board_array) initial_node = MyNode(initial_board,None,0,32) # arguments assigment method = int(argv[1]) TIME_LIMIT = int(argv[2]) if(method == 1): result_1 = bfs(initial_node,POINT_TABLE,TIME_LIMIT) elif(method == 2): result_2 = dfs(initial_node,POINT_TABLE,TIME_LIMIT) elif(method == 3): result_3 = ids(initial_node,POINT_TABLE,TIME_LIMIT) elif(method == 4): result_4 = dfs_rand(initial_node,POINT_TABLE,TIME_LIMIT) elif(method == 5): result_5 = dfs_spec(initial_node,TIME_LIMIT) else: print("\n1-) Breadth First Search\n2-) Depth First Search\n3-) Iterative Deepening Search\n4-) Depth First with Random") print("5-) Depth First with Heuristic")
for i, row in enumerate(self._grid): for j, cell in enumerate(row): if cell == Cell.path: self._grid[i][j] = Cell.empty if __name__ == "__main__": import time from search import dfs, bfs, a_star, node_to_path nrows, ncols = 24, 120 start = MazeLocation(0, 0) end = MazeLocation(nrows - 1, ncols - 1) m = Maze(nrows, ncols, start=start, end=end) print(m) tic = time.time() df_solution = dfs(m.start, m.goal_test, m.possible_next_locations) toc = time.time() if df_solution is None: print("Depth-first search did not find solution") else: df_path = node_to_path(df_solution) m.mark_path(df_path) print("Depth-first search results:") print(" Path length: {}".format(len(df_path))) print(" Eval time: %.5f" % (toc - tic)) print(m) m.clear_path() tic = time.time() bf_solution = bfs(m.start, m.goal_test, m.possible_next_locations) toc = time.time() if bf_solution is None:
def __init__(self, bzrc, algorithm): self.bzrc = bzrc self.algorithm = algorithm self.constants = self.bzrc.get_constants() self.commands = [] bases = self.bzrc.get_bases() for base in bases: if base.color == self.constants['team']: self.base = Answer() self.base.x = (base.corner1_x + base.corner3_x) / 2 self.base.y = (base.corner1_y + base.corner3_y) / 2 self.update() self.past_position = {} self.goals = {} self.stuck = {} for tank in self.mytanks: self.past_position[tank.index] = tank.x, tank.y self.goals[tank.index] = None self.stuck[tank.index] = 0 self.set_flag_goals() self.vertex_positions = [] self.vertex_positions.append((self.base.x, self.base.y)) self.obstacles = self.bzrc.get_obstacles() for obstacle in self.obstacles: for i in range(len(obstacle)): x = obstacle[i][0] - obstacle[(i + 2) % 4][0] y = obstacle[i][1] - obstacle[(i + 2) % 4][1] dist = math.sqrt(x**2 + y**2) self.vertex_positions.append((obstacle[i][0] + x / dist * 0, obstacle[i][1] + y / dist * 0)) self.vertex_positions.append(self.goals[0]) #print "self.vertex_positions = " + str(self.vertex_positions) self.adjacency_matrix = numpy.zeros( [len(self.vertex_positions), len(self.vertex_positions)]) for i in range(len(self.obstacles)): for j in range(4): index = i * 4 + j + 1 if j < 3: self.adjacency_matrix[index][ index + 1] = self.adjacency_matrix[ index + 1][index] = math.sqrt( (self.vertex_positions[index][0] - self.vertex_positions[index + 1][0])**2 + (self.vertex_positions[index][1] - self.vertex_positions[index + 1][1])**2) else: first_corner = i * 4 + 1 self.adjacency_matrix[index][ first_corner] = self.adjacency_matrix[first_corner][ index] = math.sqrt( (self.vertex_positions[index][0] - self.vertex_positions[first_corner][0])**2 + (self.vertex_positions[index][1] - self.vertex_positions[first_corner][1])**2) for i in range(len(self.vertex_positions)): for j in range(i + 1, len(self.vertex_positions)): if i == 0 or j == len(self.vertex_positions) - 1 or ( i - 1) / 4 != (j - 1) / 4: #print "i = " + str(i) #print "j = " + str(j) xa = self.vertex_positions[i][0] ya = self.vertex_positions[i][1] xb = self.vertex_positions[j][0] yb = self.vertex_positions[j][1] #print "a = (" + str(xa) + ", " + str(ya) + ")" #print "b = (" + str(xb) + ", " + str(yb) + ")" intersect = False for m in range(len(self.obstacles)): if intersect: break for n in range(4): index = m * 4 + n + 1 if index == i or index == j: continue xc = self.vertex_positions[index][0] yc = self.vertex_positions[index][1] #print "c = (" + str(xc) + ", " + str(yc) + ")" if n < 3: if index + 1 == i or index + 1 == j: continue xd = self.vertex_positions[index + 1][0] yd = self.vertex_positions[index + 1][1] else: first_corner = m * 4 + 1 if first_corner == i or first_corner == j: continue xd = self.vertex_positions[first_corner][0] yd = self.vertex_positions[first_corner][1] #print "d = (" + str(xd) + ", " + str(yd) + ")" if self.segments_intersect(xa, ya, xb, yb, xc, yc, xd, yd): #print "intersection" #print "a = (" + str(xa) + ", " + str(ya) + ")" #print "b = (" + str(xb) + ", " + str(yb) + ")" #print "c = (" + str(xc) + ", " + str(yc) + ")" #print "d = (" + str(xd) + ", " + str(yd) + ")" intersect = True break if intersect: self.adjacency_matrix[i][j] = self.adjacency_matrix[j][ i] = 0 else: self.adjacency_matrix[i][j] = self.adjacency_matrix[j][ i] = math.sqrt((self.vertex_positions[i][0] - self.vertex_positions[j][0])**2 + (self.vertex_positions[i][1] - self.vertex_positions[j][1])**2) half_worldsize = int(self.constants['worldsize']) / 2 tanklength = int(self.constants['tanklength']) for i in range(1, len(self.vertex_positions) - 1): if half_worldsize - self.vertex_positions[i][ 0] < tanklength or half_worldsize + self.vertex_positions[i][ 0] < tanklength or half_worldsize - self.vertex_positions[ i][1] < tanklength or half_worldsize + self.vertex_positions[ i][1] < tanklength: for j in range(len(self.vertex_positions)): self.adjacency_matrix[i][j] = self.adjacency_matrix[j][ i] = 0 numpy.set_printoptions(threshold=numpy.nan) #print "self.adjacency_matrix = " + str(self.adjacency_matrix) self.updateGraph() if self.algorithm == 'dfs': self.path = search.dfs(self.graph, 0, len(self.vertex_positions) - 1, self.obstacles, self.vertex_positions) elif self.algorithm == 'bfs': self.path = search.bfs(self.graph, 0, len(self.vertex_positions) - 1, self.obstacles, self.vertex_positions) else: self.path = search.aStar(self.graph, self.adjacency_matrix, self.vertex_positions, 0, len(self.vertex_positions) - 1, self.obstacles) self.plot_visibility_graph() for i in range(len(self.obstacles)): obstacle = self.obstacles[i] for j in range(len(obstacle)): x1 = obstacle[j][0] - obstacle[(j + 1) % 4][0] y1 = obstacle[j][1] - obstacle[(j + 1) % 4][1] dist1 = math.sqrt(x1**2 + y1**2) x1 /= dist1 y1 /= dist1 x2 = obstacle[j][0] - obstacle[(j + 3) % 4][0] y2 = obstacle[j][1] - obstacle[(j + 3) % 4][1] dist2 = math.sqrt(x2**2 + y2**2) x2 /= dist2 y2 /= dist2 self.vertex_positions[i * 4 + j + 1] = ((obstacle[j][0] + (x1 + x2) * 10, obstacle[j][1] + (y1 + y2) * 10)) self.current_goal_index = 1 self.goals[0] = self.vertex_positions[self.path[ self.current_goal_index]]
def __init__(self, bzrc, algorithm): self.bzrc = bzrc self.algorithm = algorithm self.constants = self.bzrc.get_constants() self.commands = [] bases = self.bzrc.get_bases() for base in bases: if base.color == self.constants['team']: self.base = Answer() self.base.x = (base.corner1_x+base.corner3_x)/2 self.base.y = (base.corner1_y+base.corner3_y)/2 self.update() self.past_position = {} self.goals = {} self.stuck = {} for tank in self.mytanks: self.past_position[tank.index] = tank.x, tank.y self.goals[tank.index] = None self.stuck[tank.index] = 0 self.set_flag_goals() self.vertex_positions = [] self.vertex_positions.append((self.base.x, self.base.y)) self.obstacles = self.bzrc.get_obstacles() for obstacle in self.obstacles: for i in range(len(obstacle)): x = obstacle[i][0] - obstacle[(i + 2) % 4][0] y = obstacle[i][1] - obstacle[(i + 2) % 4][1] dist = math.sqrt(x ** 2 + y ** 2) self.vertex_positions.append((obstacle[i][0] + x / dist * 0, obstacle[i][1] + y / dist * 0)) self.vertex_positions.append(self.goals[0]) #print "self.vertex_positions = " + str(self.vertex_positions) self.adjacency_matrix = numpy.zeros([len(self.vertex_positions), len(self.vertex_positions)]) for i in range(len(self.obstacles)): for j in range(4): index = i * 4 + j + 1 if j < 3: self.adjacency_matrix[index][index + 1] = self.adjacency_matrix[index + 1][index] = math.sqrt((self.vertex_positions[index][0] - self.vertex_positions[index + 1][0]) ** 2 + (self.vertex_positions[index][1] - self.vertex_positions[index + 1][1]) ** 2) else: first_corner = i * 4 + 1 self.adjacency_matrix[index][first_corner] = self.adjacency_matrix[first_corner][index] = math.sqrt((self.vertex_positions[index][0] - self.vertex_positions[first_corner][0]) ** 2 + (self.vertex_positions[index][1] - self.vertex_positions[first_corner][1]) ** 2) for i in range(len(self.vertex_positions)): for j in range(i + 1, len(self.vertex_positions)): if i == 0 or j == len(self.vertex_positions) - 1 or (i - 1) / 4 != (j - 1) / 4: #print "i = " + str(i) #print "j = " + str(j) xa = self.vertex_positions[i][0] ya = self.vertex_positions[i][1] xb = self.vertex_positions[j][0] yb = self.vertex_positions[j][1] #print "a = (" + str(xa) + ", " + str(ya) + ")" #print "b = (" + str(xb) + ", " + str(yb) + ")" intersect = False for m in range(len(self.obstacles)): if intersect: break for n in range(4): index = m * 4 + n + 1 if index == i or index == j: continue xc = self.vertex_positions[index][0] yc = self.vertex_positions[index][1] #print "c = (" + str(xc) + ", " + str(yc) + ")" if n < 3: if index + 1 == i or index + 1 == j: continue xd = self.vertex_positions[index + 1][0] yd = self.vertex_positions[index + 1][1] else: first_corner = m * 4 + 1 if first_corner == i or first_corner == j: continue xd = self.vertex_positions[first_corner][0] yd = self.vertex_positions[first_corner][1] #print "d = (" + str(xd) + ", " + str(yd) + ")" if self.segments_intersect(xa, ya, xb, yb, xc, yc, xd, yd): #print "intersection" #print "a = (" + str(xa) + ", " + str(ya) + ")" #print "b = (" + str(xb) + ", " + str(yb) + ")" #print "c = (" + str(xc) + ", " + str(yc) + ")" #print "d = (" + str(xd) + ", " + str(yd) + ")" intersect = True break if intersect: self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = 0 else: self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = math.sqrt((self.vertex_positions[i][0] - self.vertex_positions[j][0]) ** 2 + (self.vertex_positions[i][1] - self.vertex_positions[j][1]) ** 2) half_worldsize = int(self.constants['worldsize']) / 2 tanklength = int(self.constants['tanklength']) for i in range(1, len(self.vertex_positions) - 1): if half_worldsize - self.vertex_positions[i][0] < tanklength or half_worldsize + self.vertex_positions[i][0] < tanklength or half_worldsize - self.vertex_positions[i][1] < tanklength or half_worldsize + self.vertex_positions[i][1] < tanklength: for j in range(len(self.vertex_positions)): self.adjacency_matrix[i][j] = self.adjacency_matrix[j][i] = 0 numpy.set_printoptions(threshold=numpy.nan) #print "self.adjacency_matrix = " + str(self.adjacency_matrix) self.updateGraph() if self.algorithm == 'dfs': self.path = search.dfs(self.graph,0,len(self.vertex_positions) - 1,self.obstacles,self.vertex_positions) elif self.algorithm == 'bfs': self.path = search.bfs(self.graph,0,len(self.vertex_positions) - 1,self.obstacles,self.vertex_positions) else: self.path = search.aStar(self.graph,self.adjacency_matrix,self.vertex_positions,0,len(self.vertex_positions) - 1,self.obstacles) self.plot_visibility_graph() for i in range(len(self.obstacles)): obstacle = self.obstacles[i] for j in range(len(obstacle)): x1 = obstacle[j][0] - obstacle[(j + 1) % 4][0] y1 = obstacle[j][1] - obstacle[(j + 1) % 4][1] dist1 = math.sqrt(x1 ** 2 + y1 ** 2) x1 /= dist1 y1 /= dist1 x2 = obstacle[j][0] - obstacle[(j + 3) % 4][0] y2 = obstacle[j][1] - obstacle[(j + 3) % 4][1] dist2 = math.sqrt(x2 ** 2 + y2 ** 2) x2 /= dist2 y2 /= dist2 self.vertex_positions[i * 4 + j + 1] = ((obstacle[j][0] + (x1 + x2) * 10, obstacle[j][1] + (y1 + y2) * 10)) self.current_goal_index = 1 self.goals[0] = self.vertex_positions[self.path[self.current_goal_index]]
map.addRoad(Road('Urziceni', 'Bucharest', 85)) map.addRoad(Road('Urziceni', 'Hirsova', 98)) map.addRoad(Road('Eforie', 'Hirsova', 86)) map.addRoad(Road('Urziceni', 'Vaslui', 142)) map.addRoad(Road('Lasi', 'Vaslui', 92)) map.addRoad(Road('Lasi', 'Neamt', 87)) return map if __name__ == '__main__': if len(sys.argv) not in [3, 4]: sys.exit("Useage: python3 map_navigation.py from_city to_city bfs/dfs") map = loadMap() map_navigation_problem = MapNavigationProblem(map, sys.argv[1], sys.argv[2]) if len(sys.argv) == 4 and sys.argv[3] == 'dfs': actions = search.dfs(map_navigation_problem) cost = map_navigation_problem.getCostOfActionSequence(actions) print(f"DFS found a path of {len(actions)} moves with {cost} costs") city = [map_navigation_problem.current_city] for a in actions: city.append(map_navigation_problem.getNextCity(a)) print('-'.join(city)) else: actions = search.bfs(map_navigation_problem) cost = map_navigation_problem.getCostOfActionSequence(actions) print(f"BFS found a path of {len(actions)} moves with {cost} costs") city = [map_navigation_problem.current_city] for a in actions: city.append(map_navigation_problem.getNextCity(a)) print('-'.join(city))
next_state = self.getNextState(state, queen_pos) yield (next_state, queen_pos, self.getActionCost(state, queen_pos, next_state)) def getActions(self, state): return state.legalMoves() def getActionCost(self, state, action, next_state): return 1 def getNextState(self, state, action): return state.result(action) def getCostOfActionSequence(self, actions): return len(actions) if __name__ == "__main__": board = BoardState() board.addRandomQueens() print('Add a random queen:') print(board) problem = EightQueensProblem(board) actions = search.dfs(problem) print('DFS found a path of %d moves: %s' % (len(actions), str(actions))) curr = board for queen_pos in actions: input("Press return for the next state...") # wait for key stroke curr = curr.result(queen_pos) print(curr)