def test_copy_point(self): p1 = Point2D(2, 0) p2 = Point2D(p1) self.assertEqual(p2._x, 2.0) self.assertEqual(p2._y, 0.0) self.assertEqual(p2._r, 2.0) self.assertEqual(p2._a, 0.0)
def draw(self): # draw filled box egi.set_pen_color(self.color) egi.closed_shape(self._pts, filled=True) # draw box border if cfg['BOXLINES_ON']: egi.set_pen_color((.7, .7, .7, 1)) egi.closed_shape(self._pts, filled=False) if self.kind == 'I': egi.set_stroke(1) egi.set_pen_color(name="RED") egi.line(self._pts[0].x + 10, self._pts[0].y - 5, self._pts[0].x + 10, self._pts[0].y - 16) egi.line(self._pts[0].x + 5, self._pts[0].y - 11, self._pts[0].x + 16, self._pts[0].y - 11) if self.kind == 'P': obj_pts = ( Point2D(self._pts[0].x + 5, self._pts[0].y - 5), # top left Point2D(self._pts[0].x + 15, self._pts[0].y - 4), # top right Point2D(self._pts[0].x + 15, self._pts[0].y - 15), # bottom right Point2D(self._pts[0].x + 5, self._pts[0].y - 15) # bottom left ) egi.set_stroke(1) egi.set_pen_color(name="RED") egi.closed_shape(obj_pts, filled=False) # centre circle if cfg['CENTER_ON']: egi.set_pen_color((.3, .3, 1, 1)) egi.circle(self._vc, 5) # box position (simple column,row) (or x,y actually) if self.node: if cfg['LABELS_ON']: if not self.idx_label: info = "%d" % self.idx self.idx_label = pyglet.text.Label(info, color=(0, 0, 0, 255), anchor_x="center", anchor_y="top") info = "(%d,%d)" % (self.pos[0], self.pos[1]) self.pos_label = pyglet.text.Label(info, color=(0, 0, 0, 255), anchor_x="center", anchor_y="bottom") self._reposition_labels() self.idx_label.draw() #self.pos_label.draw() if self.marker: if not self.marker_label or self.marker_label.text != self.marker: self.marker_label = pyglet.text.Label(self.marker, color=(255, 0, 0, 255), bold=True, anchor_x="center", anchor_y="center") self._reposition_labels() self.marker_label.draw()
def agent_shoot(self): if self.projectile: if ((self.proj_vel_x) or (self.proj_vel_y)): if ((self.projectile.x >= self.proj_target.x - 2) and (self.projectile.x <= self.proj_target.x + 2) and (self.projectile.y >= self.proj_target.y - 2) and (self.projectile.y <= self.proj_target.y + 2)): self.proj_vel_x = False self.proj_vel_y = False self.projectile = False self.proj_target = False self.world.enemy.health -= 1 if ((self.world.enemy.health <= 0) or (self.clip <= 0)): self.ll_state = "Reload" else: self.projectile.x += self.proj_vel_x / 3 self.projectile.y += self.proj_vel_y / 3 else: self.proj_vel_x = self.proj_target.x - self.projectile.x self.proj_vel_y = self.proj_target.y - self.projectile.y else: print("Firing...") self.projectile = Point2D(self.world.agent.my_x, self.world.agent.my_y) self.proj_target = Point2D(self.world.enemy.my_x, self.world.enemy.my_y) self.clip -= 1
def original_point(self): coordinate_system_origin = self.coordinate_system_.origin() if (self.coordinate_system_.position() == Position.CENTER): return Point2D(self.x() + coordinate_system_origin.x(), self.y() + coordinate_system_origin.y()) elif (self.coordinate_system_.position() == Position.TOPLEFT): return Point2D(self.x() + coordinate_system_origin.x(), (-self.y()) + coordinate_system_origin.y())
def test_add(self): p1 = Point2D(1, 0) p2 = Point2D(0, 1) p = p1 + p2 self.assertEqual(p.x, 1.0) self.assertEqual(p.y, 1.0) p = p2 + p1 self.assertEqual(p.x, 1.0) self.assertEqual(p.y, 1.0)
def test_sub(self): p1 = Point2D(1, 0) p2 = Point2D(0, 1) p = p1 - p2 self.assertEqual(p.x, 1.0) self.assertEqual(p.y, -1.0) p = p2 - p1 self.assertEqual(p.x, -1.0) self.assertEqual(p.y, 1.0)
def test_isub(self): p1 = Point2D(1, 0) p2 = Point2D(0, 1) p1 -= p2 self.assertEqual(p1.x, 1.0) self.assertEqual(p1.y, -1.0) p1 = Point2D(1, 0) p2 -= p1 self.assertEqual(p2.x, -1.0) self.assertEqual(p2.y, 1.0)
def test_iadd(self): p1 = Point2D(1, 0) p2 = Point2D(0, 1) p1 += p2 self.assertEqual(p1.x, 1.0) self.assertEqual(p1.y, 1.0) p1 = Point2D(1, 0) p2 += p1 self.assertEqual(p2.x, 1.0) self.assertEqual(p2.y, 1.0)
def __init__(self): self.ez = Ezgame(APPW, APPH) self.ez.origin = Point2D(APPW/2.0, APPH*0.90) self.ez.fps = FPS self.ez.init(self.loop) self.size = 1 p = Point2D(0, 0) p.a = math.radians(90) self.tree = Tree(p, self.size, LEVELS) self.angle = math.radians(1)
def run_example(): """Run some example functionality.""" # hold Point2D points to traverse through points = [] # add points in a square points.append(Point2D(0, 0)) points.append(Point2D(10, 0)) points.append(Point2D(10, 10)) points.append(Point2D(0, 10)) points.append(Point2D(0, 9)) # plan the route segments = plan_route(points)
def __init__(self): # list of labels self.labels = [] # list of keeputs self.keepouts = [] # for now, just create some labels and keepouts self.labels.append(Label(Point2D(1.0, 0.0), 3, 1, 'one')) self.labels.append(Label(Point2D(2.0, 0.6), 3, 1, 'two')) self.labels.append(Label(Point2D(1.5, 1.0), 5, 1, 'three')) self.labels.append(Label(Point2D(-1, -1.0), 2, 2, 'four')) # add a keeopouts self.keepouts.append(Label(Point2D(-0.2, 0.5), 0.6, 0.6))
def check_for_collision(self): rightmost_point = Point2D(self.pos.x + self.radius, self.pos.y) leftmost_point = Point2D(self.pos.x - self.radius, self.pos.y) hit = False if self.world.target.point_inside(rightmost_point): hit = True elif self.world.target.point_inside(leftmost_point): hit = True if hit: self.world.bullet = None self.world.target.hit()
def reposition(self, coords): # top, right, bottom, left pts = self.coords = coords # points for drawing self._pts = ( Point2D(pts[3], pts[0]), # top left Point2D(pts[1], pts[0]), # top right Point2D(pts[1], pts[2]), # bottom right Point2D(pts[3], pts[2]) # bottom left ) # vector-centre point self._vc = Point2D((pts[1] + pts[3]) / 2.0, (pts[0] + pts[2]) / 2.0) # labels may need to be updated self._reposition_labels()
def voronoi(me, neigh, r): """ Return a Polygon with the Voronoi cell <r with the neigh around me, neigh is a list of (x,y) """ W = Point(me).buffer(r) pm = Point2D(me) for n in neigh: pn = Point2D(n) v = pn - pm pc = pm + 0.5 * v v.r = r q0 = pm + 2 * v v.a += np.pi / 2 q1 = pc + 2 * v q2 = pc - 2 * v W -= Polygon([(q0.x, q0.y), (q1.x, q1.y), (q2.x, q2.y)]) return W
def target(self, target): ''' move towards target position ''' target_offset = self.pos - target.pos target_distance = PointToVector2D(target_offset).length() target_direction = PointToVector2D(target_offset).normalise() relative_velocity = target_direction * self.speed relative_speed = relative_velocity.dot(target_direction) if (relative_speed <= 0.0): intercept_time = 1.0 else: intercept_time = target_distance / relative_speed intercept_location = target.pos + target.vel * intercept_time intercept_point = intercept_location - self.pos if self.miss(): print("miss") intercept_point += Point2D(100,100) aim = PointToVector2D(intercept_point).normalise() vel = aim * self.speed return vel
def draw(clusters: Dict[int, List[Point2D]], green_points: Set[Point2D], yellow_points: Set[Point2D], red_points: Set[Point2D], min_x: int, max_x: int, min_y: int, max_y: int): figure, axis = plot.subplots() axis.set_xlim([min_x, max_x]) axis.set_ylim([min_y, max_y]) colors = plot.rcParams["axes.prop_cycle"].by_key()["color"] for i, (cluster_id, points) in enumerate(clusters.items()): cluster_color = colors[i % len(colors)] cluster_center = Point2D( numpy.mean(numpy.array([point.x for point in points])), numpy.mean(numpy.array([point.y for point in points]))) cluster_radius = numpy.max([(point - cluster_center).r for point in points]) cluster = plot.Circle((cluster_center.x, cluster_center.y), cluster_radius, color=cluster_color, fill=False) axis.add_artist(cluster) def draw_points(points: Set[Point2D], color: str): axis.scatter([point.x for point in points], [point.y for point in points], color=color) draw_points(green_points, "g") draw_points(yellow_points, "y") draw_points(red_points, "r") plot.show()
def __init__(self, x, y, boxes): self.pos = Point2D(x, y) self.path = [] self.radius = 10 self.speed = 1 self.boxes = boxes self.end = False
def get_random_points(count: int) -> List[Point2D]: points = list() for _ in range(0, count): x = random.uniform(min_x, max_x) y = random.uniform(min_y, max_y) points.append(Point2D(x, y)) return points
def __init__(self, angular_vel, distance): self.angular_vel = angular_vel self.distance = distance self.x_pos = distance self.y_pos = 0.0 self.position = Point2D(self.x_pos, self.y_pos) self.theta = 0.0
def draw(existing_points: Dict[int, List[Point2D]], classified_new_points: Dict[int, List[Point2D]], min_x: int, max_x: int, min_y: int, max_y: int): figure, axis = plot.subplots() axis.set_xlim([min_x, max_x]) axis.set_ylim([min_y, max_y]) colors = plot.rcParams["axes.prop_cycle"].by_key()["color"] for i, cluster in enumerate(existing_points.keys()): color = colors[i % len(colors)] points = existing_points[cluster] + classified_new_points.get( cluster, []) axis.scatter([point.x for point in points], [point.y for point in points], color=color) cluster_center = Point2D( numpy.mean(numpy.array([point.x for point in points])), numpy.mean(numpy.array([point.y for point in points]))) cluster_radius = numpy.max([(point - cluster_center).r for point in points]) circle = plot.Circle((cluster_center.x, cluster_center.y), cluster_radius, color=color, fill=False) axis.add_artist(circle) plot.show()
def scale(self, scalar): new_x = self.x_ * scalar new_y = self.y_ * scalar return Vector2D(Point2D(new_x, new_y), self.coordinate_system(), transpose=False)
def get_training_points(clusters_count: int, points_count_in_cluster: int, min_x: int, max_x: int, min_y: int, max_y: int) -> Dict[int, List[Point2D]]: data = dict((i, []) for i in range(clusters_count)) for cluster in range(clusters_count): cluster_center = Point2D(random.uniform(min_x, max_x), random.uniform(min_y, max_y)) x_radius = (max_x - min_x) / clusters_count / 3 y_radius = (max_y - min_y) / clusters_count / 3 data[cluster] = [ Point2D(random.gauss(cluster_center.x, x_radius), random.gauss(cluster_center.y, y_radius)) for _ in range(points_count_in_cluster) ] return data
def getpoint(self, index): input_point = Point2D() path = "C:\\Users\\tjrgk\\Documents\\GitHub\\2D\\" dirs = os.listdir(path) if 'point' in dirs: path = os.chdir(path + "\\point") dirs = os.listdir(path) for filename in dirs: if filename.endswith(".txt"): print( "==================================================================" ) print( "==================================================================" ) f = open(filename, 'r') files = f.readlines() file_input_point = [file.strip() for file in files] point_list = [] for i in range(len(files)): if ',' in file_input_point[i]: file_input_point[i] = file_input_point[i].split(',') input_point.xcoord = float(file_input_point[i][0]) input_point.ycoord = float(file_input_point[i][1]) point_list.extend( [input_point.xcoord, input_point.ycoord]) n = 2 result = [ point_list[i * n:(i + 1) * n] for i in range((len(point_list) + n - 1) // n) ] input_point = tuple(result[index]) return input_point
def update(self): super().update() if self.where != None: arrow = Point2D(self.where.x - self.body.pos.x, self.where.y - self.body.pos.y) self.vertices = [(self.body.pos.x, self.body.pos.y), (self.where.x, self.where.y)] if arrow.r < self.tol: self.where = None else: if self.when > self.time: v = arrow.r / (self.when - self.time) else: v = np.Infinity w = self.Kp * ((pipi(arrow.a - self.body.th))) self.body.cmd_vel(v, w) else: self.vertices = None if self.nw == 'stop': # reset v and w self.body.cmd_vel(v=0, w=0) elif self.nw == 'wander': # random changes of w if uniform(0, 1) < self.p: self.body.cmd_vel(w=choice(('+', '-', '='))) elif self.nw == 'zigzag': # random changes of direction if uniform(0, 1) < self.p: self.body.teleport( th=self.body.th + uniform(-1, 1) * self.body.w_max * self.T) elif self.nw == 'keepgoing': # keep v and w pass
def get_initial_clusters(points: List[Point2D], clusters_count: int) -> List[Point2D]: circle_center = get_mean_point(points) circle_radius = numpy.max([(point - circle_center).r for point in points]) angle_step = pi * 2 / clusters_count return list( circle_center + Point2D(r = circle_radius, a = angle_step * i) for i in range(0, clusters_count))
def check_for_collision(self): rightmost_point = Point2D(self.pos.x + self.radius,self.pos.y) if rightmost_point: if self.world.target.point_inside(rightmost_point): print('hit') self.world.bullet = None self.world.target.hit()
def __init__(self, x, y, theta, position): self.position_ = position self.origin_ = Point2D(x, y) self.theta_ = theta self.rotation_ = Rotation(theta, AngleUnit.RADIANS)
def __add__(self, other): if (self.coordinate_system_ != other): raise Exception( "Adding two vectors with different coordinate systems") return None addition_point = Point2D(self.x() + other.x(), self.y() + other.y()) return Vector2D(addition_point, self.coordinate_system())
def __sub__(self, other): if (self.coordinate_system_ != other): raise Exception( "Subtracting two vectors with different coordinate systems") return None subtraction_point = Point2D(self.x() - other.x(), self.y() - other.y()) return Vector2D(subtraction_point, self.coordinate_system())
def on_draw(self): self.clear() if self.agent: self.world.draw(Point2D(self.agent.my_x, self.agent.my_y)) else: self.world.draw(False) if self.fps_display: self.fps_display.draw() for key, label in list(self.labels.items()): label.draw()