def checkGameState(self, task, message = None): goodEndingText = OnscreenText(text="", style=1, fg=(0,0,1,0.01), pos=(0,.4), align=TextNode.ACenter, scale = .25, mayChange = True) BaadEndingText = OnscreenText(text="", style=1, fg=(1,0,0,0.01), pos=(0,.4), align=TextNode.ACenter, scale = .25, mayChange = True) if(self.fadeCounter > 0): if(self.__mainAgent.hasKey(self.room1Key) and self.__mainAgent.hasKey(self.room2Key) and self.__mainAgent.hasKey(self.room3Key)): self.hasAllKeys = True #goodEndingText.setText("You have all 3 keys!") if(self.hasAllKeys): goodEndingText.setText("You have all 3 keys!") if(PathFinder.distance(self.__mainAgent, self.__room1NPC) < 5 and self.__room1NPC.getState() != "returnKey"): if(not self.__mainAgent.hasKey(self.room1Key)): self.playerWasKilledByNPC1 = True if(self.playerWasKilledByNPC1): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Alpha") if(PathFinder.distance(self.__mainAgent, self.__room2NPC) < 5 and self.__room2NPC.getState() != "returnKey"): if(not self.__mainAgent.hasKey(self.room2Key)): self.playerWasKilledByNPC2 = True if(self.playerWasKilledByNPC2): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Beta") if(PathFinder.distance(self.__mainAgent, self.__room3NPC) < 5 and self.__room3NPC.getState() != "returnKey"): if(not self.__mainAgent.hasKey(self.room3Key)): self.playerWasKilledByNPC3 = True if(self.playerWasKilledByNPC3): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Gamma") return Task.cont
def followBestPath(self): """ This function tells the NPC to continue following the best path Basically, it checks the currentTarget to determine if we're already seeking to the correct waypoint. When we finally reach the currentTarget, we pop it off the bestPath list and set the currentTarget to the next waypoint in bestPath. At this point, we also need to re-run AStar from our new currentTarget to the destination, which is bestPath[-1]. We store as our new bestPath and continue from there. """ assert self.bestPath, "self.bestPath must be valid before calling followBestPath" if self.currentTarget is not self.bestPath[0]: self.currentTarget = self.bestPath[0] # Comment out next two lines to disable path smoothening. if self.pathSmoothening: # attempting to smoothen path # print("Checking if there is a clear path to next target") while len(self.bestPath) > 1 and PathFinder.waypointIsReachable(self, self.bestPath[1]): # print("Next waypoint is reachable, skipping to next") self.bestPath.pop(0) self.currentTarget = self.bestPath[0] # have we reached our currentTarget? if PathFinder.distance(self, self.currentTarget) < 2: # This number must be greater than distance in seek() assert self.currentTarget == self.bestPath.pop( 0 ), "We've reached our currentTarget, but it's not in our bestPath" # Are there any waypoints left to follow? if self.bestPath: self.currentTarget = self.bestPath[0] if len(self.bestPath) > 1: self.bestPath = PathFinder.AStar(self.bestPath[0], self.bestPath[-1], self.waypoints)
def __init__(self, eps=1e-5, city='Amherst, Massachusetts, USA', network_type='drive', timeout=100): ''' Parameters: eps (float): epsilon value for the inverse grade calculation city (str): city of the map network_type (str): type of the map timeout (int): timeout for path finding algorithm ''' self._eps = eps # parameter for the inverse calculation self.pathFinder = PathFinder(timeout) # get map data graph for some city self.G = ox.graph_from_place(city, network_type=network_type) self.min_x = float('inf') self.max_x = -float('inf') self.min_y = float('inf') self.max_y = -float('inf') for node in self.G.nodes: nd = self.G.nodes[node] if nd['x'] > self.max_x: self.max_x = nd['x'] if nd['x'] < self.min_x: self.min_x = nd['x'] if nd['y'] > self.max_y: self.max_y = nd['y'] if nd['y'] < self.min_y: self.min_y = nd['y']
def checkGameState(self, task, message=None): goodEndingText = OnscreenText(text="", style=1, fg=(0, 0, 1, 0.01), pos=(0, .4), align=TextNode.ACenter, scale=.25, mayChange=True) BaadEndingText = OnscreenText(text="", style=1, fg=(1, 0, 0, 0.01), pos=(0, .4), align=TextNode.ACenter, scale=.25, mayChange=True) if (self.fadeCounter > 0): if (self.__mainAgent.hasKey(self.room1Key) and self.__mainAgent.hasKey(self.room2Key) and self.__mainAgent.hasKey(self.room3Key)): self.hasAllKeys = True #goodEndingText.setText("You have all 3 keys!") if (self.hasAllKeys): goodEndingText.setText("You have all 3 keys!") if (PathFinder.distance(self.__mainAgent, self.__room1NPC) < 5 and self.__room1NPC.getState() != "returnKey"): if (not self.__mainAgent.hasKey(self.room1Key)): self.playerWasKilledByNPC1 = True if (self.playerWasKilledByNPC1): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Alpha") if (PathFinder.distance(self.__mainAgent, self.__room2NPC) < 5 and self.__room2NPC.getState() != "returnKey"): if (not self.__mainAgent.hasKey(self.room2Key)): self.playerWasKilledByNPC2 = True if (self.playerWasKilledByNPC2): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Beta") if (PathFinder.distance(self.__mainAgent, self.__room3NPC) < 5 and self.__room3NPC.getState() != "returnKey"): if (not self.__mainAgent.hasKey(self.room3Key)): self.playerWasKilledByNPC3 = True if (self.playerWasKilledByNPC3): self.fadeCounter = self.fadeCounter - 1 BaadEndingText.setText("Killed by Eve clone Gamma") return Task.cont
def followBestPath(self): """ This function tells the NPC to continue following the best path Basically, it checks the currentTarget to determine if we're already seeking to the correct waypoint. When we finally reach the currentTarget, we pop it off the bestPath list and set the currentTarget to the next waypoint in bestPath. At this point, we also need to re-run AStar from our new currentTarget to the destination, which is bestPath[-1]. We store as our new bestPath and continue from there. """ assert self.bestPath, "self.bestPath must be valid before calling followBestPath" if self.currentTarget is not self.bestPath[0]: self.currentTarget = self.bestPath[0] #Comment out next two lines to disable path smoothening. if (self.pathSmoothening): #attempting to smoothen path #print("Checking if there is a clear path to next target") while (len(self.bestPath) > 1 and PathFinder.waypointIsReachable(self, self.bestPath[1])): #print("Next waypoint is reachable, skipping to next") self.bestPath.pop(0) self.currentTarget = self.bestPath[0] # have we reached our currentTarget? if PathFinder.distance( self, self.currentTarget ) < 2: #This number must be greater than distance in seek() assert self.currentTarget == self.bestPath.pop( 0 ), "We've reached our currentTarget, but it's not in our bestPath" # Are there any waypoints left to follow? if self.bestPath: self.currentTarget = self.bestPath[0] if len(self.bestPath) > 1: self.bestPath = PathFinder.AStar(self.bestPath[0], self.bestPath[-1], self.waypoints)
def start(self): self.bestPath = PathFinder.AStar(self, self.mainTarget, self.waypoints)
class MapModel(): def __init__(self, eps=1e-5, city='Amherst, Massachusetts, USA', network_type='drive', timeout=100): ''' Parameters: eps (float): epsilon value for the inverse grade calculation city (str): city of the map network_type (str): type of the map timeout (int): timeout for path finding algorithm ''' self._eps = eps # parameter for the inverse calculation self.pathFinder = PathFinder(timeout) # get map data graph for some city self.G = ox.graph_from_place(city, network_type=network_type) self.min_x = float('inf') self.max_x = -float('inf') self.min_y = float('inf') self.max_y = -float('inf') for node in self.G.nodes: nd = self.G.nodes[node] if nd['x'] > self.max_x: self.max_x = nd['x'] if nd['x'] < self.min_x: self.min_x = nd['x'] if nd['y'] > self.max_y: self.max_y = nd['y'] if nd['y'] < self.min_y: self.min_y = nd['y'] def add_elevation_info(self, api_key=None): ''' update the elevation and grade information for nodes and edges Parameters: api_key (str): Google API key for the elevation information ''' if api_key is None: with open("api_key.txt", "r") as f: api_key = f.readline() self.G = ox.add_node_elevations(self.G, api_key=api_key) self.G = ox.add_edge_grades(self.G) for e in self.G.edges: # change grade from ratio to value self.G.edges[e]['grade_abs'] *= self.G.edges[e]['length'] # calculate inverse grade_abs for maximum elevation path self.G.edges[e]['inv_grade_abs'] = 1 / ( self.G.edges[e]['grade_abs'] + self._eps) def path_info(self, path): ''' Return the length and elevation gain of the path Parameters: path (int): Path ID ''' length = self.pathFinder.get_weight_sum(self.G, path, 'length') height = self.pathFinder.get_weight_sum(self.G, path, 'grade_abs') return length, height def get_path(self, start, end, limit_ratio=1.5, weight='height', inverse=False): ''' Return the path with certain constraint Parameters: start (float tuple): coordinate for the start point end (float tuple): coordinate for the end point limit_ratio (float): the length restriction weight (str): path type inverse (bool): switch between maximum and minimum ''' return self.pathFinder.get_path(self.G, start, end, limit_ratio, weight, inverse) def plot_graph(self): fig, ax = ox.plot_graph(self.G) plt.show() def plot_path(self, path): fig, ax = ox.plot_graph_route(self.G, path, node_size=0) plt.show()
args = sys.argv[1:] try: if args: if os.path.exists(args[0]): # Starting time of the script startTime = time.time() # Intantiate a new Parser Parser = MatrixParser() # Parse the matrix from the file given matrix = Parser.getFileMatrix(args[0]) # Intantiate a new Path Finder Finder = PathFinder(matrix["rows"], matrix["columns"], matrix["content"]) # Get the longest (and steepest path) path = Finder.getLongestDescendentPath() # Execution time executionTime = time.time() - startTime print( json.dumps( {"ok": True, "result": path, "executionTime": executionTime}, ensure_ascii=False, ) ) else: raise FileNotFoundError(f"File {args[0]} does not exist")
def __init__(self): self.move_speed = 3 self.path_finder = PathFinder()
class EnemyMove(object): def __init__(self): self.move_speed = 3 self.path_finder = PathFinder() def enemy_move(self, player_x, player_z, enemy_x, enemy_z): player_int_x, player_int_z = self.get_nearest_can_reach_target_point( player_x, player_z, player_x, player_z) # if player is at can't reach area, then enemy will stop move if player_int_x is None and player_int_z is None: return [0, 0, 0] enemy_int_x, enemy_int_z = self.get_nearest_can_reach_target_point( enemy_x, enemy_z, player_x, player_z) if enemy_int_x is None and enemy_int_z is None: return [0, 0, 0] else: start_point = Point(enemy_int_x, enemy_int_z) end_point = Point(player_int_x, player_int_z) path_list = self.path_finder.find_path(start_point, end_point) target_point = self.get_next_target_point(path_list) if target_point is None: return [0, 0, 0] else: move_vector = [ target_point.X - enemy_x, 0, target_point.Z - enemy_z ] move_vector = self.vector_standardization(move_vector) return move_vector def get_nearest_can_reach_target_point(self, x, z, target_x, target_z): point_list = [] if self.path_finder.check_map(int((math.floor(x))), int(math.floor(z))): point_list.append((math.floor(x), math.floor(z))) if self.path_finder.check_map(int((math.ceil(x))), int(math.floor(z))): point_list.append((math.ceil(x), math.floor(z))) if self.path_finder.check_map(int((math.floor(x))), int(math.ceil(z))): point_list.append((math.floor(x), math.ceil(z))) if self.path_finder.check_map(int((math.ceil(x))), int(math.ceil(z))): point_list.append((math.ceil(x), math.ceil(z))) distances = [] for point_pair in point_list: distances.append( abs(target_x - point_pair[0]) + abs(target_z - point_pair[1])) min_distance = 100 min_loc = -1 for i in xrange(len(distances)): if distances[i] < min_distance: min_distance = distances[i] min_loc = i if len(point_list) != 0: return int(point_list[min_loc][0]), int(point_list[min_loc][1]) else: return None, None @staticmethod def vector_standardization(move_vector): vector_len = math.sqrt(move_vector[0] * move_vector[0] + move_vector[1] * move_vector[1] + move_vector[2] * move_vector[2]) return [n / vector_len for n in move_vector] @staticmethod def get_next_target_point(path_list): if len(path_list) == 0: return None if len(path_list) > 1: target_point = path_list[len(path_list) - 2] else: target_point = path_list[0] return target_point