def build_flat_plane(self): scene = Scene(self.screen, self.camera_position, COLOUR_WHITE, self.scale) count = 1 for x in range(count): for y in range(count): s = int(self.screen.width / count) cube_material = Material( (0 + int(random.random() * 100), 150 + int(random.random() * 100), int(1 * random.random())), # (0,0,255), (0.5, 0.5, 0.5), (0.8, 0.8, 0.8), (0.5, 0.5, 0.5), 50 ) rectangle = Rectangle( Point(x * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + y * s), Point(x * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + (y+1) * s), Point((x+1) * s - self.screen.width/2, -self.screen.height / 2, self.screen.distance + y * s), cube_material ) scene.add_object(rectangle) light_position = Point(-self.screen.width/4,-self.screen.height/2 + 50, self.screen.width * 4 + self.screen.distance) light = Light(light_position) scene.add_light(light) return scene
def __init__(self): super().__init__() self.setWindowTitle("Koch Curve - Iteration 0") self.setFixedSize(640, 480) self.iterations = [[Point(20, self.height() - 20), Point(self.width() - 20, self.height() - 20)]] self.current_iteration = 0 self.show()
def draw_coordinate_grid(self, num=(10, 10)): for x in xrange(int(self.field.left), 1 + int(self.field.right), 1): pygame.draw.line( self.screen, GRID_COLOR if x != 0 else AXES_COLOR, self.field.fit_on_screen(Point(x, self.field.bottom)), self.field.fit_on_screen(Point(x, self.field.top))) for y in xrange(int(self.field.bottom), 1 + int(self.field.top), 1): pygame.draw.line( self.screen, GRID_COLOR if y != 0 else AXES_COLOR, self.field.fit_on_screen(Point(self.field.left, y)), self.field.fit_on_screen(Point(self.field.right, y)))
def image_coordinate(self, space_coord): x, y = space_coord.x, space_coord.y # y direction is opposite return Point( self.origin_x + x * self.cell_size, self.origin_y - y * self.cell_size )
def searcher(self, position): # - Блят! да почему она не работает как надо?! # - Потому, что ты перепутал Х с У долбоёб! temp_list = [] point = False for stage in self.algorithm: if stage == "next": point = True if len(temp_list) != 0: self.priority = True self.move_list = temp_list return 'complite' continue if not (1 <= (self.position.col + stage.col) <= 8): continue if not (1 <= (self.position.row + stage.row) <= 8): continue if point == True: field = self.matrix[self.position.col + stage.col][self.position.row + stage.row] team = field.get_team() if field.get_team() == "free": temp_list.append( Point(self.position.col + stage.col, self.position.row + stage.row)) self.move_list = temp_list
def get_intersection_point(self, line): line_unit_vector = line.vector.unit() n_dot_u = self.plane_normal.dot_product(line_unit_vector) if not n_dot_u: # The line is parallel to the plane return None w = Vector.from_points(self.p1, line.point) s1 = -self.plane_normal.dot_product(w) / n_dot_u if s1 < 0: # The intersection point is on the wrong side of line.point return None intersection = Point(w.x + s1 * line_unit_vector.x + self.p1.x, w.y + s1 * line_unit_vector.y + self.p1.y, w.z + s1 * line_unit_vector.z + self.p1.z) a_m = Vector.from_points(self.p1, intersection) a_b = Vector.from_points(self.p1, self.p2) a_d = Vector.from_points(self.p1, self.p3) am_dot_ab = a_m.dot_product(a_b) ab_dot_ab = a_b.dot_product(a_b) am_dot_ad = a_m.dot_product(a_d) ad_dot_ad = a_d.dot_product(a_d) if (0 < am_dot_ab < ab_dot_ab) and (0 < am_dot_ad < ad_dot_ad): return intersection
def _point(self, x, y, z): rotated_x = x * self.side_length / 2 rotated_y = y * self.side_length / 2 rotated_z = z * self.side_length / 2 # apply z-axis rotation rotated_x, rotated_y = rotated_x * math.cos( self.z_rotation) - rotated_y * math.sin( self.z_rotation), rotated_x * math.sin( self.z_rotation) + rotated_y * math.cos(self.z_rotation) # apply y-axis rotation rotated_x, rotated_z = rotated_x * math.cos( self.y_rotation) + rotated_z * math.sin( self.y_rotation), -rotated_x * math.sin( self.y_rotation) + rotated_z * math.cos(self.y_rotation) # apply x-axis rotation rotated_y, rotated_z = rotated_y * math.cos( self.x_rotation) - rotated_z * math.sin( self.x_rotation), rotated_y * math.sin( self.x_rotation) + rotated_z * math.cos(self.x_rotation) return Point(rotated_x + self.center.x, rotated_y + self.center.y, rotated_z + self.center.z)
def reverse(self, algorithm): new_alg = [] for i in algorithm: if i == 'next': new_alg.append(i) else: new_alg.append(Point(-i.col, -i.row)) return new_alg
def graham_angle(p1, p2): ''' Not exactly the angle of the vector P₁P₂ but something that preserves the order (actually it flips it backwards but that's a good thing): if ∠P₁P₂ < ∠P₁P₃ then graham_angle(p1, p2) > graham_angle(p1, p3) ''' if p1 is p2: # this can only happen if p1 and p2 is self.min_point return -1.01 # just to guarantee the starting point is the last one v = Point(p2.x - p1.x, p2.y - p1.y) # monotonic with the angle, and faster to compute return (v.x * abs(v.x)) / squared_norm(v)
def BoundingBox(points): xmin, ymin = points[0].x, points[0].y xmax, ymax = xmin, ymin for p in points: if p.x < xmin: xmin = p.x elif p.x > xmax: xmax = p.x if p.y < ymin: ymin = p.y elif p.y > ymax: ymax = p.y return [ Point(xmin, ymin), Point(xmin, ymax), Point(xmax, ymax), Point(xmax, ymin) ]
def __init__(self, name=None, ico="·", team="neutral", location=None, matrix=None, position=None): Figure.__init__(self) self.name = name self.ico = ico self.move_list = [] self.team = team self.location = location #top bottom self.position = position self.matrix = matrix self.priority = False self.algorithm = [ Point(1, 1), Point(-1, 1), Point(-1, -1), Point(1, -1), "next", Point(1, 1), Point(1, -1) ] if location == "top": self.algorithm = self.reverse(self.algorithm)
def BoundingBoxDC(points): ''' points must be a list of Point, or whatever has both an x and a y member ''' if not isinstance(points, list): raise TypeError('points must be a list of Point') # We need to add the first point to the end points.append(points[0]) # We use a divide and conquer algorithm to find the extrema p_xmax = extremaDC(points, RIGHT) p_xmin = extremaDC(points, LEFT) p_ymax = extremaDC(points, UP) p_ymin = extremaDC(points, DOWN) xmin, xmax, ymin, ymax = p_xmin.x, p_xmax.x, p_ymin.y, p_ymax.y return [ Point(xmin, ymin), Point(xmin, ymax), Point(xmax, ymax), Point(xmax, ymin) ]
def __init__(self, x, y, mass=0.3, energy=0.1, x_vel=0.0, y_vel=0.0, inherited_phenotype=Phenotype()): """Cells begin with a specified position, without velocity, task or destination.""" # Position, Velocity and Acceleration vectors: self.pos = Point(float(x), float(y)) self.vel = Vector(x_vel, y_vel) self.acl = Vector(0.0, 0.0) # Brad's Satisfaction self.keyList = [] for i in range(0, 9): self.keyList.append([]) for j in range(0, 9): self.keyList[i].append(False) # Phenotypes: self.phenotype = inherited_phenotype # Stored for calc_variance's sake self.emRatio = inherited_phenotype.AI.emRatio # Energy/Mass gain ratio self.div_energy = self.phenotype.AI.div_energy # How much energy a cell needs to divide self.div_mass = self.phenotype.AI.div_mass # How much mass a cell needs to divide self.walk_force = self.phenotype.Static.walk_force self.density = self.phenotype.AI.density self.mutation_chance = self.phenotype.AI.mutation_chance # The likelihood of each phenotype mutating if self.phenotype.AI.color == None: self.color = Cell.colors.genColor() else: self.color = mutateColor(self.phenotype.AI.color) # Required for motion: self.energy = energy self.mass = mass self.exerted_force = Vector(0.0, 0.0) self.weight_management() # Required for logic: self.task = None self.destination = None self.destination_type = None # Task jumptable: self.TaskTable = {} self.TaskTable[None] = self.task_none self.TaskTable["FindingFood"] = self.task_finding_food self.TaskTable["GettingFood"] = self.task_getting_food
def task_finding_food(self): #closest piece of food close_food = World.food_at(self.pos, self.sight_range) #If there is any food within distance self.sight_range, get the closest one. if len(close_food) > 0: closest_food = min( close_food, key=partial( reduce, call, (attrgetter("pos"), attrgetter("distance_to"), partial( call, self.pos)))) # food: self.pos.distance_to(food.pos)) else: closest_food = None if len(close_food) == 0: """What the cell does should it be looking for food.""" #If you can't see food, accelerate in a random direction. x = random.uniform(0, World.width) y = random.uniform(0, World.height) self.destination = Point(x, y) self.destination_type = "Exploration" self.calc_force() else: #If there is any food within distance SIGHT_RANGE, get the closest one. #closest_food = min(close_food, key = lambda food: self.pos.distance_to(food.pos)) closest_food = min( close_food, key=partial( reduce, call, (attrgetter("pos"), attrgetter("distance_to"), partial( call, self.pos)))) # food: self.pos.distance_to(food.pos)) def stop_getting_food(food): """After the food gets eaten, stop trying to get it.""" self.destination = self.destination_type = self.task = None self.task = "GettingFood" self.destination_type = "Food" #weakref.proxy calls stop_getting_food when the food is destroyed. self.destination = weakref.proxy(closest_food.pos, stop_getting_food) self.food_target = weakref.ref(closest_food)
def _calculate_pixel_colour(self, x, y): screen_pixel_position = Point(x - self.screen.width / 2, y - self.screen.height / 2, self.screen.distance) camera_to_pixel_vector = Vector.from_points(self.camera_position, screen_pixel_position) camera_to_pixel = Line(camera_to_pixel_vector, self.camera_position) intersection_points = [] for rectangle in self.rectangles: intersection_point_for_current = rectangle.get_intersection_point(camera_to_pixel) if intersection_point_for_current: intersection_points.append((rectangle, intersection_point_for_current)) if intersection_points: closest_intersection = min(intersection_points, key=lambda p: p[1].distance_to(self.camera_position)) illumination = self._calculate_illumination(*closest_intersection) if illumination: return self._blinn_phong_colour(illumination) return self.background_colour
def fillinger(even=None, ico="·", uname="neutral", location=None): self.j += 1 self.i = 0 line = [None] for num in range(8): self.i += 1 if (num % 2 == 0) is even or even == None: line.append(FreeField(name="free", ico="·", team="free")) else: new = Checker(name="checker", ico=ico, team=uname, location=location, matrix=self.matrix, position=Point(self.j, self.i)) line.append(new) self.figure_set.append(new) return line
def paintEvent(self, _: QPaintEvent): qp = QPainter(self) qp.setPen(Qt.white) qp.setBrush(Qt.white) qp.drawRect(self.rect()) qp.drawImage(0, 0, self.img) center = Point(self.width() / 2, self.height() / 2) p1 = center + Vector(120, self.angle1).to_point() p2 = p1 + Vector(100, self.angle2).to_point() qp.setPen(QPen(Qt.black, 2)) qp.drawLine(*center, *p1) qp.drawLine(*p1, *p2) self.ip.setPen(QPen(Qt.black, 2)) self.ip.drawPoint(*p2) if self.last_point: self.ip.drawLine(*self.last_point, *p2) self.last_point = p2
def left_click_handler(event): global data if event.xdata is None or event.ydata is None: return point = Point(x=event.xdata, y=event.ydata) for p in data: # check if we clicked over a point, so we need to delete it if plot_distance_in_points(point, p) < plot_data.marker_radius: data.remove(p) break else: # if we didn't click over an existing point, we create a new one data.append(point) data.sort(key=lambda p: p.y, reverse=True) plot_data.clean_plot() if data: ax.scatter(*zip(*data), color='C0', zorder=10, linewidth=0) excluded = data[-1] ax.scatter(*excluded, color='C1', zorder=10, linewidth=0)
def move_like_virus(self): if not self.bool_moving: #if the cell isn't moving self.ticksLeft = 0 #then it's at the beginning - it's made 0 steps # print "Not movin', trying to move... " self.bool_moving = True #get ready to moves # print "pos = ", self.pos current_pos = self.pos #placeholder variable - bad habits from Java ref_pos = Point( 0, 0) #prepare a reference frame based on current location self.moving_path_as_string = "x^", self.curveTendency # print "future path = ", self.moving_path_as_string #end_of_eY = environment.Environment().height - current_pos.y #end_of_eX = environment.Environment().width - current_pos.x distanceTraveled = 0 #we haven't gone anywhere yet timeLeft = int(self.lifeSpan / 3) #viruses choose three paths in their life # print "time left = ", timeLeft while timeLeft > 0: #we begin adding positions in the virus' trajectory #nextPos_ref is the projected position based on a null reference frame nextPos_ref = Point( ref_pos.x + self.driftSpeed, ((ref_pos.x + self.driftSpeed)**self.curveTendency)) #print "for reference... ", nextPos_ref #realPos adds the reference frame position to the actual position realPos = Point(current_pos.x + nextPos_ref.x, current_pos.y + nextPos_ref.y) #print "adding... ", realPos self.moving_path.append(realPos) #the reference doesn't reset, but builds upon itself ref_pos = nextPos_ref #decrease steps left timeLeft -= 1 #now that movement has been predicted, we prepare for next movement #change curve which is being followed self.curveTendency = random.randint(1, 3) multi = random.uniform(-1, 1) #change direction possibly self.driftSpeed = self.maxSpeed * multi / abs(multi) #self.driftSpeed = random.uniform(-self.maxSpeed, self.maxSpeed) # print "curve = ", self.curveTendency # print "drift = ", self.driftSpeed #these should ever be used, but just in case if self.curveTendency > 10: self.curveTendency = 3 elif self.curveTendency <= 0: self.curveTendency = 1 else: #we're moving! # print "moving now" ticksMax = len(self.moving_path) #how many steps are to be taken? #print "path = ", self.moving_path # print "length of path = ", ticksMax # print "ticks left = ", self.ticksLeft #change x and y self.pos.x = self.moving_path[self.ticksLeft].x self.pos.y = self.moving_path[self.ticksLeft].y # print "moving to ", self.pos #remeber ticksLeft? Here it's used self.ticksLeft += 1 if self.ticksLeft == ticksMax: #when we've reached the end self.bool_moving = False #stop self.moving_path = [] #empty the path ticksLeft = 0 #reset ticksLeft
def get_test_point(self) -> Point: return Point(1, 2, 3)
def test_Point(self): test_p = Point(2,4) self.assertEqual(test_p + 3, Point(5,7)) pass
def __init__(self, x, y): self.energy = 0.5 self.pos = Point(x, y) self.pos.fit_to_torus()
from level import Level from obstacle import Obstacle from vector import Point WIDTH: int = 640 HEIGHT: int = 480 POPULATION_SIZE: int = 1000 CHECKPOINT_OPTIMIZATION_ROUNDS: int = 20 LEVEL: Level = [ Level(Point(WIDTH / 2, HEIGHT - 10), Point(WIDTH / 2, 10), [ Obstacle(Point(0, HEIGHT / 2 - 5), Point(WIDTH * 3 / 4, HEIGHT / 2 + 5)) ], []), Level(Point(WIDTH / 8, HEIGHT * 3 / 4), Point(WIDTH / 8, HEIGHT / 4), [ Obstacle(Point(0, HEIGHT / 2 - 5), Point(WIDTH * 7 / 8, HEIGHT / 2 + 5)) ], [Point(WIDTH * 15 / 16, HEIGHT / 2)]), Level(Point(WIDTH / 2, HEIGHT - 10), Point(WIDTH / 2, 10), [ Obstacle(Point(0, HEIGHT / 4 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT / 4 + 5)), Obstacle(Point(WIDTH * 3 / 4 - 5, HEIGHT / 4 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT * 5 / 8 - 5)), Obstacle(Point(WIDTH * 3 / 8, HEIGHT * 5 / 8 - 5), Point(WIDTH * 3 / 4 + 5, HEIGHT * 5 / 8 + 5)), Obstacle(Point(WIDTH / 4, HEIGHT * 3 / 8 - 5), Point(WIDTH * 5 / 8, HEIGHT * 3 / 8 + 5)), Obstacle(Point(WIDTH / 4 - 5, HEIGHT * 3 / 8 - 5), Point(WIDTH / 4 + 5, HEIGHT * 3 / 4 + 5)), Obstacle(Point(WIDTH / 4 - 5, HEIGHT * 3 / 4 - 5),
from vector import Point from bounding_box import BoundingBoxDC, BoundingBox output_filename = 'rectangulo.txt' if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('vertices', type=str, help='Archivo de vértices') parser.add_argument('metodo', type=str, help='Método a usar') args = parser.parse_args() # Read the vertex file with open(args.vertices, 'r') as f: points = [] for line in f.readlines(): points.append(Point(*map(float, line.strip().split(',')))) if args.metodo == 'inicial': box = BoundingBox(points) elif args.metodo == 'dyc': box = BoundingBoxDC(points) else: raise Exception('Método desconocido, los métodos pueden' \ 'ser "inicial" o "dyc" ') with open(output_filename, 'w') as f: for point in box: f.write(str(point) + '\n')
self.image.show() def save(self, filepath): if self.image is None: raise Exception("Can't save, call render() first") self.image.save(filepath) def image_coordinate(self, space_coord): x, y = space_coord.x, space_coord.y # y direction is opposite return Point( self.origin_x + x * self.cell_size, self.origin_y - y * self.cell_size ) def clear(self): del self._draw if __name__ == '__main__': g = Space2d(400, 400, 200, 200, 25) p1 = Point.origin() p2 = Point(1.1, 2.5) p3 = Point(4, 4) p4 = Point(3, 2) g.arrow(p1, p2) g.render() g.arrow(p1, p3, 'red') g.arrow(p1, p4) g.save('vectors.png')
from renderer import ImageRenderer from scene import Screen from scene_builder import SceneBuilder from vector import Point if __name__ == '__main__': SCREEN_WIDTH = 400 SCREEN_HEIGHT = 200 SCREEN_DISTANCE = 400 screen = Screen(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DISTANCE) CAMERA_X = 0 CAMERA_Y = SCREEN_HEIGHT CAMERA_Z = 0 camera_position = Point(CAMERA_X, CAMERA_Y, CAMERA_Z) SCALE = 1 scene = SceneBuilder(screen, camera_position, SCALE).build_flat_plane() ImageRenderer(scene).render('trace.png')