def test_should_retrieve_false_to_a_point_that_is_not_inside_a_polygon(self): A = [3, 6]; B = [3, 11]; C = [6, 11]; D = [6, 9]; E = [5, 9]; F = [5, 6] polygon = Polygon([A, B, C, D, E, F]) test_point = [4, 5] assert_false(polygon.belongs_to_polygon(test_point)) test_point = [6, 7] assert_false(polygon.belongs_to_polygon(test_point))
def project(self, perspective=False): p = Polygon() for line in self.lines: line2d = line.project(perspective) p.add_line(line2d) return p
def __init__(self, position = (0, 0), node_list = []): Polygon.__init__(self, node_list) Translatable.__init__(self, position) Named.__init__(self) self.__connected_objects = [] self.__pointed_objects = [] self.add_name('_arrow_')
def test_various_points_in_square(self): square = Polygon( vertex_positions=[ (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), ] ) test_points = [] for x in range(-3, 4): for y in range(-3, 4): test_points.append((0.5*x, 0.5*y)) for point in test_points: x, y = point if -1 < x < 1 and -1 < y < 1: # Point is inside. self.assertEqual(square.winding_number(point), 1) elif x < -1 or x > 1 or y < -1 or y > 1: # Point outside. self.assertEqual(square.winding_number(point), 0) else: with self.assertRaises(ValueError): square.winding_number(point)
def generate_new_poly(self, ev): points = get_random_polygon() self.set_points(points) poly = Polygon() poly.set_points(points) self.canvas.delete("all") self.draw_polygon_points(poly) self.set_result(0)
def __init__(self, position, rotation, color): p1 = Point(0,-4) p2 = Point(0,4) p3 = Point(20,0) self.outline = [p3, p1, p2] self.position = position self.rotation = rotation self.color = color Polygon.__init__(self, self.outline, self.position, self.rotation, self.color)
def make_square( self, top_left, bottom_right, z ): colour = 255 - z % 100 a, b = top_left c, d = bottom_right square = Polygon( ( colour, colour, colour ) ).add( Point( a, b, z ) ) \ .add( Point( b, c, z ) ).add( Point( c, d, z ) ) \ .add( Point( d, a, z ) ) square.set_width( 1 ) return square
def create_linked_list(filename='input.txt'): points = read_from_file(filename) poly = Polygon() poly.set_points(points) points = poly.get_linked_list() return points[0], len(points)
def test_clockwise_square(self): square = Polygon( vertex_positions=[ (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), ][::-1] ) origin = (0.0, 0.0) self.assertEqual(square.winding_number(origin), -1) self.assertEqual(square.area(), -4.0)
def test_double_square(self): square = Polygon( vertex_positions=[ (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), ] * 2 ) origin = (0.0, 0.0) self.assertEqual(square.winding_number(origin), 2) self.assertEqual(square.area(), 8.0)
def test_simple_square(self): square = Polygon( vertex_positions=[ (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), ] ) origin = (0.0, 0.0) self.assertEqual(square.winding_number(origin), 1) self.assertEqual(square.area(), 4.0)
def create_random(self, n): """ Create n polygons with random vertices. The dimensions of each picture should be specified with max_x and may_y. """ self.polygons = [] for i in xrange(0, n): p = Polygon() # 3 to 5 vertices Polygon.create_random(p, random.randint(3,5)) self.polygons.append(p) return self
def __init__(self): shape = [Point(24, 0), Point(-12, -12), Point(0, 0), Point(-12, 12)] position = Point(config.SCREEN_X/2, config.SCREEN_Y/2) self.rotation = config.SHIP_INITIAL_DIRECTION color = config.SHIP_COLOR Polygon.__init__(self, shape, position, self.rotation, color) self.accelerate = (0, 0) self.stop = Point(0, 0) pygame.mixer.init() self.fire_sfx = pygame.mixer.Sound("laser.wav") self.count = 5 self.shield_health = 100 self.nuke_count = 1
def __init__(self, position, rotation, color, rotation_speed, motion): self.outline = [] for angle in range(0, 360, 360/config.ROCK_POLYGON_SIZE): radius = random.uniform(config.ROCK_MIN_RADIUS, config.ROCK_MAX_RADIUS) angle_rad = math.radians(angle) (x,y) = math.cos(angle_rad) * radius, math.sin(angle_rad) * radius p = Point(x,y) self.outline.append(p) self.position = position self.rotation = rotation self.color = color self.rotation_speed = rotation_speed self.motion = motion Polygon.__init__(self, self.outline, self.position, self.rotation, self.color) self.accelerate(self.motion)
def test_numpy_compatibility(self): square = Polygon( vertex_positions=numpy.array( [ [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], ], dtype=numpy.float64, ) ) origin = numpy.array([0.0, 0.0], dtype=numpy.float64) self.assertEqual(square.winding_number(origin), 1) self.assertEqual(square.area(), 4.0)
def load_video(self, video_id): load = False s = self.dbs result = s.query(Video).filter(Video.id == video_id) if result.count() == 1: video = result.first() load = True elif result.count() > 1: print("Found more than 1 match in database!") else: print("No match found in database!") if load == True: self.path = video.path self.base_name = video.name self.fps = str(video.fps) self.duration = video.duration # address self.address_window = AddressWindow(self, self.main_window) self.address_window.get_address(video.address_id) # polygon self.polygon = Polygon(self, self.source) self.polygon.get_points(video.id) self.polygon.compute_area() area = self.polygon.area self.main_window.area_lbl.setText(str(abs(area))) self.metadata = get_metadata(self.path) self.duration = get_duration(self.metadata) self.resolution = get_resolution(self.metadata) self.format = get_format(self.metadata) # load in setup self.populate_setup()
def open(self): init_analysis(self.main_window) self.main_window.analysis_next_btn.setEnabled(True) if self.source.media == 'file': self.source.base_name = get_base_file(self.file) self.source.analysis_frames = cv2.VideoCapture(self.file) if self.source.media == 'camera': init_analysis_camera(self.main_window) print("Setting analysis frames for camera") # release camera resource for analysis self.source.setup_frames.release() self.source.analysis_frames = cv2.VideoCapture(config['camera']) # images folder directory = 'images/' + self.source.base_name create_dir(directory) self.get_video() if self.source.media == 'file': self.setup.load_video(self.video.id) self.background = Background(self.source) self.background.get_db(self.video.id) self.source.background = self.background self.polygon = Polygon(self.source, self.setup) self.polygon.get_points(self.video.id) self.polygon.draw_setup(self.background.frame, self.polygon.points) self.source.polygon = self.polygon self.play = Play(self.source, self.setup) self.play.run_analysis() # set location self.location.set_location(self.video.address_id) # play self.click_analysis_play_btn()
def main(): interface = GUI() points = ioclass.read_from_file(filename) interface.set_points(points) poly = Polygon() poly.set_points(points) ear_art_gallery_problem.art_gallery_problem(interface) #seidel_art_gallery_color.art_gallery_problem(interface) #ear_triang_segment_tree.ear_segment_art_gallery_problem(interface) interface.draw_polygon_points(poly) root = interface.get_root() root.mainloop()
def test_aitch(self): aitch = Polygon( vertex_positions=[ (0, 0), (1, 0), (1, 1), (2, 1), (2, 0), (3, 0), (3, 3), (2, 3), (2, 2), (1, 2), (1, 3), (0, 3), ] ) test_points = [ (0.5*x, 0.5*y) for y in range(-1, 8) for x in range(-1, 8) ] # * for boundary, '.' for outside, 'o' for inside. template = """\ ......... .***.***. .*o*.*o*. .*o***o*. .*ooooo*. .*o***o*. .*o*.*o*. .***.***. ......... """ expected = ''.join(template.strip().split()) assert len(expected) == len(test_points) for point, point_type in zip(test_points, expected): if point_type == '.': self.assertEqual(aitch.winding_number(point), 0) elif point_type == 'o': self.assertEqual(aitch.winding_number(point), 1) else: with self.assertRaises(ValueError): aitch.winding_number(point)
def art_gallery_problem(interface, points=None, show_decomposition=True): if points is None: points = ioclass.read_from_file(filename) poly = Polygon() poly.set_points(points) linked_list = poly.get_linked_list() headnode = linked_list[0] size = len(points) # Check if the file reading was successful or if there were inconsistencies: if not headnode or size < 3: print("No triangulations to output") return # Create a Triangulation object from the linked list: t1 = EarTriangulation(headnode, size) # Do the triangulation. The return value is a list of 3-tuples, which # represent the vertices of each triangle. triangles1 = t1.triangulate() # Now for the GUI. Both the polygon and its triangulation have been scaled, # as specified above. Now we need to draw them on a Tkinter Canvas. # Setup and init a canvas: if show_decomposition: interface.draw_triangles(triangles1) # The last step is to output the triangulation of the original, non-scaled # polygon to the console: ioclass.print_triangles_to_console(triangles1) art_gallery_coloring = Coloring() art_gallery_coloring.set_triangulation(points, triangles1) points_str, res = art_gallery_coloring.colorize() list_res = [] for p in points_str: p = p.name list_res.append([points[int(p)].x, points[int(p)].y]) interface.draw_result(list_res) interface.set_result(res)
class PrimitiveParser(object): def __init__(self): self.PRIMITIVE_MAP = { "Line" : self.make_line, "moveto" : self.move_to, "lineto" : self.line_to, "stroke" : self.stroke, } self.polygon = Polygon() self.pen = None def parse(self, string): parts = string.split(" ") definition = parts[:-1] identifier = parts[-1].strip() if identifier in self.PRIMITIVE_MAP: return self.PRIMITIVE_MAP[identifier](definition) else: raise RuntimeError("NotImplemented Error: Primitive [%s]" % identifier) def make_line(self, parts): parts = [int(p) for p in parts[:4]] p1 = Point([parts[0], parts[1]]) p2 = Point([parts[2], parts[3]]) return Line(p1, p2) def move_to(self, parts): x, y = [int(c) for c in parts[0:2]] self.pen = Point([x, y]) return None def line_to(self, parts): assert(self.pen is not None) last_point = self.pen self.move_to(parts) current_point = self.pen line = Line(last_point, current_point) self.polygon.add_line(line) return None def stroke(self, parts=None): polygon = self.polygon self.polygon = Polygon() return polygon
def basic_intersection_test(): poly = Polygon() poly.add_point(0, 0) poly.add_point(0, 1) poly.add_point(-1, 1) poly.add_point(-1, 0) line = [numpy.array([0, 0]), numpy.array([0, 1])] assert(intersect_single(line, poly) == True) line = [numpy.array([0, 1]), numpy.array([-1, 1])] assert(intersect_single(line, poly) == True) line = [numpy.array([-1, 1]), numpy.array([-1, 0])] assert(intersect_single(line, poly) == True) line = [numpy.array([-1, 0]), numpy.array([0, 0])] assert(intersect_single(line, poly) == True)
def basic_path_test(): poly1 = Polygon() poly1.add_point(0, 0) poly1.add_point(0, 1) poly1.add_point(-1, 1) poly1.add_point(-1, 0) # poly2 = Polygon() # poly2.add_point(101, 0) # poly2.add_point(101, 1) # poly2.add_point(100, 1) # poly2.add_point(100, 0) astarplanner = AStarPlanner() astarplanner.add_polygon(poly1) # astarplanner.add_polygon(poly2) print astarplanner.find_path(-1, -1, 1000, 1000)
def __init__(self): self.PRIMITIVE_MAP = { "Line" : self.make_line, "moveto" : self.move_to, "lineto" : self.line_to, "stroke" : self.stroke, } self.polygon = Polygon() self.pen = None
def load_objects( filename ): global VERSION_NUMBER polygons = [] with open( filename, 'r' ) as f: lines = f.readlines() version = float( lines.pop( 0 ) ) if version >= VERSION_NUMBER: lines.pop( 0 ) # ignore num_objects while len( lines ) > 0: c = lines.pop( 0 ).split() polygon = Polygon( ( int( c[ 0 ] ), int( c[ 1 ] ), int( c[ 2 ] ) ) ) num_ps = int( lines.pop( 0 ) ) for i in range( 0, num_ps ): magnitudes = map( int, lines.pop( 0 ).split() ) polygon.add( Point( *magnitudes ) ) polygons.append( polygon.close() ) else: print "Modeller3D version " + VERSION_NUMBER + " cannot read file from Modeller3D version " + version return polygons
def __init__(self): shape = [] position = Point(random.uniform(0, config.SCREEN_X), random.uniform(0, config.SCREEN_Y)) color = config.ASTEROID_COLOR self.speed = random.uniform(config.ASTEROID_MIN_SPEED, config.ASTEROID_MAX_SPEED) rotation = random.uniform(0.0, 359.99) if random.randint(0, 1): self.speed *= -1 for i in range(config.ASTEROID_POLYGON_SIZE): radius = random.uniform(config.ASTEROID_MIN_RADIUS, config.ASTEROID_MAX_RADIUS) radian = math.radians(i * 360 / config.ASTEROID_POLYGON_SIZE) x = math.cos(radian) * radius y = math.sin(radian) * radius shape.append(Point(x, y)) Polygon.__init__(self, shape, position, rotation, color) self.ast_speed = random.uniform(config.ASTEROID_MIN_SPEED, config.ASTEROID_MAX_SPEED) self.accelerate(self.ast_speed)
def change_solution_method(self, ev): # 0 - ear - coloring # 1 - ear - segment - tree self.canvas.delete("all") points = self.points poly = Polygon() poly.set_points(points) self.draw_polygon_points(poly) show_decomposition = self.show_decomposition_checkbox.var.get() == 1 mode = self.method_combo.current() if mode == 0: ear_art_gallery_problem.art_gallery_problem(interface=self, points=points, show_decomposition=show_decomposition) elif mode == 1: ear_triang_segment_tree.ear_segment_art_gallery_problem(interface=self, points=points, show_decomposition=show_decomposition) elif mode == 2: seidel_art_gallery_segment.seidel_segment_art_gallery_problem(interface=self, points=points, show_decomposition=show_decomposition) elif mode == 3: seidel_art_gallery_color.art_gallery_problem(interface=self, points=points, show_decomposition=show_decomposition)
def mutate(self): """ Create a new picture by mutating a polygon, adding a polygon, or removing a polygon. Return a new picture """ new_picture = Picture() # Buffer changes so we iterate correctly to_add = [] for polygon in self.polygons: mutation_type = random.random() if (mutation_type < 0.1): # Stay the same new_polygon = Polygon() new_polygon.vertices = list(polygon.vertices) to_add.append(new_polygon) if (mutation_type < 0.8): # Do some mutation to_add.append(polygon.mutate()) elif (mutation_type >= 0.8 and mutation_type < 0.9): # Add a polygon new_polygon = Polygon() new_polygon = new_polygon.create_random(3) to_add.append(new_polygon) elif (mutation_type >= 0.9): # Remove a polygon by not adding it to the new picture if (len(self.polygons) <= 1): # Mutate instead if there is only one polygon left to_add.append(polygon.mutate()) else: pass # Add polygons here so that we don't iterate over new polygons for p in to_add: new_picture.polygons.append(p) return new_picture
def art_gallery_problem(interface, points=None, show_decomposition=True): if points is None: points = ioclass.read_from_file(filename) poly = Polygon() poly.set_points(points) size = len(points) list_points = [] for p in points: list_points.append([p.x, p.y]) seidel_triangalator = seidel.Triangulator(list_points) triangles1 = seidel_triangalator.triangles() # Now for the GUI. Both the polygon and its triangulation have been scaled, # as specified above. Now we need to draw them on a Tkinter Canvas. # Setup and init a canvas: if show_decomposition: interface.draw_triangles(triangles1) # The last step is to output the triangulation of the original, non-scaled # polygon to the console: # ioclass.print_triangles_to_console(triangles1) art_gallery_coloring = Coloring() art_gallery_coloring.set_triangulation(points, triangles1) points_str, res = art_gallery_coloring.colorize() list_res = [] for p in points_str: p = p.name list_res.append([points[int(p)].x, points[int(p)].y]) interface.draw_result(list_res) interface.set_result(res)
def open(self): self.source.base_name = get_base_file(self.file) # background folder directory = 'backgrounds/' + self.source.base_name create_dir(directory) init_setup_new(self.main_window) self.source.setup_frames = cv2.VideoCapture(self.file) self.get_data() self.populate_setup() self.address_window = AddressWindow(self, self.main_window) self.polygon = Polygon(self, self.source) self.draw_status = False self.play = Play(self.source, self) self.play.run_setup() self.background = Background(self.source)
def test_points_not_same_as_poly_if_position_not_zero(self, *position): position = list(position) polygon = Polygon([[0, 0], [0, 10], [10, 0], [10, 10]]) piece = PolygonPiece(polygon, position) self.assertNotEqual(polygon.get_points().tolist(), piece.get_points_in_plane().tolist())
def title_screen(): globs.textboxes = [] title_box = TextBox(font_loc + "Vitreous-Black.ttf", size=80, color=Vec(0.0, 0.0, 0.0), pos=Vec(120, 525, -0.2)) title_box.text = "Tesseland" globs.textboxes.append(title_box) name_boxes = [ TextBox(font_loc + "Vitreous-Medium.ttf", size=30, color=Vec(0, 0, 0), pos=Vec(150, 425 - 50 * k, -0.2)) for k in range(3) ] name_boxes[0].text = "Triangle Madness by Sarah Asano" name_boxes[1].text = "Polygon Panic by Chris Couste" name_boxes[2].text = "Rectange Ruckus by Patrick Rall" globs.textboxes += name_boxes click_to_begin = TextBox(font_loc + "Vitreous-Medium.ttf", size=30, color=Vec(0, 0, 0), pos=Vec(150, 150, -0.2)) click_to_begin.text = "Click to begin" globs.textboxes.append(click_to_begin) globs.hud_polygons = [] globs.hud_polygons.append( Polygon(Vec(0, 1, 1), [Vec(0, 3), Vec(0, 8), Vec(5, 8)])) globs.hud_polygons.append( Polygon(Vec(1, 1, 1), [Vec(2, 5), Vec(5, 8), Vec(8, 8), Vec(8, 5)])) globs.hud_polygons.append( Polygon( Vec(1, 0.5, 0), [Vec(0, 0), Vec(0, 3), Vec(2, 5), Vec(3, 5), Vec(8, 0)])) globs.hud_polygons.append( Polygon(Vec(0.5, 1.0, 0), [Vec(3, 5), Vec(8, 0), Vec(8, 5)])) while True: _, button, action, mods = yield from listen.on_mouse_button( globs.window) x, y = glfw.get_cursor_pos(globs.window) pt = mouse_coords(x, y) for poly in globs.hud_polygons: if is_point_in_poly(pt, poly): globs.hud_polygons.remove(poly) break if len(globs.hud_polygons) == 0: globs.textboxes = [] listen.dispatch("next_level") break
def test_points_same_as_poly_if_position_zero(self, *points): points = list(points) polygon = Polygon(points.copy()) piece = PolygonPiece(polygon, [0, 0]) self.assertEqual(polygon.get_points().tolist(), piece.get_points_in_plane().tolist())
def test_right_angle_triangle_area_correct(self): points = [[1, 1], [3, 3], [3, 1]] expected_area = 2 poly = Polygon(points) self.assertEqual(expected_area, poly.area())
def box(minx, miny, maxx, maxy, ccw=True): """Returns a rectangular polygon with configurable normal vector""" coords = [(maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny)] if not ccw: coords = coords[::-1] return Polygon(coords)
def test_move_zeroes_doesnt_change_position(self): starting_position = [125, 123] piece = PolygonPiece(Polygon([[0, 0], [3, 3], [0, 3]]), starting_position.copy()) piece.move(0, 0) self.assertEqual(starting_position, piece.get_position())
def test_square_area_correct(self): points = [[0, 0], [0, 1], [1, 1], [1, 0]] expected_area = 1 poly = Polygon(points) self.assertEqual(expected_area, poly.area())
def test_polygon_created_with_points_list(self): Polygon(self.square_points)
def test_polygon_returns_points(self): polygon = Polygon(self.square_points.copy()) self.assertEqual(polygon.get_points().tolist(), self.square_points)
def __init__(self): self.rectangle = Polygon.rectangle(start, rect_x, rect_y) self.rotational_speed = 0 self.linear_speed = P(0, 0) self.center = self.rectangle.center()
def level6(): globs.move_count = 9 globs.polydata["origin"] = Vec(-5, -2) globs.polydata["nx"] = 5 globs.polydata["ny"] = 4 cs = [] cs.append(Vec(0.0, 1.0, 1.0)) # cyan 0 cs.append(Vec(0.0, 1.0, 0.0)) # green 1 cs.append(Vec(0.0, 0.0, 1.0)) # blue 2 cs.append(Vec(1.0, 0.0, 1.0)) # pink 3 cs.append(Vec(1.0, 1.0, 0.0)) # yellow 4 cs.append(Vec(0.0, 0.0, 0.0)) # black 5 globs.polydata["colors"] = [ cs[0], cs[2], cs[4], cs[3], cs[2], cs[5], cs[2], cs[4], cs[2] ] polys = {} s = 0.5 t = s * np.sqrt(3.0) / 2.0 xr = [ 0, s / 2, t, t + (s / 2), t + s, (s / 2) + (2 * t), (2 * t) + s, (1.5 * s) + (2 * t), (2 * t) + (2 * s) ] yr = [0, s / 2, s, (s / 2) + t, s + t, (1.5 * s) + t] for cut in range(6): th, cen = np.radians(cut * 60), Vec(0, 0) def n(tile): return tile + str( (cut + 1) % 6) # tile name with id for next cut (ccw) def p(tile): return tile + str( (cut - 1) % 6) # tile name with id for previous cut (cw) def c(tile, a_cut=cut): return tile + str(a_cut) # tile+id: arbitrary cut (default active) polys[c("ta")] = Polygon(cs[2], [rotate(Vec(xr[0],yr[0]),cen,th), \ rotate(Vec(xr[0],yr[2]),cen,th), rotate(Vec(xr[2],yr[1]),cen,th)]) polys[c("sb")] = Polygon(cs[0], \ [rotate(Vec(xr[0],yr[2]),cen,th), rotate(Vec(xr[1],yr[4]),cen,th), \ rotate(Vec(xr[3],yr[3]),cen,th), rotate(Vec(xr[2],yr[1]),cen,th)]) polys[c("tc")] = Polygon(cs[4], [rotate(Vec(xr[2],yr[1]),cen,th), \ rotate(Vec(xr[3],yr[3]),cen,th), rotate(Vec(xr[4],yr[1]),cen,th)]) polys[c("td")] = Polygon(cs[4], [rotate(Vec(xr[1],yr[4]),cen,th), \ rotate(Vec(xr[3],yr[5]),cen,th), rotate(Vec(xr[3],yr[3]),cen,th)]) polys[c("te")] = Polygon(cs[3], [rotate(Vec(xr[3],yr[3]),cen,th), \ rotate(Vec(xr[3],yr[5]),cen,th), rotate(Vec(xr[5],yr[4]),cen,th)]) polys[c("sf")] = Polygon(cs[5], \ [rotate(Vec(xr[3],yr[3]),cen,th), rotate(Vec(xr[5],yr[3]),cen,th), \ rotate(Vec(xr[6],yr[2]),cen,th), rotate(Vec(xr[4],yr[1]),cen,th)]) polys[c("tg")] = Polygon(cs[3], [rotate(Vec(xr[4],yr[1]),cen,th), \ rotate(Vec(xr[6],yr[2]),cen,th), rotate(Vec(xr[6],yr[0]),cen,th)]) polys[c("th")] = Polygon(cs[4], [rotate(Vec(xr[5],yr[4]),cen,th), \ rotate(Vec(xr[7],yr[4]),cen,th), rotate(Vec(xr[6],yr[2]),cen,th)]) polys[c("ti")] = Polygon(cs[2], [rotate(Vec(xr[6],yr[2]),cen,th), \ rotate(Vec(xr[7],yr[4]),cen,th), rotate(Vec(xr[8],yr[2]),cen,th)]) polys[c("sj")] = Polygon(cs[1], \ [rotate(Vec(xr[6],yr[0]),cen,th), rotate(Vec(xr[6],yr[2]),cen,th), \ rotate(Vec(xr[8],yr[2]),cen,th), rotate(Vec(xr[8],yr[0]),cen,th)]) # (b[my cut][which border] = (neighbor unit x, neighbor unit y, neighbor cut)) b = [[(0,1,4), (1,0,2), (1,0,3)], [(1,-1,5), (0,1,3), (0,1,4)], \ [(-1,0,0), (1,-1,4), (1,-1,5)], [(0,-1,1), (-1,0,5), (-1,0,0)], \ [(1,-1,2), (0,-1,0), (0,-1,1)], [(1,0,3), (1,-1,1), (1,-1,2)]] polys[c("ta")].neighbors = [(0, 0, n("ta")), (0, 0, c("sb")), (0, 0, p("ta"))] polys[c("sb")].neighbors = [(0, 0, c("ta")), (0, 0, c("tc")), (0, 0, n("tc")), (0, 0, c("td"))] polys[c("tc")].neighbors = [(0, 0, c("sf")), (0, 0, c("sb")), (0, 0, p("sb"))] polys[c("td")].neighbors = [(0, 0, c("te")), (0, 0, c("sb")), (0, 0, n("tg"))] print([(x, y, c("sj", z)) for x, y, z in [b][0][cut]][0]) polys[c("te")].neighbors = [(0,0,c("sf")), (0,0,c("td")), \ [(x,y,c("sj",z)) for x,y,z in [b][0][cut]][0]] polys[c("sf")].neighbors = [(0, 0, c("tc")), (0, 0, c("te")), (0, 0, c("th")), (0, 0, c("tg"))] polys[c("tg")].neighbors = [(0, 0, c("sf")), (0, 0, c("sj")), (0, 0, p("td"))] print([(x, y, c("ti", z)) for x, y, z in [b][0][cut]][0]) polys[c("th")].neighbors = [(0,0,c("sf")), (0,0,c("ti")), \ [(x,y,c("ti",z)) for x,y,z in [b][0][cut]][0]] print([(x, y, c("th", z)) for x, y, z in [b][0][cut]][0]) polys[c("ti")].neighbors = [(0,0,c("th")), (0,0,c("sj")), \ [(x,y,c("th",z)) for x,y,z in [b][0][cut]][0]] print([(x, y, c("te", z)) for x, y, z in [b][0][cut]][1]) print([(x, y, c("sj", z)) for x, y, z in [b][0][cut]][2]) polys[c("sj")].neighbors = [(0,0,c("ti")), (0,0,c("tg")), \ [(x,y,c("te",z)) for x,y,z in [b][0][cut]][1], [(x,y,c("sj",z)) for x,y,z in [b][0][cut]][2]] return repeat_cell(1, 1, Vec((4 * t) + (3 * s), 0), Vec((2 * t) + (1.5 * s), (3 * s) + (3 * t)), polys)
def _polygon(self, n_edges): if n_edges == 3 or n_edges == 2 or n_edges == 1 or n_edges == 0: return Polygon(n_edges=3, circumradius = self._circumradius) else: return Polygon(n_edges=n_edges, circumradius = self._circumradius)
def most_efficient(self): """Most efficient polygon in terms of area:perimeter ratio. This will always be the max vertices polygon.""" return Polygon(n_edges=self._n_edges_max, circumradius=self._circumradius)
# set timing stuff fps = 60 dt = 1 / fps clock = pygame.time.Clock() # set objects objects = [] offsets = [[0, 0], [200, 0], [200, 100], [100, 200], [0, 100]] polygons = [] polygons.append( Polygon(localOffsets=list(reversed(offsets)), mass=1, pos=[300, 200], color=[255, 0, 0], normals_length=50)) my_poly = Polygon(localOffsets=[[-50, -50], [-20, 40], [40, -20]], mass=math.inf, color=[0, 0, 255], width=1, normals_length=20) objects = polygons + [my_poly] # game loop running = True while running: # EVENT loop for event in pygame.event.get():
def test_points_dont_increase_with_positive_position(self, *position): position = list(position) polygon = Polygon([[0, 0], [0, 10], [10, 0], [10, 10]]) piece = PolygonPiece(polygon, position) self.assertLessEqual(piece.get_points_in_plane().sum(), polygon.get_points().sum())
def test_rotate_360_doesnt_change_points(self, rotation): polygon = Polygon(self.vertical_rectangle_points.copy()) polygon.rotate(rotation) rotated = [[round(p[0]), round(p[1])] for p in polygon.get_points()] self.assertEqual(self.vertical_rectangle_points, rotated)
def test_move_negative_amount_doesnt_increase_position(self, x, y): starting_position = [125, 123] piece = PolygonPiece(Polygon([[0, 0], [3, 3], [0, 3]]), starting_position.copy()) piece.move(x, y) self.assertLessEqual(piece.get_position(), starting_position)
def test_flip_polygon_point_count_doesnt_change(self, *points): points = list(points) poly = Polygon(points.copy()) poly.flip() self.assertEqual(len(points), len(poly.get_points()))
def test_get_center_distance_from_returns_array_with_two_numbers(self): piece = PolygonPiece(Polygon([[0, 0], [3, 3], [0, 3]]), [125, 30]) distance = piece.get_center_distance_from(250, 300) self.assertEqual(2, len(distance))
def convex_hull(*args): """The convex hull surrounding the Points contained in the list of entities. Parameters ========== args : a collection of Points, Segments and/or Polygons Returns ======= convex_hull : Polygon Notes ===== This can only be performed on a set of non-symbolic points. References ========== [1] http://en.wikipedia.org/wiki/Graham_scan [2] Andrew's Monotone Chain Algorithm ( A.M. Andrew, "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979) http://softsurfer.com/Archive/algorithm_0109/algorithm_0109.htm See Also ======== sympy.geometry.point.Point, sympy.geometry.polygon.Polygon Examples ======== >>> from sympy.geometry import Point, convex_hull >>> points = [(1,1), (1,2), (3,1), (-5,2), (15,4)] >>> convex_hull(*points) Polygon(Point(-5, 2), Point(1, 1), Point(3, 1), Point(15, 4)) """ from entity import GeometryEntity from point import Point from line import Segment from polygon import Polygon p = set() for e in args: if not isinstance(e, GeometryEntity): try: e = Point(e) except NotImplementedError: raise ValueError( '%s is not a GeometryEntity and cannot be made into Point' % str(e)) if isinstance(e, Point): p.add(e) elif isinstance(e, Segment): p.update(e.points) elif isinstance(e, Polygon): p.update(e.vertices) else: raise NotImplementedError('Convex hull for %s not implemented.' % type(e)) p = list(p) if len(p) == 1: return p[0] elif len(p) == 2: return Segment(p[0], p[1]) def orientation(p, q, r): '''Return positive if p-q-r are clockwise, neg if ccw, zero if collinear.''' return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1]) # scan to find upper and lower convex hulls of a set of 2d points. U = [] L = [] p.sort() for p_i in p: while len(U) > 1 and orientation(U[-2], U[-1], p_i) <= 0: U.pop() while len(L) > 1 and orientation(L[-2], L[-1], p_i) >= 0: L.pop() U.append(p_i) L.append(p_i) U.reverse() convexHull = tuple(L + U[1:-1]) if len(convexHull) == 2: return Segment(convexHull[0], convexHull[1]) return Polygon(*convexHull)
def test_rectangle_area_correct(self): points = [[0, 0], [0, 3], [1, 3], [1, 0]] expected_area = 3 poly = Polygon(points) self.assertEqual(expected_area, poly.area())
import cv2 import cv2.aruco as aruco import numpy as np import os from polygon import Polygon import math as m button = Polygon( np.array(list(map(list, [(0, 0), (0, 20), (20, 20), (20, 0)]))), (0, 255, 0)) scanState = 0 polygonsState0 = [] polygonsState1 = [] polygonsState2 = [] def finiteStateMachine(event, x, y, flags, param): global scanState, polygonsState0, polygonsState1, polygonsState2 if event == cv2.EVENT_LBUTTONDOWN: #checks mouse left button down condition print(x, y) if pointInsidePolygon((x, y), button.getCoordinates()): scanState += 1 print("cambio de estado", scanState) if scanState == 0: print("finiteStateMachine", scanState) print("desde la funcion", polygonsState0) #print((x,y), polygonsState0[0].egtCoordinates()) for polygon in polygonsState0: if pointInsidePolygon((x, y), polygon.getCoordinates()): polygon.nextColor()
def convex_hull(*args): """The convex hull of a collection of 2-dimensional points. Parameters ---------- args : a collection of Points Returns ------- convex_hull : Polygon Notes ----- This can only be performed on a set of non-symbolic points. See Also -------- Point References ---------- http://en.wikipedia.org/wiki/Graham_scan Examples -------- >>> from sympy.geometry import Point, convex_hull >>> points = [Point(x) for x in [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]] >>> convex_hull(points) Polygon(Point(-5, 2), Point(1, 1), Point(3, 1), Point(15, 4)) """ from point import Point from line import Segment from polygon import Polygon def uniquify(a): # not order preserving return list(set(a)) p = args[0] if isinstance(p, Point): p = uniquify(args) if len(p) == 1: return p[0] elif len(p) == 2: return Segment(p[0], p[1]) def orientation(p, q, r): '''Return positive if p-q-r are clockwise, neg if ccw, zero if collinear.''' return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1]) # scan to find upper and lower convex hulls of a set of 2d points. U = [] L = [] p.sort() for p_i in p: while len(U) > 1 and orientation(U[-2], U[-1], p_i) <= 0: U.pop() while len(L) > 1 and orientation(L[-2], L[-1], p_i) >= 0: L.pop() U.append(p_i) L.append(p_i) U.reverse() convexHull = tuple(L + U[1:-1]) if len(convexHull) == 2: return Segment(convexHull[0], convexHull[1]) return Polygon(convexHull)
def get_polygon(self, n, R): p = Poly(n, R) if p not in self.cache: self.cache[p] = Polygon(n, R) return self.cache[p]
def test_construct(self): PolygonPiece(Polygon([[0, 0], [0, 10], [10, 0], [10, 10]]), [0, 0])
def main(): poly = Polygon(Point(0, 0), Point(0, 1), Point(1, 1)) print("Attemptine to print polygon.") print("Note: if this doesn't work you have a problem in either \ numVertices or in getVertex\n") print("Result should be: { (0,0) (0,1) (1,1) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing insertVertex with (1,0) and 5") print("Result should be: False") print("Result is: ",poly.insertVertex(Point(1, 0), 5)) print("Result should be: { (0,0) (0,1) (1,1) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing insertVertex with (1,0) and -1") print("Result should be: False") print("Result is: ",poly.insertVertex(Point(1,0),-1)) print("Result should be: { (0,0) (0,1) (1,1) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing insertVertex with (2,-1) and 3") print("Result should be: True") print("Result is: ",poly.insertVertex(Point(2, -1), 3)) print("Result should be: { (2,-1) (0,0) (0,1) (1,1) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing insertVertex with (1,0) and 3") print("Result should be: True") print("Result is: ",poly.insertVertex(Point(1, 0), 3)) print("Printing resulting polygon:") print("Result should be: { (2,-1) (0,0) (0,1) (1,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing findVertex with (1,1)") print("Result should be: 3") print("Result is: ",poly.findVertex(Point(1, 1)),"\n") print("Testing findVertex with (1,2)") print("Result should be: False") print("Result is: ",poly.findVertex(Point(1, 2)),"\n") print("Testing getVertex with -1") print("Result should be: False") print("Result is: ",poly.getVertex(-1),"\n") print("Testing getVertex with 5") print("Result should be: False") print("Result is: ",poly.getVertex(5),"\n") print("Testing deleteVertex with -1") print("Result should be: False") print("Result is: ",poly.deleteVertex(-1)) print("Result should be: { (2,-1) (0,0) (0,1) (1,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing deleteVertex with 6") print("Result should be: False") print("Result is: ",poly.deleteVertex(6)) print("Result should be: { (2,-1) (0,0) (0,1) (1,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing deleteVertex with 0") print("Result should be: True") print("Result is: ",poly.deleteVertex(0)) print("Printing resulting polygon:") print("Result should be: { (0,0) (0,1) (1,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("") print("Testing perimeter") print("Result should be: 4.0") print("Result is: ",poly.perimeter(),"\n") print("Testing deleteVertex with 2 and then 1 ") print("Result should be: True") print("Result is: ",poly.deleteVertex(2)) print("Printing resulting polygon:") print("Result should be: { (0,0) (0,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("Result should be: False") print("Result is: ",poly.deleteVertex(1)) print("Printing resulting polygon:") print("Result should be: { (0,0) (0,1) (1,0) }") print("Result is: ", end="") printPoly(poly) print("")
def test_get_position_returns_value_passed_in_construct(self): position = [12, 543] piece = PolygonPiece(Polygon([[0, 0], [0, 10], [10, 0], [10, 10]]), position.copy()) self.assertEqual(position, piece.get_position())
def test_polygon_used(self): polygon = Polygon([[0, 0], [0, 10], [10, 0], [10, 10]]) piece = PolygonPiece(polygon, [1, 2]) self.assertEqual(polygon, piece.get_polygon())
def ending_screen(): while True: yield from listen.event("ending_screen") globs.textboxes = [] polygons = [] polygons.append( Polygon(colors["peru"], [Vec(0, 3), Vec(0, 8), Vec(5, 8)])) polygons.append( Polygon(colors["mistyrose"], [Vec(2, 5), Vec(5, 8), Vec(8, 8), Vec(8, 5)])) polygons.append( Polygon(colors["lightsteelblue"], [Vec(0, 0), Vec(0, 3), Vec(2, 5), Vec(3, 5), Vec(8, 0)])) polygons.append( Polygon(colors["mediumaquamarine"], [Vec(3, 5), Vec(8, 0), Vec(8, 5)])) yield from listen.wait(0.4) globs.hud_polygons = [] for poly in polygons: globs.hud_polygons.append(poly) yield from listen.wait(0.2) thank_you = TextBox(font_loc + "Vitreous-Medium.ttf", size=30, color=Vec(0, 0, 0), pos=Vec(125, 600, -0.2)) thank_you.text = "Thank you for playing" globs.textboxes.append(thank_you) title_box = TextBox(font_loc + "Vitreous-Black.ttf", size=80, color=Vec(0.0, 0.0, 0.0), pos=Vec(120, 525, -0.2)) title_box.text = "Tesseland" globs.textboxes.append(title_box) name_boxes = [ TextBox(font_loc + "Vitreous-Medium.ttf", size=30, color=Vec(0, 0, 0), pos=Vec(150, 325 - 50 * k, -0.2)) for k in range(5) ] name_boxes[0].text = "Special guest level by Billy Rieger" name_boxes[1].text = "Special thanks to our playtesters" name_boxes[2].text = "Levi Walker" name_boxes[3].text = "Jayashree Srinivasan" name_boxes[4].text = "Stella Wang" globs.textboxes += name_boxes globs.bgcolor = Vec(0.0, 0.0, 0) while True: _, button, action, mods = yield from listen.on_mouse_button( globs.window) x, y = glfw.get_cursor_pos(globs.window) pt = mouse_coords(x, y) for poly in globs.hud_polygons: if is_point_in_poly(pt, poly): globs.hud_polygons.remove(poly) break if len(globs.hud_polygons) == 0: globs.textboxes = [] listen.dispatch("next_level") break
def build_3(self): """level 3""" pig = Pig(950, 320, self.space) pig.life = 25 self.pigs.append(pig) pig = Pig(885, 225, self.space) pig.life = 25 self.pigs.append(pig) pig = Pig(1005, 225, self.space) pig.life = 25 self.pigs.append(pig) p = (1100, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (1070, 152) self.beams.append(Polygon(p, 85, 20, self.space)) p = (1040, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (980, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (920, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (950, 152) self.beams.append(Polygon(p, 85, 20, self.space)) p = (1010, 180) self.beams.append(Polygon(p, 85, 20, self.space)) p = (860, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (800, 100) self.columns.append(Polygon(p, 20, 85, self.space)) p = (830, 152) self.beams.append(Polygon(p, 85, 20, self.space)) p = (890, 180) self.beams.append(Polygon(p, 85, 20, self.space)) p = (860, 223) self.columns.append(Polygon(p, 20, 85, self.space)) p = (920, 223) self.columns.append(Polygon(p, 20, 85, self.space)) p = (980, 223) self.columns.append(Polygon(p, 20, 85, self.space)) p = (1040, 223) self.columns.append(Polygon(p, 20, 85, self.space)) p = (890, 280) self.beams.append(Polygon(p, 85, 20, self.space)) p = (1010, 280) self.beams.append(Polygon(p, 85, 20, self.space)) p = (950, 300) self.beams.append(Polygon(p, 85, 20, self.space)) p = (920, 350) self.columns.append(Polygon(p, 20, 85, self.space)) p = (980, 350) self.columns.append(Polygon(p, 20, 85, self.space)) p = (950, 400) self.beams.append(Polygon(p, 85, 20, self.space)) self.number_of_birds = 4 if self.bool_space: self.number_of_birds = 8 self.one_star = 30000 self.two_star = 40000 self.three_star = 60000