def nearest(self, position): if len(self.points) == 0: return None # calc distances to our position distances = {} for p in self.points: distances[p] = calc_distance( p, position ) # if the point we just checked is within the units sight range, return this point immediately # this makes for a speedier algorithm also less exact #if distances[p] < self.sight: # return p sorted_d = sorted( distances.items(), key = lambda x: x[1] ) building_found = closest_thing( position, self.distances.keys() ) if building_found == None: return sorted_d[0][0] sorted_d = list(sorted_d[0:5]) # take first four sorted points for i in range( 0, len(sorted_d) ): sorted_d[i] = list(sorted_d[i]) sorted_d[i][1] = calc_distance( sorted_d[i][0], building_found.position ) + sorted_d[i][1] sorted_d = sorted( distances.items(), key = lambda x: x[1] ) return sorted_d[0][0]
def building(self, b): if not b in self.distances: # ordered list of our points distances = {} for p in self.points: distances[p] = calc_distance( p, b.position ) distances = sorted( distances.items(), key = lambda x: x[1] ) #rebuild a list of points now that they are sorted sorted_p = [] for i in distances: sorted_p.append( i[0] ) # only take the point, which is in [0], the distance is in [1] self.distances[b] = sorted_p