def polygonEnvelope(polygon): # 多边形的顶点序列 partList = polygon.partList # 两个顶点 rt = Point() lb = Point() rt.x = lb.x = partList[0][0].x rt.y = lb.y = partList[0][0].y for i in range(len(partList)): for k in range(len(partList[i])): if partList[i][k].x < lb.x: lb.x = partList[i][k].x if partList[i][k].x > rt.x: rt.x = partList[i][k].x if partList[i][k].y < lb.y: lb.y = partList[i][k].y if partList[i][k].y > rt.y: rt.y = partList[i][k].y envelope = Envelope() envelope.rtPoint = rt envelope.lbPoint = lb return envelope
def getEnvelopeGravity(envelopeList): # rtPoint = Point() lbPoint = Point() rtPoint.x = lbPoint.x = envelopeList[0].rtPoint.x rtPoint.y = lbPoint.y = envelopeList[0].lbPoint.y for envelope in envelopeList: rt = envelope.rtPoint lb = envelope.lbPoint if lb.x < lbPoint.x: lbPoint.x = lb.x if lb.y < lbPoint.y: lbPoint.y = lb.y if rt.x > rtPoint.x: rtPoint.x = rt.x if rt.y > rtPoint.y: rtPoint.y = rt.y envelope = Envelope() envelope.lbPoint = lbPoint envelope.rtPoint = rtPoint gravity = Point() gravity.x = (rtPoint.x + lbPoint.x) / 2 gravity.y = (rtPoint.y + lbPoint.y) / 2 return gravity, envelope pass
def weakestDirection(self, point): """ 4方向の中で1番自分陣営の攻撃力が弱いポイント """ directions = [Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0)] d = min(directions, key=lambda d: self.damage(point.plus(d))) return point.plus(d)
def __init__(self, width, height, player_vision): self.map_width = width self.map_heigth = height self.start_point = Point(0,0) self.finish_point = Point(self.map_width-1, self.map_heigth-1) self.player_vision = player_vision self.restart_game = False
def handle_options(self): self.map_width = self.map_info['width'] self.map_height = self.map_info['height'] self.start_position = Point(self.s_pos['x'], self.s_pos['y']) self.player_position = self.start_position self.player_vision = self.player_info['player-vision'] self.exit_position = Point(self.f_pos['x'], self.f_pos['y'])
def change_positon(self, char): if char in "wsad": self.set_up_player.change_position(char) if self.read_new_position() == self.finish_point: self.restart_game = True elif char in "r": self.prepared_map.change_player_position(self.read_new_position(),Point(0,0)) self.set_up_player.position = Point(0,0)
def build_graph_context(graph) -> (Point, Point): # min of both axes using most points with min x and min y points = list(graph.keys()) points.sort(key=lambda x: x[0]) x1, x2 = points[0][0], points[-1][0] points.sort(key=lambda x: x[1]) y1, y2 = points[0][1], points[-1][1] return GraphContext(Point(x1, y1), Point(x2, y2))
def aroundStrength(self, point, size): if self._aroundStrength.get((point, size)): return self._aroundStrength[(point, size)] p1 = Point(point.x - size, point.y - size) p2 = Point(point.x + size, point.y + size) self._aroundStrength[(point, size)] = self.rangeStrength(p1, p2) return self._aroundStrength[(point, size)]
def tiebian(): global sidePoints sidePoints = np.array(sidePoints) yawAim = getYawAim(sidePoints) log.info('已加载导航点,共有%d个点' % len(sidePoints)) index = 0 pos = Point(g.getValue('ship').lat, g.getValue('ship').lng) # 判断刚开始时,是否需要原地转 state = State.TURN if utils.getDistance( pos, Point(sidePoints[0, 0], sidePoints[0, 1])) > 3 else State.GO try: while index < len(sidePoints): yaw = g.getValue('ship').yaw lat = g.getValue('ship').lat lng = g.getValue('ship').lng gz = g.getValue('ship').gz speed = g.getValue('ship').speed pShip = Point(lat, lng) pAim = Point(sidePoints[index, 0], sidePoints[index, 1]) isFirst = True if index == 0 else False if state == State.TURN: thrust = 0 dire = PID_Turn(pShip, pAim, yaw, -gz, yawAim[index], isFirst) if dire == 0: # 转弯完毕,进入直行阶段 state = State.GO elif state == State.GO: # 判断直线段或是曲线段,之后五个点期望角度最大误差 slowSpeed = True if angleArray_ptp( yawAim[index:index + 5]) > 15 or index == 0 else False log.info('Go:当前期望方向角 %.1f 度,slowSpeed是 %s' % yawAim[index], slowSpeed) dire, thrust = PID_Go(pShip, pAim, yaw, -gz, yawAim[index], slowSpeed, isFirst) dist = utils.getDistance(pShip, pAim) if state == State.GO and index > 0: # 将最近点序号作为当前序号 index = index_cal(pShip, index, SearchLength=10) #函数中使用了global量sidePoints log.info('当前处于第 %d 个点' % index) if dist < 1 and index == 0: state = State.TURN index += 1 if index == len(sidePoints): # 跑完 thrust = 0 dire = 0 data = struct.pack("hhb", int(thrust), int(dire), 0) g.getValue("can").send(0x544, data) log.info("%s\t%d\t%.1f\t%.1f\t%d" % (state, index, thrust, dire, dist)) time.sleep(1) except Exception: log.error('贴边Error', exc_info=True) log.info('导航结束')
class Envelope(object): # 外包矩形的四个顶点 rtPoint = Point() # 右上 lbPoint = Point() # 左下 def __str__(self): return "rt:" + "x:" + bytes(self.rtPoint.x) + " y:" + bytes(self.rtPoint.y) + " lb:" + "x:" + bytes( self.lbPoint.x) + " y:" + bytes(self.lbPoint.y)
def __init__(self, map_width, map_heigth, start_position, exit_positon): super().__init__(map_width, map_heigth, start_position, exit_positon) self.populate_walls() self.points_round = defaultdict() self.points_round = { 'up': Point(0, 1), 'right': Point(1, 0), 'down': Point(0, -1), 'left': Point(-1, 0) }
def read_from_file(filename, polygons=False): with open(os.path.join('data', filename), "r") as f: objects = [] for coordinates in f.readlines(): if polygons: list_of_pairs = list( zip(*[iter([int(i) for i in coordinates.split()])] * 2)) polygons = Polygon( vertices=[Point(x, y) for x, y in list_of_pairs]) objects.append(polygons) else: point = Point(*[int(i) for i in coordinates.split()]) objects.append(point) return objects
def main(): points = console_io.get_number_of_points() pie = Pie(Point(50, 50), 90, 50) lines = [] for index in range(points): lines.append(console_io.read_line()) index = 0 for line in lines: index += 1 percent, x, y = list(map(lambda l: int(l), line.split(' '))) is_inside = pie.is_inside(Point(x, y), percent) color = 'black' if is_inside else 'white' console_io.show_result(index, color)
def buildBase(self, workers): halfStrength = self.brain.aStage.enemies.rangeStrength( self.brain.castle.point, Point(SILBER_POINT, SILBER_POINT)) if self.brain.aStage.isStartEnemyAttack and len( self.brain.unit(UnitType.BASE)) < 1 and self.brain.aStage.five: worker = min(workers, key=lambda x: x.point.dist(self.brain.castle.point)) else: zero = Point(60, 60) worker = min(workers, key=lambda x: x.point.dist(zero)) self.brain.actions[worker.cid] = UnitType.BASE.value self.brain.aStage.resourceNum -= Cost[UnitType.BASE] workers.remove(worker)
def populate_borders(self): minus_one = -1 for width in range(-1, self.map_width + 1): bottom_border_wall = Wall(Point(width, minus_one), self) upper_border_wall = Wall(Point(width, self.map_heigth), self) self.walls_positions[ bottom_border_wall.position] = bottom_border_wall self.walls_positions[ upper_border_wall.position] = upper_border_wall for height in range(self.map_heigth): left_border_wall = Wall(Point(minus_one, height), self) right_border_wall = Wall(Point(self.map_width, height), self) self.walls_positions[left_border_wall.position] = left_border_wall self.walls_positions[ right_border_wall.position] = right_border_wall
def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount+1): line = lines[i] parts = line.split() points.append(Point(float(parts[0]), float(parts[1]))) # build a trivial solution # visit the nodes in the order they appear in the file solution_point = solution_function(points.copy()) solution = point_to_order(solution_point,points) # # calculate the length of the tour obj = total_length_by_point(solution_point) # prepare the solution in the specified output format output_data = '%.2f' % obj + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data
def draw_box( out_img: np.ndarray, box: Box, labels: Iterable[Tuple[str, Point]], color: Color = Color.red(), line_thickness: int = 2, ) -> np.ndarray: cv.rectangle( img=out_img, pt1=box.top_left, pt2=box.bottom_right, color=color.to_bgr(), thickness=line_thickness, ) for text, translation in labels: text_loc: Point = translate_point( Point(box.top_left_x, box.bottom_right_y), translation) cv.putText( img=out_img, text=text, org=text_loc, fontFace=cv.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=Color.orange().to_bgr(), thickness=2, ) return out_img
class Polyline(object): # id oid = "" # 起止点 startPoint = Point() endPoint = Point() lines = [] # type: list[Line] # 长度 _length = 0 def getLength(self): if self._length == 0: for seg in self.lines: self._length += seg.getLength() return self._length
def calculateGravity(pointList): # 重心坐标 gravity = Point() p1 = pointList[0] p2 = pointList[1] x1 = p1.x y1 = p1.y sum_x = 0 sum_y = 0 sum_area = 0 for i in range(2, len(pointList)): x2 = p2.x y2 = p2.y p3 = pointList[i] x3 = p3.x y3 = p3.y area = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0 sum_x += (x1 + x2 + x3) * area sum_y += (y1 + y2 + y3) * area sum_area += area p2 = p3 gravity.x = sum_x / sum_area / 3.0 gravity.y = sum_y / sum_area / 3.0 return gravity
def houseSitting(self, force, resources): self.check(force) resources.sort(key=lambda x: x[0].point.dist(force.point)) if not force.goal and resources: for r in resources: if len(r[0].mother) < 3: r[0].mother.append(force) force.goal.append(r[0].point) break else: resources.remove(r) d = "" if force.goal: d = force.goToPoint(force.goal[0]) if not d: p, strength = self.brain.aStage.enemies.strongest( force.point, Range[force.forceType]) if strength > GATEKEEP_STRENGTH: d = force.goToPoint(p) if not d: d = force.goToPoint( Point(force.cid % 2 * (MAPSIZE - 1), (1 - force.cid % 2) * (MAPSIZE - 1))) return d
def post(self): pointJson = json.loads(self.request.body) point = Point(pointJson['mapId'], pointJson) point = pointService.save(point) if 'name' in pointJson: loc = Loc(pointJson['mapId'], pointJson['name'], pointJson) locService.save(loc) self.write({'code': 0, 'data': point.toJsonMap()})
def findById(self, id: str, mid: str) -> Point: col = self.getColl(mid) result = col.find_one({'_id': ObjectId(id)}) if result is not None: point = Point(mid, result) point.id = id return point return None
def castlePoint(self, character): castle = self.enemies.unit[UnitType.CASTLE.value] if castle: p = min([ p for p in [Point(-1, -1), Point(1, -1), Point(0, -2), Point(-2, 0)] ], key=lambda x: castle[0].point.dist(p)) character.goal = [castle[0].point.plus(Point(-1, -1))] character.isFix = True return if character.goal and character.goal[0] == character.point: strongestPoint, strength = self.enemies.strongest( character.point, 5) character.goal.append(strongestPoint) character.goal.pop(0) if not character.goal: character.goal.append( Point(MAPSIZE - 5 - (self.turnNum % 6) * 5, MAPSIZE - 1)) character.goal.append( Point(MAPSIZE - 5 - (self.turnNum % 6) * 5, MAPSIZE - 45))
def findAll(self, mid: str) -> typing.List[Point]: col = self.getColl(mid) cursor = col.find() result = [] for item in cursor: p = Point(item['mapId'], item) p.id = str(item['_id']) result.append(p) return result
def damageTable(self): table = collections.defaultdict(int) for unit in self.units.values(): r = AttackRange[unit.type.value] # 気合入れれば半分にできる for x in xrange(-r, r + 1): for y in xrange(-r, r + 1): if 0 <= unit.point.x + x < MAPSIZE and 0 <= unit.point.y + y < MAPSIZE and abs(x) + abs(y) <= r: table[unit.point.plus(Point(x, y))] += Strength[unit.type.value] return table
def searchPoints(self): if self.searchPoints: return self.searchPoints() searchPoints = [] for i in xrange(MAPSIZE / self.GRID): for j in xrange(MAPSIZE / self.GRID): if self.field[i][j] == 0: searchPoints.append(Point(i * MAPSIZE, j * MAPSIZE)) self._searchPoints = searchPoints return searchPoints
def getPoints(filename): global sidePoints with open(filename) as f: reader = csv.reader(f) for row in reader: try: sidePoints.append(Point(float(row[0]), float(row[1]))) except ValueError: continue sidePoints = simplified(sidePoints)
def cast_point(value, cur): if value is None: return None # Convert from (f1, f2) syntax using a regular expression. m = re.match(r"\(([^)]+),([^)]+)\)", value) if m: return Point(float(m.group(1)), float(m.group(2))) else: raise InterfaceError("bad point representation: %r" % value)
def buildBase(self, workers): if len(self.brain.unit(UnitType.BASE)) > 0: worker = min(workers, key=lambda x: x.point.dist(self.brain.castle.point)) else: zero = Point(60, 60) worker = min(workers, key=lambda x: x.point.dist(zero)) self.brain.actions[worker.cid] = UnitType.BASE.value self.brain.aStage.resourceNum -= Cost[UnitType.BASE] workers.remove(worker)
class Line(object): # id oid = "" # 起止点 startPoint = Point() endPoint = Point() # 长度 length = 0 # 顶点序列 pointList = [] # type: list[Point] def getLength(self): if self.length == 0: p1 = self.pointList[0] for i in range(2, len(self.pointList)): p2 = self.pointList[i] self.length += mu.pointDistance(p1, p2) p1 = p2 return self.length