def main(): house = Point(10, 9) print('House is at X:', house.x) print('House is at Y:', house.y) work = Point(5, 2) print('House to work distance:', house.distance_to(work)) city = Rectangle(Point(5, 5), 10, 10) print('City corner is:', city.bottom_left_corner) print('City width:', city.w) print('City height:', city.h) print('House in city:', city.contains(house)) print('Work in city:', city.contains(work)) city_center = city.find_center() print('City center:', city_center) cats_house = Point(10, 9) identical_city = Rectangle(Point(5, 5), 10, 10) different_city = Rectangle(Point(13, 13), 10, 10) print("My cat's house and mine are equal:", house == cats_house) print('Two identical cities are equal:', city == identical_city) print('Two different cities are equal:', city == different_city) house.move_by(1, -1) print('After moving my house:', house)
def paint(self, surface): surface.fill((0,0,0)) for k in self.rocks: k.paint(surface) k.bod.paint(surface) k.lwing.paint(surface) k.rwing.paint(surface) for r in self.space: if r.isActive(): r.colorz() r.paint(surface) locat = self.ship.getPoints() x,y = self.ship.position.pair() imgp = Point(x - 50, y - 50) for f in self.rocks: rx,ry = f.position.pair() impF = Point(rx - 50, ry - 50) mx,my = f.bod.position.pair() impm = Point(mx - 50, my - 50) lx,ly = f.lwing.position.pair() limpm = Point(lx - 50, ly - 50) tx,ty = f.rwing.position.pair() timpm = Point(tx - 50, ty - 50) if f.isActive(): surface.blit(f.curImage,(impF.pair())) if f.bod.isActive(): surface.blit(f.bod.curImage,(impm.pair())) if f.lwing.isActive(): surface.blit(f.lwing.curImage,(limpm.pair())) if f.rwing.isActive(): surface.blit(f.rwing.curImage,(timpm.pair())) if self.ship.isActive(): surface.blit(self.ship.curImage,(imgp.pair()))
def __contains__(self, o): """Is other GeometryEntity contained in this Ray?""" if isinstance(o, Ray): return (Point.is_collinear(self.p1, self.p2, o.p1, o.p2) and (self.xdirection == o.xdirection) and (self.ydirection == o.ydirection)) elif isinstance(o, Segment): return (o.p1 in self) and (o.p2 in self) elif isinstance(o, Point): if Point.is_collinear(self.p1, self.p2, o): if (not self.p1.x.free_symbols and not self.p1.y.free_symbols and not self.p2.x.free_symbols and not self.p2.y.free_symbols): if self.xdirection is S.Infinity: return o.x >= self.source.x elif self.xdirection is S.NegativeInfinity: return o.x <= self.source.x elif self.ydirection is S.Infinity: return o.y >= self.source.y return o.y <= self.source.y else: # There are symbols lying around, so assume that o # is contained in this ray (for now) return True else: # Points are not collinear, so the rays are not parallel # and hence it isimpossible for self to contain o return False # No other known entity can be contained in a Ray return False
def __contains__(self, o): """Return True if o is on this Ray, or False otherwise.""" if isinstance(o, Ray): d = o.p2 - o.p1 return Point.is_collinear(self.p1, self.p2, o.p1, o.p2) \ and (self.xdirection == o.xdirection) \ and (self.ydirection == o.ydirection) elif isinstance(o, Segment): return ((o.p1 in self) and (o.p2 in self)) elif isinstance(o, Point): if Point.is_collinear(self.p1, self.p2, o): if (not self.p1[0].atoms(C.Symbol)) and (not self.p1[1].atoms(C.Symbol)) \ and (not self.p2[0].atoms(C.Symbol)) and (not self.p2[1].atoms(C.Symbol)): if self.xdirection is S.Infinity: return o[0] >= self.source[0] elif self.xdirection is S.NegativeInfinity: return o[0] <= self.source[0] elif self.ydirection is S.Infinity: return o[1] >= self.source[1] return o[1] <= self.source[1] else: # There are symbols lying around, so assume that o # is contained in this ray (for now) return True else: # Points are not collinear, so the rays are not parallel # and hence it isimpossible for self to contain o return False # No other known entity can be contained in a Ray return False
def iterator(self): for i, outer in enumerate(self.outer.iterator()): inner_iterator = self.inner.iterator() alternate = False if self.snake and i % 2: alternate = True # Reverse the inner iterator as in place list inner_iterator = list(inner_iterator) inner_iterator.reverse() for inner in inner_iterator: point = Point() # Insert outer points point.positions.update(outer.positions) point.lower.update(outer.positions) point.upper.update(outer.positions) # Insert inner points point.positions.update(inner.positions) # alternate has lower and upper bound swapped if alternate: point.upper.update(inner.lower) point.lower.update(inner.upper) else: point.upper.update(inner.upper) point.lower.update(inner.lower) # Insert indexes point.indexes = outer.indexes + inner.indexes yield point
def track_holes(self, image): rospy.loginfo('Tracking Fish') t = image.header.stamp.to_time() image = self.bridge.imgmsg_to_cv2(image, "bgr8") img = self.crop_img(image) angle = self.get_angle(t-self.start_time) fishes = self.rotate(self.fish_locales, angle) fish_found = 0 for i in range(len(fishes)): if self.fish_holes[i].is_fish(): location = Point(*fishes[i]) if self.mouth_open(location): location = location + self.board_center cv2.circle(img,location.to_image(), 20,(0,255,0),2) fish_found += 1 else: location = location + self.board_center cv2.circle(img,location.to_image(), 20,(0,0,255),2) # rospy.loginfo('Fish At {}'.format(location)) # for cam in self.openings: # circle = cam + self.board_center # cv2.circle(img, circle.to_image(),3,(0,255,0),2) if __name__ == "__main__": self.pub_results.publish(self.bridge.cv2_to_imgmsg(img, "bgr8")) else: return img
def _update(self): secs = (datetime.now() - self.timestamp).total_seconds() # if we haven't seen a metronome() call in 2 seconds, revert to autoscan delta_beat = secs / (60.0/self.bpm) if self.count in (1, 3): self.pos = delta_beat else: self.pos = 1 - delta_beat if delta_beat > 1.05 or delta_beat < -0.05: delta_beat = np.clip(delta_beat, 0, 1) self.count = ((self.count) % 4) + 1 self.timestamp = datetime.now() for scanner in self.scanners: n1,n2 = scanner['n1'], scanner['n2'] r,g,b = scanner.get('color', (1,1,1)) point = Point(self.pos, n2 - n1, width=scanner.get('width', 2)) points = point.get_points() color_points = np.full((n2-n1)*3, fill_value=0, dtype=np.uint8) color_points[0::3] = r * points color_points[1::3] = g * points color_points[2::3] = b * points self.video_buffer.merge(n1, n2, color_points)
def __init__(self): self.screen = None self.color = Color() pygame.init() self.screen = pygame.display.set_mode(SIZE) pygame.display.set_caption("Test Cannon Shoot") pygame.key.set_repeat(1,10) self.header = pygame.font.SysFont("monospace", 36) self.point = pygame.font.SysFont('monospace', 18) self.center = Point() self.center.set(x=SIZE[0]/2, y=SIZE[1]/2) self.sec = Point() self.sec.set(x=SIZE[0]/2+15, y=SIZE[1]/2) self.clock = pygame.time.Clock() self.speed = 1 self.level = Level(BASE) self.player = Player(1, self.center) self.player.shoot_mode() self.level.add_cannon(250, 250, self.player, game=False) self.level.add_cannon(260, 250, self.player, game=False) for gun in self.player.guns: gun.unpaint() controls = { MOVE_UP: pygame.K_UP, MOVE_DOWN: pygame.K_DOWN, MOVE_RIGHT: pygame.K_RIGHT, MOVE_LEFT: pygame.K_LEFT, SHOOT: pygame.K_w, LAY_PIECE: pygame.K_w, ROTATE_RIGHT: pygame.K_d, ROTATE_LEFT: pygame.K_a } self.player.set_controls(controls)
def puzzle12(): lights_on = dict() f.seek(0) for line in f: parts = line.split() if parts[0] == 'toggle': start = get_point_from_text(parts[1]) end = get_point_from_text(parts[3]) points = Point.create_rectangle_of_points(start, end) difference = 2 elif parts[0] + parts[1] == 'turnon': start = get_point_from_text(parts[2]) end = get_point_from_text(parts[4]) points = Point.create_rectangle_of_points(start, end) difference = 1 elif parts[0] + parts[1] == 'turnoff': start = get_point_from_text(parts[2]) end = get_point_from_text(parts[4]) points = Point.create_rectangle_of_points(start, end) difference = -1 for point in points: try: lights_on[point] += difference except KeyError: lights_on[point] = difference if lights_on[point] < 0: lights_on[point] = 0 return sum(lights_on.values())
def test_add_point(self): p1 = Point(1.2, 2.3) p2 = Point(2.1, 3.2) self.assertEqual(p1 + p2, Point(3.3,5.5)) p1 += Point(2,3) self.assertTrue(p1.isNear(Point(3.2,5.3)))
def test_sub_point(self): p1 = Point(1.2, 2.3) p2 = Point(2.1, 3.2) self.assertTrue((p2 - p1).isNear(Point(0.9,0.9))) p1 -= Point(0.2,0.3) self.assertTrue(p1.isNear(Point(1,2)))
def contains(self, o): """Is other GeometryEntity contained in this Ray?""" if isinstance(o, Ray): return (Point.is_collinear(self.p1, self.p2, o.p1, o.p2) and self.xdirection == o.xdirection and self.ydirection == o.ydirection) elif isinstance(o, Segment): return o.p1 in self and o.p2 in self elif isinstance(o, Point): if Point.is_collinear(self.p1, self.p2, o): if self.xdirection is S.Infinity: rv = o.x >= self.source.x elif self.xdirection is S.NegativeInfinity: rv = o.x <= self.source.x elif self.ydirection is S.Infinity: rv = o.y >= self.source.y else: rv = o.y <= self.source.y if isinstance(rv, bool): return rv raise Undecidable( 'Cannot determine if %s is in %s' % (o, self)) else: # Points are not collinear, so the rays are not parallel # and hence it is impossible for self to contain o return False # No other known entity can be contained in a Ray return False
def __init__(self, space, detection_radius): self.space = space self.detection_radius = detection_radius horizontal_detection_radius_multiplier = 1 vertical_detection_radius_multiplier = 1 print("GRID INITIALISED") bottom_left = space.bottom_left top_right = space.top_right top_left = Point(bottom_left) top_left.latitude = top_right.latitude bottom_right = Point(bottom_left) bottom_right.longitude = top_right.longitude self.origin = Point(bottom_left) self.origin.altitude = 85 map_height = bottom_left.distance_to(top_left) map_width = bottom_left.distance_to(bottom_right) pre_sector_height = detection_radius * vertical_detection_radius_multiplier pre_sector_width = detection_radius * horizontal_detection_radius_multiplier self.y_count = int(map_height / pre_sector_height) + 1 self.x_count = int(map_width / pre_sector_width) + 1 self.sector_height = map_height / self.y_count self.sector_width = map_width / self.x_count self.sector_state = {(i, j): [SectorState.notSearched, None] for i, j in itertools.product(range(self.x_count), range(self.y_count))}
def include(self, p): """ Expand the rectangle if needed to include a point. """ x0 = self._p0.x() y0 = self._p0.y() x1 = self._p1.x() y1 = self._p1.y() xspan = self.xSpan() yspan = self.ySpan() if x0 == 0 and y0 == 0 and x1 == 0 and y1 == 0: x0 = p.x() y0 = p.y() x1 = x0 y1 = y0 else: if xspan == 0: if p.x() < x0: x0 = p.x() if p.x() > x1: x1 = p.x() elif (p.x() - x0) / self.xSpan() < 0: x0 = p.x() elif (p.x() - x1) / self.xSpan() > 0: x1 = p.x(); if yspan == 0: if p.y() < y0: y0 = p.y() if p.y() > y1: y1 = p.y() elif (p.y() - y0) / self.ySpan() < 0: y0 = p.y() elif (p.y() - y1) / self.ySpan() > 0: y1 = p.y() self._p0 = Point(x0,y0) self._p1 = Point(x1,y1)
def to_absolute(self, point): #bbox = self.main_bbox #scale = 1000 * (707.0-209) / (bbox[2] - bbox[0] * 1.0) relative_to_box = Point(int(round(point.x / self.scale)), int(round(point.y / self.scale))) absolute = relative_to_box.plus(self.rel_point) return absolute
def _as_point(data): result = Point(data[tags.x_pos], data[tags.y_pos]) if tags.label in data: result.label = data[tags.label] if tags.color in data: result.color = _as_color(data[tags.color]) return result
def test_sub_number(self): p1 = Point(1.2, 2.3) p2 = p1 - 1.1 self.assertTrue(p2.isNear( Point(0.1,1.2)) ) self.assertTrue((p1 - 1.1).isNear( Point(0.1,1.2) )) p1 -= 1.1 self.assertTrue(p1.isNear( Point(0.1,1.2) ) )
def yFlip(self): """ Flip the rect vertically """ x0 = self._p0.x() y0 = self._p0.y() x1 = self._p1.x() y1 = self._p1.y() self._p0 = Point(x0,y1) self._p1 = Point(x1,y0)
def __init__(self, polar_coords, atom, size): ''' Surface object constructor ''' Point.__init__(self, None) self.radius, self.theta, self.phi = polar_coords self.atom = atom self.size = size
def _rotate(self, old): # 'old' coordinates are relative to the center of rotation # 'new' coordinates are absolute new = Point() new.x = self.center_of_rotation.x + (old.x * cos(self._angle_radians)) - (old.y * sin(self._angle_radians)) new.y = self.center_of_rotation.y + (old.x * sin(self._angle_radians)) + (old.y * cos(self._angle_radians)) old.x = new.x old.y = new.y
def __init__(self, gnWikipediaResult): lat = gnWikipediaResult['lat'] lon = gnWikipediaResult['lng'] # for storage, we remember both name and summary in the message variable message = "%s\n%s" % (gnWikipediaResult['title'],gnWikipediaResult['summary']) Point.__init__(self, lat, lon, gnWikipediaResult.get('elevation', None), message) self.abstract="%s..." % gnWikipediaResult['summary'][0:50] # chop a part of the summary self.result = gnWikipediaResult
def xFlip(self): """ Flip the rect horizontally """ x0 = self._p0.x() y0 = self._p0.y() x1 = self._p1.x() y1 = self._p1.y() self._p0 = Point(x1,y0) self._p1 = Point(x0,y1)
def iterator(self): for i in xrange(self.num): point = Point() point.positions[self.name] = self._calc(i) point.lower[self.name] = self._calc(i - 0.5) point.upper[self.name] = self._calc(i + 0.5) point.indexes = [i] yield point
def __init__(self, dim=2, num_points=10, upper_limit=10, lower_limit=-10): self.points = [] self.num_points = num_points for ix in xrange(num_points): new_point = Point(dim=dim, upper_limit=upper_limit, lower_limit=lower_limit) new_point.generate_random_point() self.points.append(copy.deepcopy(new_point))
class lines(): def __init__(self,seedListSize,max_y_value,numberOfItterations,roughnessConstant): #declare local varibles self.head self.seedListSize = seedListSize self.max_y_value = max_y_value self.numberOfItterations = numberOfItterations self.roughnessConstant = self.roughnessConstant #define mountain range head = randomLinkedList() createMountains() ''' create a randomLinkedList of Point as seeds ''' def __randomLinkedList__(): self.head = Point() self.head.set_y_val(random.random()*self.max_y_value) temp = self.head while numberOfNodes > 0: temp.setNext(Point()) temp = temp.getNext() temp.set_y_val(random.random()*rangeOf_y) numberOfNodes -= 1 return ''' create a procedual mountains ''' def __createMountains__(self,node, numberOfRuns,roughConstant): i = 1 while i <= numberOfRuns: self.addNodes(node,i,roughConstant) i += 1 return ''' for every other node this will add nodes inbetween the average will be part of the calculation for the node + a random amount multipled by a roughConstant ''' def __addNodes__(node,run,roughConstant): while node.getNext() is not None: newNode = Point() averageRandom = (node.get_y_val() + node.getNext().get_y_val())/2 + 200 *random.random() * roughConstant * math.pow(2,-run*roughConstant) newNode.set_y_val(averageRandom) newNode.setNext(node.getNext()) node.setNext(newNode) node = newNode.getNext() return ''' print the linked list into an array formmated string ''' def printNodes(node): a = "[" while node is not None: a = a + str(node.get_y_val()) + " " node = node.getNext() a = a + "]" return a
def test_apply(self): p = Point([0, 0]) m = Matrix().translate(x=12, y=-5) p2 = p.apply_transform(m) m = Matrix().rotate_ccw(radians=math.pi) p3 = p2.apply_transform(m) self.compareVector(p3.vec, [-12, 5, 1])
def add(self, name, x, y, h, k): if not name in self: # print "New "+self.name+" Point: "+ str(name) self[name] = Point(x, y, h, k, name) elif name in self: print "point: '" + str(name) + "' already exists... Calculating mean" self[name].x = (self[name].x + x) / 2 self[name].y = (self[name].y + y) / 2 self[name].h = (self[name].h + h) / 2
def load_calibration(self): self.center_point = Point(*calibration_data.center_point) self.board_center = Point(*calibration_data.board_center) self.board_radius = calibration_data.board_radius self.fish = [Point(*a) for a in calibration_data.fish] self.cams = [Point(*c) for c in calibration_data.cams] self.base_cams = [Point(*c) for c in calibration_data.base_cams] self.skew_matrix = np.float32(calibration_data.skew_matrix) self.recalibrate = True
def test_add_number(self): p1 = Point(1.2, 2.3) p2 = p1 + 1.1 self.assertEqual(p2, Point(2.3,3.4)) self.assertEqual(p1 + 1.1, Point(2.3,3.4)) p1 += 2.2 # sum is not exact !? self.assertTrue(p1.isNear(Point(3.4,4.5)))
def __init__(self, img, n, parallel=True): self.N = n self._img = img BasePoint.set_borders(img.shape[1], img.shape[0]) # for some reason shape gives us y, then x self._points = [] self._triangulation = None self._randomize()
def test_scale(self): p1 = Point(1, 2, 3) p2 = p1 * 2 self.assertEqual((p2.x, p2.y, p2.z), (2, 4, 6)) p3 = 3 * p1 self.assertEqual((p3.x, p3.y, p3.z), (3, 6, 9))
# test try: from point import Point except ImportError as e: print(e) p1 = Point(10, 20) print(p1) p2 = Point() print(p2) p2.set_x(100) print(p2)
def test_iterable_point(self): point = Point(x=1, y=2, z=3) x, y, z = point self.assertEqual((x, y, z), (1, 2, 3))
class Player(object): def __init__(self, pitch, team='team1', angle=90): self.team=team self.pitch = pitch self.position = Point(random.randrange(350, 450), random.randrange(250, 350)) self.reward = 0 self.angle = angle self.n_actions = 9 self.action_space = [0,1,2,3,4,5,6,7,8] self.model_name=f"actor{self.team}.h5" self.gamma=0.95 self.alpha = 0.005 self.beta = 0.005 self.input_dims = 12 self.fc1_dims = 16 self.fc2_dims = 8 self.epsilon = 1 self.epsilon_dec = 0.9999991 self.epsilon_min = 0.05 self.batch_size = 16 self.model_file = 'ddqn.h5' self.replace_target = 1000 self.mem_size= 1_0000 self.memory = ReplayBuffer(self.mem_size, self.input_dims, self.n_actions, discrete=True) self.q_eval = build_dqn(self.alpha, self.n_actions, self.input_dims, 256, 256) self.q_target = build_dqn(self.alpha, self.n_actions, self.input_dims, 256, 256) if self.team =='team1': self.position = Point(random.randrange(350, 450), random.randrange(250, 350)) self.image = pygame.image.load("kit.png") else: self.x = Point(random.randrange(WIDTH/2+30, WIDTH-30), random.randrange(20, HEIGHT)) self.image = pygame.image.load("kit2.png") self.image = pygame.transform.scale(self.image, (PLAYER_SIZE, PLAYER_SIZE)) def return_rotation(self): return pygame.transform.rotate(self.image, self.angle) def reset_position(self): self.position = Point(random.randrange(350, 450), random.randrange(250, 350)) def move(self,speed=3): if self.position.x <self.pitch.lower_x_pitch: self.position.x = self.pitch.lower_x_pitch if self.position.x > self.pitch.upper_x_pitch: self.position.x = self.pitch.upper_x_pitch if self.position.y < self.pitch.lower_y_pitch: self.position.y = self.pitch.lower_y_pitch if self.position.y > self.pitch.upper_y_pitch: self.position.y =self.pitch.upper_y_pitch self.getNewPos(speed) def rotate(self, direction=1): self.angle = self.angle + 20*(direction*2-3) if self.angle>360: self.angle=0 if self.angle<0: self.angle=360 def getNewPos(self, speed): old_x, old_y = self.position.x, self.position.y angle = float(self.angle) delta_y = speed*2 * math.cos(math.radians(angle)) delta_x = speed*2 * math.sin(math.radians(angle)) self.position = Point(self.position.x - delta_x, self.position.y - delta_y) def kick_ball(self, ball, power=6): if self.position.distance_between_points(ball.position)<20 and ball.speed==0: ball.player=self ball.is_kicked=True ball.player_angle = self.angle + random.randint(-20,20) ball.speed=20 ball.angle = self.angle ball.power =power def return_observation(self,opponent, ball): # return np.array([self.position.x/WIDTH,self.position.y/HEIGHT, math.radians(self.angle)/math.pi, ball.position.x/WIDTH, ball.position.y/HEIGHT, self.position.distance_between_points(ball.position)/WIDTH, self.position.angle_between_points(ball.position)/2/math.pi]) return np.array([math.radians(self.angle)/math.pi, self.position.distance_between_points(ball.position)/WIDTH, self.position.angle_between_points(ball.position)/2/math.pi, self.position.x/WIDTH, ball.position.x/WIDTH, ball.position.y/HEIGHT, self.position.y/HEIGHT, opponent.position.x/WIDTH, opponent.position.y/HEIGHT, opponent.position.distance_between_points(ball.position)/WIDTH, opponent.position.distance_between_points(self.position)/WIDTH, self.position.angle_between_points(opponent.position)/2/math.pi]) def pass_ball(self): pass def shoot_ball(self): pass def remember(self, state, action, reward, new_state, done): self.memory.store_transition(state, action, reward, new_state, done) def choose_action(self, state, ball, goal1, goal2, opponent): ball.is_kicked = False state = state[np.newaxis, :] rand = np.random.random() if rand < self.epsilon: action = np.random.choice(self.action_space) else: actions = self.q_eval.predict(state) action = np.argmax(actions) if self.position.distance_between_points(ball.position)<20: self.kick_ball(ball,power=action) self.reward = 0.1 if goal1==True: if self.team=='team1': self.reward=-1 opponent.reward=1 else: self.reward= 1 opponent = -1 elif goal2==True: if self.team=='team1': self.reward=1 opponent.reward=-1 else: self.reward=-1 opponent.reward = 1 else: old_position = self.position.distance_between_points(ball.position) if action <3: self.rotate(direction=action) elif action <5: self.last_position = self.position self.move(speed=action) self.reward=(old_position-self.position.distance_between_points(ball.position))/WIDTH return action def learn(self): if self.memory.mem_cntr > self.batch_size: state, action, reward, new_state, done = \ self.memory.sample_buffer(self.batch_size) action_values = np.array(self.action_space, dtype=np.int8) action_indices = np.dot(action, action_values) q_next = self.q_target.predict(new_state) q_eval = self.q_eval.predict(new_state) q_pred = self.q_eval.predict(state) max_actions = np.argmax(q_eval, axis=1) q_target = q_pred batch_index = np.arange(self.batch_size, dtype=np.int32) q_target[batch_index, action_indices] = reward + \ self.gamma*q_next[batch_index, max_actions.astype(int)]*done _ = self.q_eval.fit(state, q_target, verbose=0) self.epsilon = self.epsilon*self.epsilon_dec if self.epsilon > \ self.epsilon_min else self.epsilon_min if self.memory.mem_cntr % self.replace_target == 0: self.update_network_parameters() def update_network_parameters(self): self.q_target.model.set_weights(self.q_eval.model.get_weights()) def save_model(self): self.q_eval.save(self.model_file) def load_model(self): self.q_eval = load_model(self.model_file) # if we are in evaluation mode we want to use the best weights for # q_target if self.epsilon == 0.0: self.update_network_parameters()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import pygame from circlebot import CircleBot from point import Point from color import Color pygame.init() k = 0.003 width = 500 height = 500 p = Point(20, 20) c = Color(0, 50, 255) m = Point(5, 3) b = Point(0.5, 0.5) circle_1 = CircleBot(20, p, c, m, b) p = Point(width - 20, height - 20) circle_2 = CircleBot(20, p, c, m, b) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('YAHOOOO') clock = pygame.time.Clock() while True: dt = clock.tick(50) / 1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
def test_constructor(): p1 = Point() Point.class_method() p2 = Point(10, 20) Point.class_method() p1.show() # p1 객체 삭제 del p1 Point.class_method() p2.show()
def all_points(): for i in range(1, BOARD_ROW_LENGTH+1): for j in range(1, BOARD_COL_LENGTH+1): yield Point(i, j)
def add_position(self, move): return Point(self.x, self.y) + move
def test_get_explode_area(self): level = Level('level1.txt') index = level.put_bomb_and_get_bomb_index() explode_area = level.get_explode_area(index) self.assertEqual({Point(2, 1), Point(1, 2), Point(1, 1)}, explode_area)
#!/usr/bin/env python3 import sys import hashlib from collections import namedtuple sys.path.append('..') from point import Point START = Point(0, 0) DEST = Point(3, 3) Door = namedtuple('Door', 'index name direction') State = namedtuple('State', 'path position') DOORS = ( Point(0, -1), Point(0, 1), Point(-1, 0), Point(1, 0), ) DOORS = tuple(Door(i, *x) for i, x in enumerate(zip('UDLR', DOORS))) UP, DOWN, LEFT, RIGHT = DOORS def get_hash(path): return hashlib.md5((PASSCODE + path).encode('ascii')).hexdigest()
break else: # the start is following the end along the wall for i in range(1, len(wall_sequence)): point = wall_sequence[-i - 1] moves.append(point) if self.universe[point.x, point.y] == str(original_pipe_id): break return original_pipe_id, moves # No pipe to process following the walls return -1, [] if __name__ == "__main__": setup_logging() size = 4 pipes = [ (Point(0, 0), Point(3, 1)), (Point(1, 1), Point(3, 0)), (Point(0, 3), Point(3, 2)), ] engine = WallFollowerEngine(size, pipes) while not engine.solved: for next_move in engine.next_moves(): logging.debug(next_move) logging.info(engine.display())
def tangent_lines(self, p): """Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ---------- p : Point Returns ------- tangent_lines : list with 1 or 2 Lines Raises ------ NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also -------- Point Line Examples -------- >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line(Point(3, 0), Point(3, -12))] >>> # This will plot an ellipse together with a tangent line. >>> from sympy import Point, Ellipse, Plot >>> e = Ellipse(Point(0,0), 3, 2) >>> t = e.tangent_lines(e.random_point()) # doctest: +SKIP >>> p = Plot() # doctest: +SKIP >>> p[0] = e # doctest: +SKIP >>> p[1] = t # doctest: +SKIP """ from sympy import solve if self.encloses_point(p): return [] if p in self: rise = (self.vradius**2) * (self.center[0] - p[0]) run = (self.hradius**2) * (p[1] - self.center[1]) p2 = Point(simplify(p[0] + run), simplify(p[1] + rise)) return [Line(p, p2)] else: if len(self.foci) == 2: f1, f2 = self.foci maj = self.hradius test = (2 * maj - Point.distance(f1, p) - Point.distance(f2, p)) else: test = self.radius - Point.distance(self.center, p) if test.is_number and test.is_positive: return [] # else p is outside the ellipse or we can't tell. In case of the # latter, the solutions returned will only be valid if # the point is not inside the ellipse; if it is, nan will result. x, y = Dummy('x'), Dummy('y') eq = self.equation(x, y) dydx = idiff(eq, y, x) slope = Line(p, Point(x, y)).slope tangent_points = solve( [w.as_numer_denom()[0] for w in [slope - dydx, eq]], [x, y]) # handle horizontal and vertical tangent lines if len(tangent_points) == 1: assert tangent_points[0][0] == p[0] or tangent_points[0][ 1] == p[1] return [ Line(p, Point(p[0] + 1, p[1])), Line(p, Point(p[0], p[1] + 1)) ] # others return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
def test_unbound_class_method(): p = Point() Point.set_x(p, 10) Point.set_y(p, 20) print(Point.get_x(p), Point.get_y(p))
def test_othermethod(): Point.class_method() Point.static_method()
def test_equality_and_inequality(self): p1 = Point(1, 2, 3) p2 = Point(1, 2, 4) p3 = Point(1, 2, 3) self.assertNotEqual(Point(1, 2, 3), Point(1, 2, 4)) self.assertEqual(Point(1, 2, 3), Point(1, 2, 3)) self.assertFalse(Point(1, 2, 3) != Point(1, 2, 3)) self.assertNotEqual(p1, p2) self.assertEqual(p1, p3) p3.x, p3.z = p3.z, p3.x self.assertNotEqual(p1, p3) self.assertTrue(p1 != p3) self.assertFalse(p1 == p3)
def is_barrier_at(self, x, y): """ Return true if barrier is at x,y.""" return Point(x, y) in self.get_barriers()
step.swipe(device) else: step.click(device) if 'location' in step.note and cancel_button.exists( device): cancel_button.click(device) time.sleep(1) def show_steps(self): self.steps.show_steps() class StepList(list): def show_steps(self): start_war_flag = 'start_war' for step in self: print(step) if start_war_flag in step.note: print("\nBattle") if __name__ == '__main__': import atx device = atx.connect('4200c49cf2faa381') point = Point('location4', 534, 122) cancel_button = Image( os.path.join(constant.BATTLE_COMMON_IMAGE_DIR, 'cancel_button')) point.click(device) if 'location' in point.note and cancel_button.exists(device): cancel_button.click(device)
def test_should_check_get_angle(): # given central_point = Point('P1245', 0, 0) end_point_0 = Point('P0', 1, 0) end_point_50 = Point('P50', 1, 1) end_point_100 = Point('P100', 0, 1) end_point_150 = Point('P150', -1, 1) end_point_200 = Point('P200', -1, 0) end_point_250 = Point('P250', -1, -1) end_point_300 = Point('P300', 0, -1) end_point_350 = Point('P350', 1, -1) # when # then assert central_point.get_angle(end_point_0, end_point_0) == 0 assert central_point.get_angle(end_point_0, end_point_50) == 50 assert central_point.get_angle(end_point_0, end_point_100) == 100 assert central_point.get_angle(end_point_0, end_point_150) == 150 assert central_point.get_angle(end_point_0, end_point_200) == 200 assert central_point.get_angle(end_point_0, end_point_250) == 250 assert central_point.get_angle(end_point_0, end_point_300) == 300 assert central_point.get_angle(end_point_0, end_point_350) == 350 assert central_point.get_angle(end_point_50, end_point_50) == 0 assert central_point.get_angle(end_point_50, end_point_100) == 50 assert central_point.get_angle(end_point_50, end_point_150) == 100 assert central_point.get_angle(end_point_50, end_point_200) == 150 assert central_point.get_angle(end_point_50, end_point_250) == 200 assert central_point.get_angle(end_point_50, end_point_300) == 250 assert central_point.get_angle(end_point_50, end_point_350) == 300 assert central_point.get_angle(end_point_50, end_point_0) == 350 assert central_point.get_angle(end_point_100, end_point_100) == 0 assert central_point.get_angle(end_point_100, end_point_150) == 50 assert central_point.get_angle(end_point_100, end_point_200) == 100 assert central_point.get_angle(end_point_100, end_point_250) == 150 assert central_point.get_angle(end_point_100, end_point_300) == 200 assert central_point.get_angle(end_point_100, end_point_350) == 250 assert central_point.get_angle(end_point_100, end_point_0) == 300 assert central_point.get_angle(end_point_100, end_point_50) == 350
def test_put_bomb_and_get_bomb_index(self): level = Level('level1.txt') index = level.put_bomb_and_get_bomb_index() self.assertEqual(Point(1, 1), level.Bombs[index].position) self.assertEqual(1, level.Bombs[index].power) self.assertTrue(level.Bombs[index].is_active)
def enpointen(moves_list): return [Point(**move) for move in moves_list]
def _strpos2pt(self, strpos): return Point(*self._strpos2xy(strpos))
from calc import Calc import csv clusters = {} #[[points in the cluster],Number of points in the cluster, Centroid of the cluster, Average of distances between points and centroid of the cluster] clustCount = 0 #Number of clusters found algoName = "" #Name of the clustering Algorithm flag = 0 #read the location from the csv input file and store each location as a Point(latit,longit) object f = open('input.txt', 'r') h= open('output','a') reader = csv.reader(f, delimiter=",") for line in reader: if flag is 1: if len(line) is 2: if clustCount in clusters: loc_ = Point(float(line[0]), float(line[1])) #tuples for location elemCount += 1 clusters[clustCount][0].append(loc_) clusters[clustCount][1] = elemCount else: loc_ = Point(float(line[0]), float(line[1])) #tuples for location clusters[clustCount] = [[loc_],elemCount,Point(0,0),0] else: clustCount += 1 print "Processing Cluster:" + str(clustCount) elemCount = 1 #Number of elements in the cluster else: algoName=line[0] flag = 1 print str(clustCount) + " Clusters found"
def __init__(self): self.position = Point(10, 10)
def __init__(self): self.chess_pieces = {Player.white: list(), Player.black: list()} self.focused_chess_piece = None self.operator = Player.black self.init_positions = { Player.white: { Rook: [Point(0, 0), Point(7, 0)], Knight: [Point(1, 0), Point(6, 0)], Bishop: [Point(2, 0), Point(5, 0)], Queen: [Point(3, 0)], King: [Point(4, 0)], Pawn: list(Point(x, 1) for x in range(8)) }, Player.black: { Rook: [Point(0, 7), Point(7, 7)], Knight: [Point(1, 7), Point(6, 7)], Bishop: [Point(2, 7), Point(5, 7)], Queen: [Point(3, 7)], King: [Point(4, 7)], Pawn: list(Point(x, 6) for x in range(8)) } } self.some_player_win = None
def reset_position(self): self.position = Point(random.randrange(350, 450), random.randrange(250, 350))
def __iter__(self): for j in range(BOARD_COL_LENGTH): for i in range(BOARD_ROW_LENGTH): point = Point(i, j) yield point, self[point]
def process_frame(mapp, img, K, Kinv, plot2d, plot3d): t1 = time.time() # first resize: frame = Frame(mapp, K, Kinv, img) if frame.id == 0: return # current frame f1 = mapp.frames[-1] # previous frame f2 = mapp.frames[-2] print(f1.id) # once we have two frames: # step1: match two images to get point indices and Rt # these indices whose points correspond have passed RANSAC filter idx1, idx2, pose_matrix, _ = match_frame(f1, f2) f1.pose = np.dot(pose_matrix, f2.pose) # step2: # add new observation if the point is already observed in the previous frame for i, idx in enumerate(idx2): if f2.key_pts[idx] is not None and f1.key_pts[idx1[i]] is None: f2.key_pts[idx].add(f1, idx1[i]) # idx1 and idx2 correspond to the same list of points but in two adjacent frames # because key points have the same length as raw points: # idx1 is the index of the points that have match for # we want to triangulate the key points that we don't have match for: good_pts = np.array([f1.key_pts[ii] is None for ii in idx1]) # using normalized coordinates to compute triangulation # this will return the key points' homogeneous coordinates: pts_homo = triangulate(f1, f2, normalize(f1.Kinv, f1.raw_pts[idx1]), normalize(f2.Kinv, f2.raw_pts[idx2])) good_pts &= np.abs(pts_homo[:, 3]) != 0 pts_homo /= pts_homo[:, 3:] # for a qualified point to be added to the map, it has to pass the following tests: new_pts_count = 0 for i, p in enumerate(pts_homo): if not good_pts[i]: continue # check if the points are in front of the camera pl1 = np.dot(f1.pose, p) pl2 = np.dot(f2.pose, p) if pl1[2] < 0 or pl2[2] < 0: continue # reproject: pp1 = np.dot(K, pl1[:3]) pp2 = np.dot(K, pl2[:3]) # check reprojection error: pp1 = (pp1[0:2] / pp1[2]) - f1.raw_pts[idx1[i]] pp2 = (pp2[0:2] / pp2[2]) - f2.raw_pts[idx2[i]] pp1 = np.sum(pp1**2) pp2 = np.sum(pp2**2) if pp1 > 2 or pp2 > 2: continue # using the colored pixel in the frame at the point location to color the point color = img[int(round(f1.raw_pts[idx1[i], 1])), int(round(f1.raw_pts[idx1[i], 0]))] pt = Point(mapp, p[0:3], color) pt.add(f1, idx1[i]) pt.add(f2, idx2[i]) new_pts_count += 1 # by these two filters, adding the qualified points print("New points added: %d" % new_pts_count) # now display the result (in both 2D and 3D mapping): if plot2d is not None: # paint annotations on the image for i1, i2 in zip(idx1, idx2): u1, v1 = int(round(f1.raw_pts[i1][0])), int( round(f1.raw_pts[i1][1])) u2, v2 = int(round(f2.raw_pts[i2][0])), int( round(f2.raw_pts[i2][1])) # this is for plotting the matching line: if f1.key_pts[i1] is not None: if len(f1.key_pts[i1].frames) >= 5: cv2.circle(img, (u1, v1), color=(0, 255, 0), radius=3) else: cv2.circle(img, (u1, v1), color=(0, 0, 255), radius=3) else: cv2.circle(img, (u1, v1), color=(0, 0, 0), radius=3) cv2.line(img, (u1, v1), (u2, v2), color=(255, 0, 0)) # font = cv2.FONT_HERSHEY_SIMPLEX # cv2.putText(img, 'FPS: %.2F' % (1/(time.time()-t1)), (10, 500), font, 1, (0, 0, 255), 2, cv2.LINE_AA) plot2d.draw(img) # Now doing Bundle Adjustment for every 10 frames: if frame.id >= 9 and frame.id % 10 == 0: err = mapp.optimize() print("Optimizing the frame: %f units of error" % err) # now display the 3D map: if plot3d is not None: plot3d.draw(mapp) print('FPS: %.1f' % (1 / (time.time() - t1)))
def test_attributes(self): point = Point(1, 2, 3) self.assertEqual((point.x, point.y, point.z), (1, 2, 3)) point.x = 4 self.assertEqual(point.x, 4)
def test_should_check_get_azimuth(): # given begin_point = Point('P1245', 0, 0) end_point_0 = Point('P0', 1, 0) end_point_50 = Point('P50', 1, 1) end_point_100 = Point('P100', 0, 1) end_point_150 = Point('P150', -1, 1) end_point_200 = Point('P200', -1, 0) end_point_250 = Point('P250', -1, -1) end_point_300 = Point('P300', 0, -1) end_point_350 = Point('P350', 1, -1) # when # then assert begin_point.get_azimuth(end_point_0) == 0 assert begin_point.get_azimuth(end_point_50) == 50 assert begin_point.get_azimuth(end_point_100) == 100 assert begin_point.get_azimuth(end_point_150) == 150 assert begin_point.get_azimuth(end_point_200) == 200 assert begin_point.get_azimuth(end_point_250) == 250 assert begin_point.get_azimuth(end_point_300) == 300 assert begin_point.get_azimuth(end_point_350) == 350
lon = float(lon) if lon < -180.0 or lon > 180.0: raise argparse.ArgumentTypeError("Longitude is between -180 and 180") return lon if __name__ == "__main__": # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("--file", type=str, required=True, help="Path to data file") parser.add_argument("--max-dist", type=float, default=MAX_DIST, help="Max distance in kilometers") parser.add_argument("--lat", type=latitude, default=ORIGIN[0], help="Origin latitude to calculate distances from") parser.add_argument("--lon", type=longitude, default=ORIGIN[1], help="Origin longitude to calculate distances from") args = parser.parse_args() # initialise variables, check if within given distance users_to_invite = [] origin = Point(args.lat, args.lon) for record in reader.read(args.file): point = Point.from_record(record) if point.within_dist(origin, args.max_dist): users_to_invite.append(User.from_record(record)) # sort users users_to_invite.sort() # log LOGGER.info("Users to invite:") for user in users_to_invite: LOGGER.info(user)