def main(): running = True algorithm = input("What algorithm should be checked?: ") if algorithm == "all": checks = int( input("how many times should the algorithms be checked?: ")) for mapNr in range(3): testAlgs(makeMap(mapNr + 1), mapNr + 1, checks) Pygame.update() else: mapNr = int(input("What map should be tested? (1-3): ")) map = makeMap(mapNr) Pygame.init(map) if algorithm == "dfs" or algorithm == "depthfirstsearch": result = Pathfinder.findPath("dfs", map) Pygame.drawPath(result[0], (255, 255, 0)) elif algorithm == "bfs" or algorithm == "breadthfirstsearch": result = Pathfinder.findPath("bfs", map) Pygame.drawPath(result[0], (0, 150, 140)) elif algorithm == "astar" or algorithm == "a*": result = Pathfinder.findPath("a*", map) Pygame.drawPath(result[0], (0, 50, 100)) elif algorithm == "custom": result = Pathfinder.findPath("custom", map) Pygame.drawPath(result[0], (120, 0, 255)) while running is True: running = Pygame.update()
async def on_message(message): global list if message.author == client.user: return if re.match(r'send m.+', message.content, re.I) or re.match( r'sawaw puas', message.content) is not None: date = re.findall(r'[a-zA-Z]+ (\d+)', message.content) if re.search('[T|t]oday', message.content) != None: date = d.today().strftime('%Y%m%d') if type(date) is not str: list = Pathfinder.getpath(date[0]) else: list = Pathfinder.getpath(date) i = 0 while i < len(list): with open('iisc.ugmemes\\' + list[i], 'rb') as file: meme = discord.File(file) await message.channel.send(file=meme) date_time = list[i].replace('.jpg', '') await message.channel.send(Captions.caption(date_time)) time.sleep(1) i = i + 1
def findPath(self, reference, start, end): """ Start computing the Path. @param reference: the reference of the settler who needs the path @param start: the startnode @param end: the endnode """ if self.islands.sameIsland(start, end): pf = Pathfinder(self.pathstorage) lock = threading.Lock() # computing the (macro)path: path = pf.aStar(start, end, None) # obstaclemap is None for testing # TODO: if both nodes are at the same island, there should be a path every time # if a macropath was computed: if abs(path[0][0] - path[1][0]) > 1 or abs(path[0][1] - path[1][1]) > 1: macro_path = path last_index = len(path) - 1 #path = [] i = 0 # only every second node of the macro path is used for node in macro_path: if i % 2 == 0 and i + 2 < last_index: temp_path = pf.aStar(node, macro_path[i + 2], None) lock.acquire( ) # because only one thread should access the one FIFO self.fifo.add(reference, temp_path) lock.release() #print temp_path #for item in temp_path: # path.append(item) time.sleep(2) elif i % 2 == 0: # endnode is closer than one macrostep temp_path = pf.aStar(node, end, None) lock.acquire() self.fifo.add(reference, temp_path) lock.release() #print temp_path #for item in temp_path: # path.append(item) break i = i + 1 else: # its a short path (no macropath needed) lock.acquire() self.fifo.add(reference, path) lock.release() else: # start- and endpoint not at the same island - no path can be computed lock.acquire() self.fifo.add(reference, None) lock.release()
def findPath(self, reference, start, end): """ Start computing the Path. @param reference: the reference of the settler who needs the path @param start: the startnode @param end: the endnode """ if self.islands.sameIsland(start, end): pf = Pathfinder(self.pathstorage) lock = threading.Lock() # computing the (macro)path: path = pf.aStar(start, end, None) # obstaclemap is None for testing # TODO: if both nodes are at the same island, there should be a path every time # if a macropath was computed: if abs(path[0][0] - path[1][0]) > 1 or abs(path[0][1] - path[1][1]) > 1: macro_path = path last_index = len(path) - 1 #path = [] i = 0 # only every second node of the macro path is used for node in macro_path: if i%2 == 0 and i+2 < last_index: temp_path = pf.aStar(node, macro_path[i+2], None) lock.acquire() # because only one thread should access the one FIFO self.fifo.add(reference, temp_path) lock.release() #print temp_path #for item in temp_path: # path.append(item) time.sleep(2) elif i%2 == 0: # endnode is closer than one macrostep temp_path = pf.aStar(node, end, None) lock.acquire() self.fifo.add(reference, temp_path) lock.release() #print temp_path #for item in temp_path: # path.append(item) break i = i + 1 else: # its a short path (no macropath needed) lock.acquire() self.fifo.add(reference, path) lock.release() else: # start- and endpoint not at the same island - no path can be computed lock.acquire() self.fifo.add(reference, None) lock.release()
def execute(self, agent): pos = agent.getPos() if agent.getPath() == [] or agent.getPath()[len(agent.getPath()) - 1] != agent.base.getPos(): agent.setPath(Pathfinder.findPath(agent, agent.base.getPos())) elif not agent.getLocked(): diff = (time.time() - Agents.agent.getTimer(agent) ) * TimeMultiplier.timeMultiplier if Map.map[pos[0]][pos[1]] in ("G", "T", "t"): traverseTime = StatParser.statDict["tsSlowed"] else: traverseTime = StatParser.statDict["tsGround"] if diff >= traverseTime: agent.setTimer(time.time()) agent.setPos(agent.getPath()[0]) agent.setPath(agent.popPath()) if agent.getPos() == agent.base.getPos(): agent.setPath([]) if agent.getInventory() == "wood": agent.base.addWood() elif agent.getInventory() == "minerals": agent.base.addMinerals() agent.setInventory("empty") if agent.getRole() == "worker": agent.setState(locateMaterials()) elif agent.getRole() == "builder": agent.setState(idle()) elif agent.getJob() in ("coalWorker", "weaponSmith", "smelteryWorker"): agent.setState(findWorkStation())
def execute(self, agent): if not agent.getPath(): workDict = { "coalWorker": "coalFurnace", "weaponSmith": "blacksmith", "smelteryWorker": "smeltery" } for building in agent.base.getBuildings(): if building.getName() == workDict[ agent.getJob()] and not building.getOccupied(): agent.setPath(Pathfinder.findPath(agent, building.getPos())) building.setOccupied(True) agent.setJob(building) break else: pos = agent.getPos() diff = (time.time() - Agents.agent.getTimer(agent) ) * TimeMultiplier.timeMultiplier if Map.map[pos[0]][pos[1]] in ("G", "T", "t"): traverseTime = StatParser.statDict["tsSlowed"] else: traverseTime = StatParser.statDict["tsGround"] if diff >= traverseTime: agent.setTimer(time.time()) agent.setPos(agent.getPath()[0]) agent.setPath(agent.popPath()) if not agent.getPath(): agent.setState(work())
def findMinerals(self, agent): mineralPrioList = [] pos = agent.getPos() # Add all ores in the world and sort by closeness to spawn for ore in Resources.mineralLeft: if FogOfWar.fogOfWar[ore[0]][ore[1]]: mineralPrioList.append( (ore[0], ore[1], abs(ore[0] - pos[0]) + abs(ore[1] - pos[1]))) mineralPrioList.sort(key=lambda x: x[2]) # If agent has no path, go to closest found ore if not agent.getPath() and mineralPrioList: agent.setPath( Pathfinder.findPath( agent, (mineralPrioList[0][0], mineralPrioList[0][1]))) Resources.mineralFound( (mineralPrioList[0][0], mineralPrioList[0][1])) elif agent.getPath(): self.move(agent, pos) if Resources.gatherMinerals(agent): agent.setTimer(time.time()) agent.setState(returnHome())
def testAlgs(map, mapNr, checks): dfsDiff = 0 bfsDiff = 0 astarDiff = 0 customDiff = 0 Pygame.init(map) for i in range(checks): result = Pathfinder.findPath("dfs", map) Pygame.drawPath(result[0], (255, 255, 0)) dfsDiff += result[1] for j in range(checks): result = Pathfinder.findPath("bfs", map) Pygame.drawPath(result[0], (0, 150, 140)) bfsDiff += result[1] for k in range(checks): result = Pathfinder.findPath("a*", map) Pygame.drawPath(result[0], (0, 50, 100)) astarDiff += result[1] for l in range(checks): result = Pathfinder.findPath("custom", map) Pygame.drawPath(result[0], (120, 0, 255)) customDiff += result[1] print("\n") print("|>------------------------------<|") print("Average time for dfs test on map" + str(mapNr) + ":") print(dfsDiff / checks) print("|>------------------------------<|") print("Average time for bfs test on map" + str(mapNr) + ":") print(bfsDiff / checks) print("|>------------------------------<|") print("Average time for astar test on map" + str(mapNr) + ":") print(astarDiff / checks) print("|>------------------------------<|") print("Average time for custom alg test on map" + str(mapNr) + ":") print(customDiff / checks)
def getPath(self): pm = Pathfinder.PathManager() path = pm.findPath(self.startPoint, self.endPoint, self.lines) currentNode = path.head nodeArray = [] for i in range(path.size - 1): pathLine = ln(currentNode.point, currentNode.nextNode.point, "red") self.drawLine(pathLine) nodeArray.append(currentNode) currentNode = currentNode.nextNode return path
def __init__(self): self.root = tk.Tk() self.root.title(self._APPLICATION_NAME) self.root.minsize(width=self._MIN_WIDTH, height=self._MIN_HEIGHT) self.root.maxsize(width=self._MIN_WIDTH, height=self._MIN_HEIGHT) self.pathfinder = Pathfinder.Pathfinder() self._init_default_states() self._init_canvas() self._init_turtle() self._init_canvas_buttons()
def execute(self, agent): map = Map.map pos = agent.getPos() traverseTime = 10 # Delay walking speed diff = (time.time() - Agents.agent.getTimer(agent)) * TimeMultiplier.timeMultiplier if map[pos[0]][pos[1]] in ("G", "T", "t"): traverseTime = StatParser.statDict["tsSlowed"] else: traverseTime = StatParser.statDict["tsGround"] if diff >= traverseTime: agent.setTimer(time.time()) # Set/declare variables fogOfWar = FogOfWar.fogOfWar fogOfWarList = FogOfWar.fogOfWarList r = Map.r path = agent.getPath() woodsFound = False WoodsPos = (0, 0) # Check if neighbour is tree and close to fog of war for next in r: if map[pos[0] + next[0]][pos[1] + next[1]] == "T" and not fogOfWar[ pos[0] + (next[0] * 2)][pos[1] + (next[1] * 2)]: woodsFound = True woodsPos = (pos[0] + next[0], pos[1] + next[1]) break # If has no path, get random finish in unexplored area if not woodsFound: if not fogOfWarList: agent.setState(returnHome()) elif not path: index = random.randrange(0, len(fogOfWarList) - 1) goal = fogOfWarList[index] agent.setPath(Pathfinder.findPath(agent, goal)) else: agent.setPos(agent.getPath()[0]) agent.setPath(agent.popPath()) # If woods found, discard path and walk that way else: if agent.getPath() != []: agent.setPath([]) agent.setPos(woodsPos)
def run_app2(): """ usage: curl -i -H "Content-Type: application/json" -X POST -d '{"test":"data"}' http://127.0.0.1:5000/pathfinder/run_app2 curl -i -H "Content-Type: application/json" -X POST --data-binary @/pathfinder/PFinput.json http://127.0.0.1:5000/pathfinder/run_app2 curl -i -H "Content-Type: application/json" -vX POST -d @PFinput.json http://127.0.0.1:5000/pathfinder/run_app2 """ if not request.json: flask_restful.abort(400) PFinput = request.json result = Pathfinder.pathfinder_algorithm(PFinput) #return json.dumps(result, indent=4), 200 return jsonify(PATH=result), 200
def go(self,month,cal_index): if not self.overridesjson[month][cal_index]: if len(self.startlocation)>0: ll = '' header = Label(self.master, text='Schedule for ' + str(Months[month])+' '+str(self.cal[cal_index].date), bg = '#fffffc', font = ('Verdana',11)) header.grid(row=1,sticky='NW') self.line = Canvas(self.master,width=256,height=3,bg='#fffffc',relief='flat') self.line.create_line(-100,0,300,0,width=13,fill='#2F97C1') self.line.grid(row=2,columnspan=7,sticky='NW') listbox = Listbox(self.master, height=20, width=40, bg = "#ffffff", font = ('Arial Bold',10), fg = '#0f0f0f', selectbackground = '#fffffc', selectforeground = '#0f0f0f', relief = 'flat', activestyle = None) listbox.grid(pady=5,column=0) try: tasklist = self.cal[cal_index].tasklist jobandAddy = {} for x in tasklist: jobandAddy[x.addressString] = x.job addressbook = Pathfinder.addressbook([x.addressString for x in tasklist] + [self.startlocation]) travelPath = addressbook.traveller(self.startlocation)[0] count = 1 for x in travelPath: listbox.insert(END,str(count)+'. '+x) listbox.insert(END,' > '+ jobandAddy[x].title()) count+=1 except KeyError: #warning(['Error: Address on',self.cal[cal_index].date,'Not Recognized'] pass else: #warning(['Please enter a start location in settings','before a list can be viewed']) pass else: print 'eat a balls'
def run_app(): """ usage: curl -i -H "Content-Type: application/json" -X POST http://127.0.0.1:5000/pathfinder/run_app url = '' # example to actually run # url = 'http://httpbin.org/post' data = {} # example of JSON data #data = {'a': 10, 'b': [{'c': True, 'd': False}, None]} headers = {'Content-Type': 'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) return json.dumps(r.json(), indent=4) """ result = Pathfinder.pathfinder_algorithm_from_file() return jsonify(PATH=result), 200
def _fill(self, start_coord, island_tag): """ Usesd by the searchIslands method. Gets a hole area (island) by using the iterative floodfilling algorithm. @param start_coord: the coordinate to start with the floodfill algorithm @param island_tag: the tag for this specific island """ stack = [] stack.append(coord_start) while stack != []: coord = stack.pop(0) if (coord not in self.islands.keys()): self.islands[coord] = island_tag successors = Pathfinder.successors(coord) for entry in successors: stack.append(entry)
def findWood(self, agent): woodPrioList = [] pos = agent.base.getPos() # Add all trees in the world and sort by closeness to spawn for tree in Resources.woodLeft: if FogOfWar.fogOfWar[tree[0]][tree[1]]: woodPrioList.append( (tree[0], tree[1], abs(tree[0] - pos[0]) + abs(tree[1] - pos[1]))) woodPrioList.sort(key=lambda x: x[2]) # If agent has no path, go to closest found tree if not agent.getPath() and woodPrioList: agent.setPath( Pathfinder.findPath(agent, (woodPrioList[0][0], woodPrioList[0][1]))) Resources.treeFound((woodPrioList[0][0], woodPrioList[0][1])) elif agent.getPath(): self.move(agent, agent.getPos()) if Resources.gatherWood(agent): agent.setTimer(time.time()) agent.setState(woodCutting())
# @param NONE # @return NONE # description: Check if the Ghost Rover and User Rover are close enough to warrant capture def checkForCapture(): if (abs(ghost.X - user.X) < CAUGHT_DIST and abs(ghost.Y - user.Y) < CAUGHT_DIST): user.C = True print "Captured" pathfinder.captured() else: user.C = False #print "Not Captured" pathfinder = Pathfinder() # Wait for blocks # while 1: count = pixy_get_blocks(100, blocks) if count > 0: # Blocks found # for index in range(0, count): #print"Message Queue Size %d" % count #print "Raw Data:" #print '[BLOCK_TYPE=%d SIG=%d X=%3d Y=%3d WIDTH=%3d HEIGHT=%3d]' % (blocks[index].type, blocks[index].signature, blocks[index].x, blocks[index].y, blocks[index].width, blocks[index].height) if (convertRawData(index)): UPDATE = 1 print(UPDATE) if ((user.nX >= 0) and (ghost.nX >= 0) and (corner1.X >= 0)
def provisioner(): """ *NOT DEFINED YET* usage: IP address needed (localhost not valid) curl -i -H "Content-Type: application/xml" -X POST --data-binary @/pathfinder/circuitRequest.xml http://127.0.0.1:5000/pathfinder/provisioner curl -i -H "Content-Type: application/xml" -vX POST -d @circuitRequest.xml http://127.0.0.1:5000/pathfinder/provisioner """ controllerIp = "127.0.0.1:8080" midSwitches = defaultdict(list) if request.headers['Content-Type'] == 'application/xml': #parse data from XML input to python parsed_data = BeautifulSoup(request.data) #E2E ip addresses and ports src_ip = parsed_data.source.address.string dst_ip = parsed_data.destination.address.string #src_port = parsed_data.source.linkport.string #considering #dst_port = parsed_data.destination.linkport.string #considering #label = parsed_data.label.string # requested QoS parameters max_delay = int(parsed_data.qos_policy.maxlatency.string) max_jitter = int(parsed_data.qos_policy.maxjitter.string) max_pLoss = int(parsed_data.qos_policy.maxpacketloss.string) min_band = int(parsed_data.qos_policy.minthroughput.string) #identify the request req_id = "FIBRE-test" #request input data #input_data = {"requestID": req_id, "ip-src": src_ip, "ip-dst": dst_ip, "src-port": src_port, "dst-port": dst_port, "bandwidth": min_band, "delay": max_delay, "packet-loss": max_pLoss, "jitter": max_jitter} input_data = {"requestID": req_id, "ip-src": src_ip, "ip-dst": dst_ip, "bandwidth": min_band, "delay": max_delay, "packet-loss": max_pLoss, "jitter": max_jitter} #recover topology file from: manually set or tester.py with open('PFinput_stats.json', 'r') as PFtopo: topofile = json.load(PFtopo) PFtopo.close() adapted_request = Adapter.adapter(controllerIp, input_data, topofile) with open('PFrequest.json', 'wb') as PFtester: json.dump(adapted_request, PFtester, indent=4) PFtester.close() print "Adapted request", adapted_request result = Pathfinder.pathfinder_algorithm(adapted_request) print result with open('path.json', 'wb') as PFpath: json.dump(result, PFpath, indent=4) PFpath.close() Forwarding.smart_flow_pusher(src_ip, dst_ip, controllerIp, result, min_band, queues) return jsonify(PATH=result), 200 else: flask_restful.abort(400)
import makeMaze import Pathfinder from PIL import Image from Grid import Grid Input = "maze.png" Output = "output.png" maze = makeMaze.make(Input) #lines = file.readlines() #aze = [] #for i in lines: # maze.append([]) # for j in i.strip(): # maze[-1].append(j) grid = Grid(len(maze), len(maze[0])) grid.grid = maze path = Pathfinder.aStar(grid.grid, grid.find("x"), grid.find("o"), "#") img = Image.open("maze.png") for i in path: img.putpixel((i[1], i[0]), (0, 255, 0)) img.save(Output)
def main(): gameRunning = True im = Image.open("graphics/map4.png", "r") pixels = list(im.getdata()) myMap = Map(Globals.gTileSize) # create a map from the image myMap.loadMap(pixels, im.size[0], im.size[1]) graphicsMgr = GraphicsManager(myMap) myPathfinder = Pathfinder(myMap) path = None startCoord = (0, 0) endCoord = (0, 0) ninja1 = Entity("ninja", myPathfinder) ninja2 = Entity("ninja", myPathfinder) ninja1.setPosition((0, 6)) ninja2.setPosition((5, 0)) ninjas = [ninja1, ninja2] Globals.gEntities = [ninja1, ninja2] ninja1.setPath( myPathfinder.findPath( ninja1.getTilePos(), (9, 0) ) ) ninja2.setPath( myPathfinder.findPath( ninja2.getTilePos(), (2, 10) ) ) ninja1.ChangeState(Globals.gStates["MoveAlongPath"]) ninja2.ChangeState(Globals.gStates["MoveAlongPath"]) selectedNinja = ninja1 ninja1.select() Globals.gDeltaTime = time.clock() - Globals.gDeltaTime while(gameRunning): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: mouseTilePos = getTileCoords(event.pos, Globals.gTileSize) if event.button == 3: # set end pos startCoord = selectedNinja.getTilePos() endCoord = mouseTilePos path = myPathfinder.findPath(startCoord, endCoord) if( not path ): print "no path" else: selectedNinja.setPath(path) selectedNinja.ChangeState(Globals.gStates["MoveAlongPath"]) elif event.button == 1: print "mouse coord: ", mouseTilePos # select ninja for ninja in ninjas: ninja.unselect() ninjaPos = ninja.getTilePos() if ninjaPos[0] == mouseTilePos[0] and ninjaPos[1] == mouseTilePos[1]: selectedNinja = ninja ninja.select() for ninja in ninjas: ninja.update() graphicsMgr.render(myMap, path, ninjas)
center = Point(x, y) radius = min(boxWidth, boxHeight) / 4 dot = Circle(center, radius) if node == target: dot.setFill('#00ff7d') else: dot.setFill('#007dff') dot.draw(win) dot.setWidth(0) label = Text(center, str(number)) label.setFill('#ffffff') label.setSize(min(boxWidth, boxHeight) / 6) label.draw(win) pathfinder = Pathfinder(map, root, target) pathfinder.search() checked = pathfinder.checked path = pathfinder.retrace() drawGrid() for node in checked: drawNode(node) sleep(0.5) for i in range(len(path)): drawPathNode(path[i], i + 1) sleep(0.5) for dot in dots: dot.undraw()