コード例 #1
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()
コード例 #2
0
ファイル: fsm.py プロジェクト: strollcata/games-ai-spike-14
 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
コード例 #3
0
ファイル: test_point2d.py プロジェクト: SplinterDev/point2d
 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)
コード例 #4
0
 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())
コード例 #5
0
ファイル: test_point2d.py プロジェクト: SplinterDev/point2d
 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)
コード例 #6
0
ファイル: test_point2d.py プロジェクト: SplinterDev/point2d
 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)
コード例 #7
0
ファイル: test_point2d.py プロジェクト: SplinterDev/point2d
 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)
コード例 #8
0
ファイル: test_point2d.py プロジェクト: SplinterDev/point2d
 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)
コード例 #9
0
ファイル: example.py プロジェクト: SplinterFM/ezgame
    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)
コード例 #10
0
ファイル: motion_planner.py プロジェクト: timkostka/cert3d
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)
コード例 #11
0
ファイル: palp.py プロジェクト: timkostka/palp
 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))
コード例 #12
0
    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()
コード例 #13
0
 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()
コード例 #14
0
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
コード例 #15
0
ファイル: main.py プロジェクト: DrunkRussianGun/DA_ML
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
コード例 #16
0
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()
コード例 #17
0
ファイル: small_worl2d.py プロジェクト: davdmc/MRS
 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
コード例 #18
0
    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)
コード例 #19
0
ファイル: parallel_kmeans.py プロジェクト: aakashsa/15-440
def slave_function():
	'''
	Slave functionality K_means code
	'''
	# Get communication instance
	comm = MPI.COMM_WORLD

	# Get k
	k = comm.recv(source = 0)

	# Get Data Points	
	data_points = comm.recv(source = 0)

	# New Centroid List
	new_centroids =  [ [] for i in range(k) ]
	# Population List have size of each cluster
	population_slave = [ [] for i in range(k) ]
	centroids = []
	while (True):
		# Receive centroids from master
		centroids = comm.bcast(centroids,root=0) 
		
		# check if done signal is received
		if len(centroids) == 0:
			return 
		# Assign points to clusters (2D list of points)
		assigned_points = utils.assign_cluster(data_points, centroids, k)
		for i in range (0, k):
			# new_centroids: list of points
			new_centroids[i] = Point2D.getAverage(assigned_points[i])
			# population_slave: list of numbers; i-th number is no. of points in cluster i
			population_slave[i] =  len(assigned_points[i])
		# Send the new centroids and the population count of each cluster	
	   	comm.send((new_centroids, population_slave), dest=0)
コード例 #20
0
ファイル: filereader.py プロジェクト: hongseokhan/2D
 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
コード例 #21
0
ファイル: sequential_kmeans.py プロジェクト: aakashsa/15-440
def k_means (points, k, centroids):
	'''
	Actual K Means code 
	'''	
	iteration = 0
	while (True):
		new_centroids = []
		# Assign data points to clusters
		cluster_lists = utils.assign_cluster(points, centroids, k)

		# compute new centroids as average of points in each cluster
		for list_item in cluster_lists:
			new_centroids.append(Point2D.getAverage(list_item))

		# Check for convergence
		if (set(centroids) == set(new_centroids)):
			iteration += 1
			print "Took " + str(iteration) + " iteration(s)"
			return centroids

		# Iterate again if not convered
		centroids = copy.deepcopy(new_centroids)
		iteration += 1
	print "Took " + str(iteration) + " iteration(s)"
	return centroids
コード例 #22
0
ファイル: main.py プロジェクト: DrunkRussianGun/DA_ML
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()
コード例 #23
0
ファイル: entry_point.py プロジェクト: DrunkRussianGun/DA_ML
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
コード例 #24
0
    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
コード例 #25
0
 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
コード例 #26
0
 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
コード例 #27
0
ファイル: entry_point.py プロジェクト: DrunkRussianGun/DA_ML
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))
コード例 #28
0
    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()
コード例 #29
0
    def __init__(self, x, y, theta, position):
        self.position_ = position

        self.origin_ = Point2D(x, y)
    
        self.theta_ = theta

        self.rotation_ = Rotation(theta, AngleUnit.RADIANS)
コード例 #30
0
    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())
コード例 #31
0
    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())
コード例 #32
0
ファイル: main.py プロジェクト: strollcata/games-ai-spike-12
 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()
コード例 #33
0
ファイル: sequential_kmeans.py プロジェクト: aakashsa/15-440
	return centroids

if __name__ == "__main__":
	if (len(sys.argv) != 4):
		print "Usage: python sequential_kmeans.py <pointsFile> <k> <centroidsFile>"
		sys.exit(0)
	k = int(sys.argv[2])
	if (k <= 0):
		print "ERROR: k must be at least 1"
		sys.exit(0)

	# Get data points
	points = utils.read_2D_points(sys.argv[1])

	if (k > len(points)):
		print "ERROR: k must be at most the number of data points"
		sys.exit(0)
	
	# Get centroids
	centroids = utils.read_2D_points(sys.argv[3])

	if (len(centroids) != k):
		print "ERROR: k must be equal to number of centroids"
		sys.exit(0)

	# Run sequential K means
	start_time = time.time()
	result = k_means(points, k, centroids)
	end_time = time.time()
	print "Final centroids = " + Point2D.stringify(result)
	print "Sequential Kmeans on 2D data set took " + str(end_time - start_time) + " second(s)"