def run_bfs(p): results = init_results() progress = len(puzzles) * len(orders) i = 0 for puzzle in puzzles: for order in orders: bfs = BFS(search_order=order) dim, lay = load_config(os.path.join("puzzles", puzzle)) bfs.model.load_layout(dim, lay) t = time() path = bfs.run() t = round((time() - t) * 1000, 3) # get the depth from 4x4_depth_00000.txt depth = int(puzzle.split('_')[1]) if path == -1: continue result = { "path_length": len(path), "frontier": len(bfs.frontier) + len(bfs.explored), "explored": len(bfs.explored), "depth": len(path), "time": t } results["BFS"][order][depth].append(result) print("BFS progress: {}%".format(round((i / progress) * 100, 2)), end='\r', flush=True) i += 1 # avg_whole, avg_orders return process_results("BFS", results)
def _color(self): print("height %d width %d" % (self.height, self.width)) #self._print() self.img = self.img.convert('RGB') impix = self.img.load() dest = [self.height - 1, -1] source = [0, -1] for i in range(0, self.width): if (self.data[i] > 0): source[1] = i break for i in range(1, self.width): if (self.data[(self.width * self.height) - i] > 0): dest[1] = self.width - i print(self.height * self.width - i) break print("source node: ", source) print("dest node: ", dest) pix = [] func = BFS(source, dest, self.width, self.height) pix = func.bfs() pix.reverse() for i in pix: row = i[0] col = i[1] #print(impix[col ,row]) impix[col, row] = (0, 0, 204) self.img.save(self.out)
def setUp(self): self.bfs = BFS() self.graph = Graph() self.graph.insert_edge(create_edge(0, 1, 10)) self.graph.insert_edge(create_edge(1, 3, 10)) self.graph.insert_edge(create_edge(0, 2, 20)) self.graph.insert_edge(create_edge(0, 3, 30)) self.graph.insert_edge(create_edge(2, 3, 60)) self.graph.insert_edge(create_edge(3, 4, 120))
def run(args): path = args['--path'] if args['--path'] else None method = args['--method'] if args['--method'] else 'sha1' bf = BFS(path=path, method=method) if args['--write']: id, size = bf.fwrite(args['--write']) print(id, size) elif args['--read']: print(bf.read(args['--read'])) elif args['--stat']: print(bf.stat()) elif args['--show']: for i in bf.get_all_id(): print(i)
def main(): # python driver.py bfs 0,8,7,6,5,4,3,2,1 arguments = sys.argv search_type = arguments[1] # create a list of initial states from arguments[2] initial_state_list = [int(x) for x in arguments[2].split(',')] # now use this list to create initial_state object from State class initial_state = State(initial_state_list) # let's use time var to time execution start_time = time.time() # create output Object from Output class output = Output() if search_type == 'bfs': output = BFS(initial_state) elif search_type == 'dfs': output = DFS(initial_state) # elif search_type == 'ast': # output = solve_ast(initial_state) else: print('Invalid search_type: {}'.format(search_type)) # Let's add max ram uage and running time to output object output.max_ram_usage = resource.getrusage( resource.RUSAGE_SELF).ru_maxrss / 1024 output.running_time = time.time() - start_time f = open('output.txt', 'w') f.write(str(output)) f.close()
def shortest_path(source, target, graph): def target_check(u, v): return v==target parent, level = BFS(graph = graph, root = source, check_terminate = target_check) print("Parent: ", parent) print("Level: ",level) path = [target] cur_country = target if parent.get(cur_country) is None: return [] while parent[cur_country] is not None: parent_country = parent[cur_country] path.append(parent_country) cur_country = parent_country path.reverse() return path
def measure_bfs(): bfs = BFS(Graph(0)) avg_memory_consumption = [] for i in range(START_COUNTING_FROM_NODE, NUM_OF_NODES): print(f"Measuring BFS for {i} nodes.") graph = Graph(i) bfs.graph = graph starting_node = next(iter(graph.graph)) mem_usage = memory_usage((bfs.breadth_first_search, (), { 'start_node': starting_node })) avg_memory_consumption.append(mem_usage[-1]) return avg_memory_consumption
def main(start_state, goal_state, search_type): if search_type == "bfs": breadth_first_search = BFS(goal_state) res = breadth_first_search.breadthFirstSearch(start_state) elif search_type == "h1": a_star_h1 = AStar(goal_state, search_type) res = a_star_h1.aStar(start_state) elif search_type == "h2": a_star_h2 = AStar(goal_state, search_type) res = a_star_h2.aStar(start_state) else: print("Usage: python3 'SearchType' '[StartState]' '[EndState]'") print( "Search type = bfs, h1, or h2 where h1 is A* with count of tiles in the wrong place, and h2 is A* with Manhattan Values" ) for i in res: print(i)
def get_solve_graph(algo_enum: AlgoEnum): solve_graph: BaseGlobalSearch = None if algo_enum == AlgoEnum.IDS: solve_graph = IDS(order_int_list, N) elif algo_enum == AlgoEnum.BFS: solve_graph = BFS(order_int_list, N) elif algo_enum == AlgoEnum.A_STAR: solve_graph = AStar(order_int_list, N) return solve_graph
def main(dictionary, from_word, to_word): words = dictionary.split(",") # add the start and end word to the dictionary words.append(from_word) words.append(to_word) graph = constructGraph(words) BFS(graph, graph.getVertex(from_word)) return traverse(graph.getVertex(to_word))
def solve(): """ Solve the puzzle by getting the required parameters from the request args. """ algorithm = request.args['algorithm'] arr = list(map(int, request.args['input[]'][1:-1].split(','))) print(algorithm) agent = None if algorithm == "BFS": agent = BFS() elif algorithm == "DFS": agent = DFS() elif algorithm == "A start (Euclidean)": agent = AStar(Euclidean) elif algorithm == "A start (Manhatten)": agent = AStar(Manhatten) else: return arr start = timeit.default_timer() res = agent.search(arr) end = timeit.default_timer() res['time'] = end - start ret = jsonify(res) return ret
def findWaterBodies(imageObject, season): listOfWaterEdges = set() pixels = imageObject.load() width, height = imageObject.size for i in range(width): for j in range(height): if (pixels[i, j] == (0, 0, 255, 255)): if i > 0 and pixels[i - 1, j] != (0, 0, 255, 255): listOfWaterEdges.add((i - 1, j)) if i < 394 and pixels[i + 1, j] != (0, 0, 255, 255): # left dir listOfWaterEdges.add((i + 1, j)) if j > 0 and pixels[i, j - 1] != (0, 0, 255, 255): # right dir listOfWaterEdges.add((i, j - 1)) if j < 499 and pixels[i, j + 1] != (0, 0, 255, 255): # up dir listOfWaterEdges.add((i, j + 1)) if i > 0 and j > 0 and pixels[i - 1, j - 1] != ( 0, 0, 255, 255): # down dir listOfWaterEdges.add((i - 1, j - 1)) if i < 394 and j > 0 and pixels[i + 1, j - 1] != ( 0, 0, 255, 255): # diagonal listOfWaterEdges.add((i + 1, j - 1)) if i > 0 and j < 499 and pixels[i - 1, j + 1] != ( 0, 0, 255, 255): # diagonal listOfWaterEdges.add((i - 1, j + 1)) if i < 394 and j < 499 and pixels[i + 1, j + 1] != ( 0, 0, 255, 255): # diagonal listOfWaterEdges.add((i + 1, j + 1)) listOfWaterEdges = sorted(listOfWaterEdges) print(listOfWaterEdges) list = [] for i in listOfWaterEdges: neighbour = [] for new_position in [(0, -7), (0, 7), (-7, 0), (7, 0), (-7, -7), (-7, 7), (7, -7), (7, 7)]: node_position = (i[0] + new_position[0], i[1] + new_position[1]) if node_position[0] > ( 394) or node_position[0] < 0 or node_position[1] > ( 499) or node_position[1] < 0: continue else: neighbour.append(node_position) BFS(i, node_position, pixels, imageObject, season) list.append(neighbour) imageObject.save("test2.png")
def test_random(): """ Test all approaches on random graph. """ num_of_nodes = 7 graph = Graph(num_of_nodes) starting_node = next(iter(graph.graph)) print("{:-^100}".format(" TESTING RANDOM PATH ")) dfs = DFS(graph) paths_dfs = dfs.depth_first_search(starting_node) print("DEPTH FIRST SEARCH") print("Number of Hamilton Cycles found:", len(paths_dfs)) print("Shortest path:", graph.get_shortest_path(paths_dfs), end="\n\n") bfs = BFS(graph) paths_bfs = bfs.breadth_first_search(starting_node) print("BREADTH FIRST SEARCH") print("Number of Hamilton Cycles found:", len(paths_bfs)) print("Shortest path:", graph.get_shortest_path(paths_bfs), end="\n\n") greedy = Greedy(graph) path_greedy = greedy.greedy_approach(starting_node) print("GREEDY APPROACH") print("Path length:", (path_greedy, graph.calculate_path_length(path_greedy)), end="\n\n") a_star_custom = AStarCustom(graph) path_a_star = a_star_custom.a_star(starting_node) print("A* APPROACH") print("Path length:", (path_a_star, graph.calculate_path_length(path_a_star)), end="\n") print("{:-^100}".format(" END OF TEST "), end="\n\n")
class TestBFS(unittest.TestCase): def setUp(self): self.bfs = BFS() self.graph = Graph() self.graph.insert_edge(create_edge(0, 1, 10)) self.graph.insert_edge(create_edge(1, 3, 10)) self.graph.insert_edge(create_edge(0, 2, 20)) self.graph.insert_edge(create_edge(0, 3, 30)) self.graph.insert_edge(create_edge(2, 3, 60)) self.graph.insert_edge(create_edge(3, 4, 120)) def test_bfs(self): result = self.bfs.bfs(0, self.graph) expected = [0, 1, 2, 3, 4] self.assertEqual(expected, result)
def __init__(self): super().__init__() self.setupUi(self) self.CurrentPage = GD self.CurrentPage_Dict = None self.CurrentTabItems = None self.list1_selected_index = None self.list2_selected_text = None self.CurrentTab = 0 self.list1.clicked.connect(self.list1_clicked) self.list2.clicked.connect(self.list2_clicked) self.com1.currentIndexChanged.connect(self.com1_change) self.com2.currentIndexChanged.connect(self.com2_change) self.pushButton.clicked.connect(self.add) self.btn1.clicked.connect(self.start) self.thread_list = [] self.MyBfs = BFS() # self.list1.itemSelectionChanged.connect(self.list1_selectionchanged) self.Current_list2 = None #缺省设置 self.CurrentTabItems = TABBAR['工单'].keys() for key in TABBAR['工单'].keys(): self.com2.addItem(key) print(self.MyBfs.MyDriver.title) self.get_df_from_excel() print(list(self.data_pd.keys())) ############################################################################# self.list_page_items.clicked.connect(self.list_page_items_clicked) self.list_tab_items.clicked.connect(self.list_tab_items_clicked) self.list_operate_items.clicked.connect( self.list_operate_items_clicked) self.list_element_toolbar_items.clicked.connect( self.list_element_clicked) self.list_element_items.clicked.connect(self.list_element_clicked) self.list_finally_items.doubleClicked.connect( self.list_finally_items_clicked) self.current_dict = GD self.list_page_index = 0 self.list_page_text = '工单' self.list_tab_index = 0 self.list_tab_text = '查询' self.list_operate_index = 0 self.list_operate_text = '点击' self.list_element_text = '保存' print( '****************************************************************************************' ) print(self.data_pd['名称'])
def correr_busqueda(tipo_busqueda=0): tablero = CMP(get_mapa_caracteres()) if tipo_busqueda == 1: resultados, tablero = BFS(tablero) elif tipo_busqueda == 2: resultados, tablero = DFS(tablero) elif tipo_busqueda == 3: resultados, tablero = IDS(tablero) elif tipo_busqueda == 0: print("No se envio el parametro tipo de busqueda") exit() else: print("No se envio un tipo de busqueda correcto") exit() return resultados, tablero
def run(self): if self.algorithm == "DFS": self.solution = DFS.run(self.source, self.destinations) if self.solution is not None: self.end_time = self.start_time + len(self.solution) - 1 self.end_time = self.end_time % 24 elif self.algorithm == "BFS": self.solution = BFS.run(self.source, self.destinations) if self.solution is not None: self.end_time = self.start_time + len(self.solution) - 1 self.end_time = self.end_time % 24 elif self.algorithm == "UCS": self.solution = UCS.run(self.start_time, self.source, self.destinations) if self.solution is not None: self.end_time = self.solution.pop(0) else: raise Exception("Unexpected Algorithm = " + self.algorithm)
def init(): # Create GUI window pygame.init() DSURF = pygame.display.set_mode((DISPLAYWIDTH, DISPLAYHEIGHT)) # Create the gridworld where the search will take place board = Board(BOARDWIDTH, BOARDHEIGHT, 100) board2 = deepcopy(board) board2.shift_w = BOARDWIDTH + 2 # Initialize the BFS and A* graph search algorithms a_star = ASTAR(board) bfs = BFS(board2) # Counter for the number of iterations the algorithm have taken iter_star = 1 iter_bfs = 1 return DSURF, board, board2, a_star, bfs, iter_star, iter_bfs
def run(): label_find_the_result.config(text="Result:") label_time.config(text="Time:") label_steps.config(text="Steps:") btn_run.config(state=tk.DISABLED) btn_reset.config(state=tk.DISABLED) radio_dfs.config(state=tk.DISABLED) radio_bfs.config(state=tk.DISABLED) radio_bestfs.config(state=tk.DISABLED) radio_hc.config(state=tk.DISABLED) algorithm = alg.get() res = "" steps = 0 time_start = time.time() if algorithm == 1: res = DFS.solve(puzzle_in, window) print("DFS: ", res) elif algorithm == 2: res = BFS.solve(puzzle_in, window) print("BFS: ", res) elif algorithm == 3: res = BestFirstSearch.solve(puzzle_in, window) print("Best First Search: ", res) elif algorithm == 4: res = HillClimbing.solve(puzzle_in, window) print("Hill Climbing: ", res) time_end = time.time() if res is None: solution = "No!" else: solution = "Yes!" steps = len(res) output(solution, time_end - time_start, steps) btn_run.config(state=tk.NORMAL) btn_reset.config(state=tk.NORMAL) radio_dfs.config(state=tk.NORMAL) radio_bfs.config(state=tk.NORMAL) radio_bestfs.config(state=tk.NORMAL) radio_hc.config(state=tk.NORMAL)
def Assemble(self): while True: self.board.Clear() # first place the delivery car at the exit self.board.AddDelivery(4, 2) num_tries = 0 # filling in object until we think there are enough while len(self.board._blocks) <= random.randint(9, 12): # pick a position to place the next object x = random.randint(0, 5) y = random.randint(0, 5) obj = self.GetAnObject(x, y) if (x <= 4 and y == 2 and (obj._kind == Block.BlockKinds.OBSTACLE or obj._isVertical)): continue num_tries += 1 if self.board.IsBlockAddable(obj): self.board.AddBlock(obj) minSteps = BFS(self.board, visitAll=False) if minSteps >= 15: print "Found a board with %d moves" % minSteps self.board.PrintData() self.board.PrintBlocksInfo()
from bfs import BFS # General setup pygame.init() clock = pygame.time.Clock() RUNNING = False # Set up main window SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Pathfinding') # Add pathfinding classes bfs = BFS(SCREEN_WIDTH, SCREEN_HEIGHT) while True: # handle input for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if not RUNNING: pos = pygame.mouse.get_pos() clicked_cells = [] for row in bfs.cells: for c in row: if c.rect.collidepoint(pos): clicked_cells.append(c)
from json import loads from bfs import BFS from dfs import DFS from ids import IDS from hc import HC # Load tree data from file filePath = open('./data.json') data = filePath.read() dataJson = loads(data) tree = dataJson['tree'] # list of goals of DFS, DFS, IDS algorithms goals = dataJson['goals'] hill_climb = dataJson['hill-climb'] # list of goals of HC algorithm goals_HC = dataJson['hill-climb']['goals'] # root node root = dataJson['root'] if __name__ == '__main__': DFS(tree, root, goals) BFS(tree, root, goals) IDS(tree, root, goals, 2) HC(hill_climb, root, goals_HC)
__author__ = 'muneeb' from node import Node from ids import IDS from dfs import DFS from bfs import BFS from graph_generator import Graph_Generator import copy start = "1" goal = "15" g = Graph_Generator(8000) graph = g.generate_graph() ids = IDS(copy.deepcopy(graph), start, goal) bfs = BFS(copy.deepcopy(graph), start, goal) dfs = DFS(copy.deepcopy(graph), start, goal) ids.walk() bfs.walk() dfs.walk()
from bfs import BFS from romenia_map import ROMENIA bfs = BFS(ROMENIA, start="Arad") print bfs.search("Bucharest") == "Bucharest"
def create_path(self, g, u, v): self.path = BFS(g, u, v)
elif low_level_planner_class is IW: low_level_planner = IW( generate_successor_fn=low_level_actor.generate_successor, width=args.low_level_width, features_name="low_level_features", ignore_terminal_nodes=True) elif low_level_planner_class is CountbasedRolloutIW: low_level_planner = CountbasedRolloutIW( generate_successor_fn=low_level_actor.generate_successor, width=args.low_level_width, features_name="low_level_features", temp=args.countbasedRIW_temp, ignore_terminal_nodes=True) elif low_level_planner_class is BFS: low_level_planner = BFS( generate_successor_fn=low_level_actor.generate_successor, features_name="low_level_features") else: raise ValueError( f"Low level planner class {low_level_planner_class.__name__} not known." ) low_level_planner.add_stop_fn( lambda tree: not interactions.within_budget()) low_level_planner.add_stop_fn( lambda tree: low_level_actor.get_tree_size(tree) >= args.max_tree_size) if args.guide_plan_network_policy: assert low_level_planner_class is RolloutIW if low_level_planner_class is RolloutIW: assert args.guide_plan_network_policy
from bfs import BFS from romenia_map import ROMENIA bfs = BFS(ROMENIA, start='Arad') print bfs.search('Bucharest') == 'Bucharest'
def print_tree(self): self.assign_root() bfs = BFS() bfs.bfs([self.root]) print ''
def try_all_approaches(num_of_samples: int, num_of_nodes: int): """ Execute all approaches on the same graphs for given number of nodes and samples (the more samples the more statistically accurate results). Returns: Achieved path lengths and execution times for all approaches. """ graph = Graph(0) dfs = DFS(graph) dfs_path_lengths = [] dfs_execution_times = [] bfs = BFS(graph) bfs_path_lengths = [] bfs_execution_times = [] greedy = Greedy(graph) greedy_path_lengths = [] greedy_execution_times = [] a_star_custom = AStarCustom(graph) a_star_path_lengths = [] a_star_execution_times = [] for i in range(a_star_custom.num_of_heuristics): a_star_path_lengths.append([]) a_star_execution_times.append([]) for j in range(num_of_samples): graph = Graph(num_of_nodes) starting_node = next(iter(graph.graph)) start = time.time() dfs.graph = graph paths_dfs = dfs.depth_first_search(starting_node) dfs_path_lengths.append(Graph.get_shortest_path(paths_dfs)[1]) execution_time = time.time() - start dfs_execution_times.append(execution_time) start = time.time() bfs.graph = graph paths_bfs = bfs.breadth_first_search(starting_node) bfs_path_lengths.append(Graph.get_shortest_path(paths_bfs)[1]) execution_time = time.time() - start bfs_execution_times.append(execution_time) start = time.time() greedy.graph = graph path_greedy = greedy.greedy_approach(starting_node) greedy_path_lengths.append(Graph.calculate_path_length(path_greedy)) execution_time = time.time() - start greedy_execution_times.append(execution_time) for i in range(a_star_custom.num_of_heuristics): start = time.time() a_star_custom.graph = graph a_star_custom.heuristic_choice = i path_a_star = a_star_custom.a_star(starting_node) execution_time = time.time() - start a_star_path_lengths[i].append( Graph.calculate_path_length(path_a_star)) a_star_execution_times[i].append(execution_time) dfs_avg_results = sum(dfs_path_lengths) / num_of_samples, sum( dfs_execution_times) / num_of_nodes, "DFS Recurrent" bfs_avg_results = sum(bfs_path_lengths) / num_of_samples, sum( bfs_execution_times) / num_of_nodes, "BFS" greedy_avg_results = sum(greedy_path_lengths) / num_of_samples, sum( greedy_execution_times) / num_of_nodes, "Greedy" a_star_avg_results = [] for i in range(a_star_custom.num_of_heuristics): label = "A* heuristic " + str(i) a_star_avg_results.append( (sum(a_star_path_lengths[i]) / num_of_samples, sum(a_star_execution_times[i]) / num_of_samples, label)) data = [dfs_avg_results, bfs_avg_results, greedy_avg_results] data.extend(a_star_avg_results) return data
import sys import time from state import State from bfs import BFS from dfs import DFS SEARCH_TYPE = sys.argv[1] INITIAL_STATE = map(int, sys.argv[2].split(',')) game = State(INITIAL_STATE); search = None if SEARCH_TYPE == 'bfs': search = BFS(game) if SEARCH_TYPE == 'dfs': search = DFS(game) result = search.perform_search() goal_pos = result.position res = resource.getrusage(resource.RUSAGE_SELF) def trace_path(goal_pos): pos = goal_pos path = [] while pos != None: if (pos.node.action != None): path.append(pos.node.action)
map1 = "maps/map1.txt" map2 = "maps/map2.txt" map3 = "maps/map3.txt" b_map1 = "generatedpaths/bfs/map1.txt" b_map2 = "generatedpaths/bfs/map2.txt" b_map3 = "generatedpaths/bfs/map3.txt" d_map1 = "generatedpaths/dfs/map1.txt" d_map2 = "generatedpaths/dfs/map2.txt" d_map3 = "generatedpaths/dfs/map3.txt" print "\nBFS - Map1" world = World(Util.read_file(map1), b_map1) bfs_search = BFS(world) print timeit.Timer(bfs_search.search).timeit(1) print "\nBFS - Map2" world = World(Util.read_file(map2), b_map2) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nBFS - Map3" world = World(Util.read_file(map3), b_map3) bfs_search = BFS(world) bfs_search.search() print timeit.Timer(bfs_search.search).timeit(1) print "\nDFS - Map1"
def run(self): R = len(self.content['starts']) # robots N = self.content['N'] # grid size # We use a breadth-first search to determine the horizon, i.e., # upper complexity bound, of the problem, based on the maximum distance # of a goal from the start positions of the paths. distance_to_target = [] bfs = BFS(N, self.content['starts'], self.content['obstacles']) for i, source in enumerate(bfs.starts): bfs.search(source) distance_to_target.append(bfs.G[tuple( self.content['goals'][i])]['d']) H_MIN = max(distance_to_target) # horizon H_MAX = int(H_MIN * self.h_mult) H_MAX_ORIG = H_MAX logging.log(logging.INFO, 'BFS lower bound: {}.'.format(H_MIN)) logging.log(logging.INFO, 'Setting H_MAX to h_mult * {}: {}'.format(H_MIN, H_MAX)) if self.search == 'binary': H = (H_MAX - H_MIN) // 2 + H_MIN elif self.search == 'linear': H = H_MIN else: logging.log(logging.ERROR, 'Search method is not one of "linear", "binary".') exit() logging.log(logging.INFO, 'Beginning search with horizon: {}'.format(H)) # H denotes the horizon (makespan) we are currently checking. # If H is too small, there will be no solution and the solver will # return *unsat*. H_MAX is the maximum possible horizon of the problem, # as computed above using BFS. while H < H_MAX: # make the EF-SMT instance here plan = [[[ Symbol('p_%d^%d-0' % (i, j), INT), Symbol('p_%d^%d-1' % (i, j), INT) ] for j in range(H)] for i in range(R)] attack = [[Symbol('a_%d-0' % i, INT), Symbol('a_%d-1' % i, INT)] for i in range(H)] # There is an implicit "exists" quantifier out front on the plan # variables. We are asking the solver to determine if there exists a # model for the plan variables s.t. the plan is a valid MAPF # solution, and s.t. forall choices (in (Z^2)^H) for the attack # variables, the attack is not a valid attack on the plan. formula = ForAll( [symvar for coordinate in attack for symvar in coordinate], And( IsPlan(plan, N, self.content['starts'], self.content['goals'], self.content['safes'] + self.content['obstacles']), Not( IsAttack(attack, plan, N, self.content['obstacles'], self.content['safes'])))) try: model = self.get_model(formula) except timeout_decorator.TimeoutError: model = None # If the solver returns a sat result, we ask for a satisfying model. # The makespan of the MAPF solution will be H (<= H_MAX). if model: control = [[[ model.get_py_value(plan[i][j][0]), model.get_py_value(plan[i][j][1]) ] for j in range(H)] for i in range(R)] self.content['control'] = list(zip(*control)) logging.log(logging.INFO, 'Found solution for horizon: {}'.format(H)) if self.search == 'linear': break else: H_MAX = H H = (H_MAX - H_MIN) // 2 + H_MIN else: logging.log(logging.INFO, 'UNSAT for H={}, updating H.'.format(H)) if self.search == 'linear': H += 1 else: H_MIN = H + 1 H = (H_MAX - H_MIN) // 2 + H_MIN if 'control' not in self.content: logging.log(logging.INFO, 'UNSAT for H_MAX={}.'.format(H_MAX_ORIG))
for line in txtFile.splitlines(): try: if line[1] == ',': if len(playerPositions) == 0: playerPositions.append(int(line[0])) playerPositions.append(int(line[2])) else: boxPositions.append([int(line[0]), int(line[2])]) else: j = 0 temp = [] for a in line.replace('\n', ''): temp.append(a) if a == 'X': goals.append([i, j]) j += 1 gameTable.append(temp) i += 1 except IndexError: pass readLevel(sys.argv[1]) print(BFS(gameTable, playerPositions, goals, boxPositions)) print(DFS(gameTable, playerPositions, goals, boxPositions)) print(IDFS(gameTable, playerPositions, goals, boxPositions))
def main(): pygame.init() # Taking input from user n = int(input("Enter grid size:")) Sx, Sy = [int(x) for x in input("Enter knight coords:").split()] Tx, Ty = [int(x) for x in input("Enter queen coords:").split()] # Setting up the screen and images res = (n * pixels, n * pixels) gameDisplay = pygame.display.set_mode(res) queen = pygame.image.load("queen.png") knight = pygame.image.load("knight.png") # Initializing the board and the algo createChessboard(gameDisplay, n) placeEntity(queen, Ty, Tx, gameDisplay) b = BFS(n, Sx, Sy, Tx, Ty) # game loop running = True while running: if b.q: # returns current node and previous node t, prev = b.search() placeEntity(knight, t[1], t[0], gameDisplay) markVisited(prev[1], prev[0], gameDisplay) pygame.display.update() time.sleep(1) if t == (Tx, Ty): createChessboard(gameDisplay, n) placeEntity(queen, Ty, Tx, gameDisplay) placeEntity(knight, Sy, Sx, gameDisplay) path = b.createPath() for i, j in path[1:]: markVisited(j, i, gameDisplay) pygame.display.update() continue if b.q == []: createChessboard(gameDisplay, n) cross = pygame.image.load("cross.jpg") placeEntity(cross, Ty, Tx, gameDisplay) placeEntity(knight, Sy, Sx, gameDisplay) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break print("Target position ", (Tx, Ty), " reached: ", b.visited[Tx][Ty]) pygame.quit()