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 __init__(self, x, y, mass=0.3, energy=0.1, x_vel=0.0, y_vel=0.0): """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) # Arbitrary constants: self.density = .005 # density is used to calculate radius # Required for motion: self.mass = 1 self.walk_force = 0.001 self.exerted_force = Vector(0.0, 0.0) self.weight_management() # Required for logic: self.task = None self.destination = None self.destination_type = None self.energy = energy # Task jumptable: self.TaskTable = {} self.TaskTable[None] = self.task_none self.TaskTable["FindingFood"] = self.task_finding_food self.TaskTable["GettingFood"] = self.task_getting_food # Misc: self.color = random_color()
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 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 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 __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 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 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 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 _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 __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 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 __init__(self, x, y, mass=0.3, energy=0.1, x_vel=0.0, y_vel=0.0, Phenotype=[2.0, 0.001, 0.5,0.6, 0.005, None, 0.0]): """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) # Phenotypes: self.phenotype = Phenotype # Stored for calc_variance's sake self.emRatio = Phenotype[0] # Energy/Mass gain ratio self.walk_force = Phenotype[1] self.div_energy = Phenotype[2] # How much energy a cell needs to divide self.div_mass = Phenotype[3] # How much mass a cell needs to divide self.density = Phenotype[4] if Phenotype[5] == None: self.color = random_color() Phenotype[5] = self.color else: self.color = Phenotype[5] self.mutation_chance = Phenotype[6] # The likelihood of each phenotype mutating # 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 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()
class Cell: def __init__(self, x, y, mass=0.3, energy=0.1, x_vel=0.0, y_vel=0.0): """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) # Arbitrary constants: self.density = .005 # density is used to calculate radius # Required for motion: self.mass = 1 self.walk_force = 0.001 self.exerted_force = Vector(0.0, 0.0) self.weight_management() # Required for logic: self.task = None self.destination = None self.destination_type = None self.energy = energy # Task jumptable: self.TaskTable = {} self.TaskTable[None] = self.task_none self.TaskTable["FindingFood"] = self.task_finding_food self.TaskTable["GettingFood"] = self.task_getting_food # Misc: self.color = random_color() # "Task" functions, i.e. the cell's activities during each tick, depending on its task. def task_none(self): """What the cell does should it have no task.""" self.task = "FindingFood" def task_finding_food(self): #closest piece of food close_food = environment.Environment().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, environment.Environment().width) y = random.uniform(0, environment.Environment().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 task_getting_food(self): """What the cell does when it has found food and is attempting to get it.""" #assert(len(environment.Environment().food_at(self.destination, 0)) != 0) distance_to_destination = self.pos.distance_to(self.destination) print self.destination print distance_to_destination if distance_to_destination > self.distance_to_start_slowing_down(): self.calc_force() for f in environment.Environment().food_at(self.pos, self.radius): self.eat(f) #if distance_to_destination <= self.radius: # self.eat(self.food_target()) def update_coords(self): """Updates the cell's position, velocity and acceleration in that order.""" prev_vel = Vector(self.vel.x, self.vel.y) self.pos += self.vel self.vel += self.acl #acl is change in velocity #displacement = (prev_vel + self.exerted_force/self.mass/2) #self.energy -= self.exerted_force*displacement #self.energy -= self.exerted_force*prev_vel self.acl = self.exerted_force - self.vel*abs(self.vel)*environment.Environment().resistance*(self.radius)/self.mass self.exerted_force = Vector(0.0,0.0) def calc_force(self): """Cells calculate how much force they are exerting (prior to resistance).""" self.exerted_force = (self.destination - self.pos)*self.walk_force / abs(self.destination - self.pos) #self.exerted_force = (self.destination - self.pos)*self.walk_force / (abs(self.destination - self.pos)*self.mass) if self.energy > self.walk_force: self.energy -= self.walk_force*1.0 else: self.mass -= self.walk_force*3.0 """Changes the cell's position based on its velocity, a.k.a. movement.""" def distance_to_start_slowing_down(self): """Calculates the distance from the destination that, once past, the cell ought to begin slowing down to reach its destination.""" return (abs(self.vel) * self.mass) / (environment.Environment().resistance * self.radius) def eat(self, f): #for f in environment.Environment().food_at(self.pos, self.radius): self.energy += f.energy/2.0 self.mass += f.energy/2.0 environment.Environment().remove_food(f) #The above line automatically resets our task and destination by calling stop_getting_food() def weight_management(self): self.radius = ( 3.0*self.mass*self.density / (4.0*math.pi) )**(1/2.0) self.sight_range = .2 + self.radius def life_and_death(self): if self.energy >= 0.5 and self.mass >= 0.6: #hardcoded threshold #stats of both babbyz newMass = self.mass/2.0 newEnergy = (self.energy - 3.0)/2.0 #make babby 1 x1 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y1 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) environment.Environment().add_cells_at_location(x1,y1,newMass,newEnergy,self.vel.x,self.vel.y) #make babby 2 x2 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y2 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) environment.Environment().add_cells_at_location(x2,y2,newMass,newEnergy,self.vel.x,self.vel.y) #make two cells at slightly different positions environment.Environment().remove_cell(self) elif self.mass <= 0.1: environment.Environment().kill_cell(self) def one_tick(self): """What a cell does every arbitrary unit of time.""" self.TaskTable[self.task]() self.update_coords() self.weight_management() self.life_and_death()
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')
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),
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
class Cell: def __init__(self, x, y, mass=0.3, energy=0.1, x_vel=0.0, y_vel=0.0, Phenotype=[2.0, 0.001, 0.5,0.6, 0.005, None, 0.0]): """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) # Phenotypes: self.phenotype = Phenotype # Stored for calc_variance's sake self.emRatio = Phenotype[0] # Energy/Mass gain ratio self.walk_force = Phenotype[1] self.div_energy = Phenotype[2] # How much energy a cell needs to divide self.div_mass = Phenotype[3] # How much mass a cell needs to divide self.density = Phenotype[4] if Phenotype[5] == None: self.color = random_color() Phenotype[5] = self.color else: self.color = Phenotype[5] self.mutation_chance = Phenotype[6] # The likelihood of each phenotype mutating # 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 #"Task" functions, i.e. the cell's activities during each tick, depending on its task. def task_none(self): """What the cell does should it have no task.""" self.task = "FindingFood" def task_finding_food(self): #closest piece of food close_food = environment.Environment().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, environment.Environment().width) y = random.uniform(0, environment.Environment().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 task_getting_food(self): """What the cell does when it has found food and is attempting to get it.""" #assert(len(environment.Environment().food_at(self.destination, 0)) != 0) distance_to_destination = self.pos.distance_to(self.destination) print self.destination print distance_to_destination if distance_to_destination > self.distance_to_start_slowing_down(): self.calc_force() for f in environment.Environment().food_at(self.pos, self.radius): self.eat(f) #if distance_to_destination <= self.radius: # self.eat(self.food_target()) def update_coords(self): """Updates the cell's position, velocity and acceleration in that order.""" prev_vel = Vector(self.vel.x, self.vel.y) self.pos += self.vel self.vel += self.acl #acl is change in velocity #displacement = (prev_vel + self.exerted_force/self.mass/2) #self.energy -= self.exerted_force*displacement #self.energy -= self.exerted_force*prev_vel self.acl = self.exerted_force - self.vel*abs(self.vel)*environment.Environment().resistance*(self.radius)/self.mass self.exerted_force = Vector(0.0,0.0) def calc_force(self): """Cells calculate how much force they are exerting (prior to resistance).""" self.exerted_force = (self.destination - self.pos)*self.walk_force / abs(self.destination - self.pos) #self.exerted_force = (self.destination - self.pos)*self.walk_force / (abs(self.destination - self.pos)*self.mass) if self.energy > self.walk_force: self.energy -= self.walk_force*1.0 else: self.mass -= self.walk_force*3.0 def distance_to_start_slowing_down(self): """Calculates the distance from the destination that, once past, the cell ought to begin slowing down to reach its destination.""" return (abs(self.vel) * self.mass) / (environment.Environment().resistance * self.radius) def eat(self, f): """Updates energy and mass according to set emRatio value and removes food item.""" #for f in environment.Environment().food_at(self.pos, self.radius): self.energy += f.energy/self.emRatio self.mass += f.energy - (f.energy/self.emRatio) environment.Environment().remove_food(f) #The above line automatically resets our task and destination by calling stop_getting_food() def weight_management(self): """Updates radius and sight range according to mass and density""" self.radius = ( 3.0*self.mass*self.density / (4.0*math.pi) )**(1/2.0) self.sight_range = .2 + self.radius def calculate_variance(self): """Setting variance for child cell. Called when cell duplicates""" #Currently only color varaince newphenotype = [] ##Below code needs to be rewritten## ###SOLUTION: Use fraction of acceptable margin as argument for randint modification### newcolor = (self.phenotype[5][0] + random.randint(-15,15),self.phenotype[5][1] + random.randint(-15,15), +\ self.phenotype[5][2] + random.randint(-15,15)) while (newcolor[0]+newcolor[1]+newcolor[2])/3>150 or newcolor[0]<0 or newcolor[0]>255 or newcolor[1]<0 or newcolor[1]>255 or newcolor[2]<0 or newcolor[2]>255: print newcolor,"sucks! Its average is either above 150 or one of its color values is impossible!" newcolor = (self.phenotype[5][0]+random.randint(-15,15), int(self.phenotype[5][1]+random.randint(-15,15)/1.15), self.phenotype[5][2]+random.randint(-15,15)) print newcolor,"should be fine, and if it isn't, F**K." for t in self.phenotype[:5]: newphenotype.append(t) newphenotype.append(newcolor) for t in self.phenotype[6:]: newphenotype.append(t) return newphenotype def life_and_death(self): """Checks if cell mass is great enough for division or low enough to cause death.""" """Brings new cells into existance or removes cell if conditions are true.""" if self.mass >= self.div_mass and self.energy >= self.div_energy: ##Removed Jack-ese## #Statistics for child cells newMass = self.mass/self.emRatio newEnergy = (self.energy - 3.0)/self.emRatio #Create child 1 x1 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y1 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) newPhenotype1 = self.calculate_variance() environment.Environment().cell_list.append(Cell(x1,y1,newMass,newEnergy,self.vel.x,self.vel.y,newPhenotype1)) #Create child 2 x2 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y2 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) newPhenotype2 = self.calculate_variance() environment.Environment().cell_list.append(Cell(x2,y2,newMass,newEnergy,self.vel.x,self.vel.y,newPhenotype2)) #Instantiates children at slightly different positions environment.Environment().remove_cell(self) #Kills cell elif self.mass <= 0.1: environment.Environment().kill_cell(self) def one_tick(self): """What a cell does every arbitrary unit of time.""" self.TaskTable[self.task]() self.update_coords() self.weight_management() self.life_and_death()
def get_test_point(self) -> Point: return Point(1, 2, 3)
class Cell(object): colors = Colors() 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 #"Task" functions, i.e. the cell's activities during each tick, depending on its task. def task_none(self): """What the cell defaults to in the instance of having no task.""" self.task = "FindingFood" 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 task_getting_food(self): """What the cell does when it has found food and is attempting to get it.""" distance_to_destination = self.pos.distance_to(self.destination) if distance_to_destination > self.distance_to_start_slowing_down(): self.calc_force() for f in World.food_at(self.pos, self.radius): self.eat(f) def update_coords(self): """Updates the cell's position, velocity and acceleration in that order.""" prev_vel = Vector(self.vel.x, self.vel.y) self.pos += self.vel if numpy.isnan(self.pos.x): self.pos.x = random.uniform(0, World.width) if numpy.isnan(self.pos.y): self.pos.y = random.uniform(0, World.width) self.vel += self.acl self.acl = self.exerted_force - self.vel * abs( self.vel) * World.resistance * (self.radius) / self.mass self.exerted_force = Vector(0.0, 0.0) def calc_force(self): """Cells calculate how much force they are exerting (prior to resistance).""" self.exerted_force = ( self.destination - self.pos) * self.walk_force / abs(self.destination - self.pos) if self.energy > self.walk_force: self.energy -= self.walk_force * 1.0 else: self.mass -= self.walk_force * 3.0 def distance_to_start_slowing_down(self): """Calculates the distance from the destination that, once past, the cell ought to begin slowing down to reach its destination.""" return (abs(self.vel) * self.mass) / (World.resistance * self.radius) def eat(self, f): """Updates energy and mass according to set emRatio value and removes food item.""" self.energy += f.energy / self.emRatio self.mass += f.energy - (f.energy / self.emRatio) World.remove_food(f) #The above line automatically resets our task and destination by calling stop_getting_food() def weight_management(self): """Updates radius and sight range according to mass and density""" self.radius = (3.0 * self.mass * self.density / (4.0 * math.pi))**(1 / 2.0) self.sight_range = .2 + self.radius def determine_phenotype(self): """Setting variance for child cell. Called when cell duplicates""" self.phenotype.mutate_phenotype() def life_and_death(self): """Checks if cell mass is great enough for division or low enough to cause death.""" """Brings new cells into existance or removes cell if conditions are true.""" if self.mass >= self.div_mass and self.energy >= self.div_energy: #Statistics for child cells newMass = self.mass / self.emRatio newEnergy = (self.energy - 3.0) / self.emRatio #Create child 1 x1 = random.uniform(self.pos.x - 0.01, self.pos.x + 0.01) y1 = random.uniform(self.pos.y - 0.01, self.pos.y + 0.01) self.determine_phenotype() World.cell_list.append( Cell(x1, y1, newMass, newEnergy, self.vel.x, self.vel.y, self.phenotype)) #Create child 2 x2 = random.uniform(self.pos.x - 0.01, self.pos.x + 0.01) y2 = random.uniform(self.pos.y - 0.01, self.pos.y + 0.01) self.determine_phenotype() World.cell_list.append( Cell(x2, y2, newMass, newEnergy, self.vel.x, self.vel.y, self.phenotype)) #Instantiates children at slightly different positions World.remove_cell(self) #Kills cell elif self.mass <= 0.1: World.kill_cell(self) def one_tick(self): """What a cell does every arbitrary unit of time.""" self.TaskTable[self.task]() self.update_coords() self.weight_management() self.life_and_death() def collideWith(self, foe): """assumed cells are colliding""" #get distance between cell radii as a vector selfPos = self.pos foePos = foe.pos xDiff = selfPos.x - foePos.x yDiff = selfPos.y - foePos.y dist = math.sqrt(xDiff**2 + yDiff**2) dist += 5 distVec = Vector(xDiff, yDiff) distVec.x = round(distVec.x, 3) distVec.y = round(distVec.y, 3) unitVec = distVec / dist unitVec.x = round(unitVec.x, 3) unitVec.y = round(unitVec.y, 3) #make a force vector forcApp = 1 / dist forcApp = round(forcApp, 3) forcVec = unitVec * forcApp forcVec.x = round(forcVec.x, 3) forcVec.y = round(forcVec.y, 3) #apply the force vector to other cell #the target's acceration is changed #by F/target's mass targetPushVec = forcVec / foe.mass targetPushVec.x = round(targetPushVec.x, 3) targetPushVec.y = round(targetPushVec.y, 3) foe.acl += -targetPushVec def guessedKey(self, vKey): vKeyO = vKey % 10 #gets the number in the ones place in vKey vKeyT = (vKey - vKeyO) / 10 #gets the number in the tens place in vKey if self.keyList[vKeyT][ vKeyO] == True: #if the cell already knows the key return True randN = round(random.random(), 2) * 100 randNO = randN % 10 randNT = (randN - randNO) / 10 #if the guess shares the same tens value and is at least 2 units away from the ones value if vKeyT == randNT and vKeyO < randNT + 2 and vKeyO >= randNT - 2: self.keyList[randNT][randNO] = True return True return False #if this is reached, all guesses have failed def randExponent(curve, maximum): x = random.randint(0, maximum * 100.0) / 100.0 base = (((maximum + curve) / curve))**(1.0 / maximum) y = curve * (base**x) - curve return y
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')
class Cell(object): colors = Colors() 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 #"Task" functions, i.e. the cell's activities during each tick, depending on its task. def task_none(self): """What the cell defaults to in the instance of having no task.""" self.task = "FindingFood" 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 task_getting_food(self): """What the cell does when it has found food and is attempting to get it.""" distance_to_destination = self.pos.distance_to(self.destination) if distance_to_destination > self.distance_to_start_slowing_down(): self.calc_force() for f in World.food_at(self.pos, self.radius): self.eat(f) def update_coords(self): """Updates the cell's position, velocity and acceleration in that order.""" prev_vel = Vector(self.vel.x, self.vel.y) self.pos += self.vel if numpy.isnan(self.pos.x): self.pos.x = random.uniform(0,World.width) if numpy.isnan(self.pos.y): self.pos.y = random.uniform(0,World.width) self.vel += self.acl self.acl = self.exerted_force - self.vel*abs(self.vel)*World.resistance*(self.radius)/self.mass self.exerted_force = Vector(0.0,0.0) def calc_force(self): """Cells calculate how much force they are exerting (prior to resistance).""" self.exerted_force = (self.destination - self.pos)*self.walk_force / abs(self.destination - self.pos) if self.energy > self.walk_force: self.energy -= self.walk_force*1.0 else: self.mass -= self.walk_force*3.0 def distance_to_start_slowing_down(self): """Calculates the distance from the destination that, once past, the cell ought to begin slowing down to reach its destination.""" return (abs(self.vel) * self.mass) / (World.resistance * self.radius) def eat(self, f): """Updates energy and mass according to set emRatio value and removes food item.""" self.energy += f.energy/self.emRatio self.mass += f.energy - (f.energy/self.emRatio) World.remove_food(f) #The above line automatically resets our task and destination by calling stop_getting_food() def weight_management(self): """Updates radius and sight range according to mass and density""" self.radius = ( 3.0*self.mass*self.density / (4.0*math.pi) )**(1/2.0) self.sight_range = .2 + self.radius def determine_phenotype(self): """Setting variance for child cell. Called when cell duplicates""" self.phenotype.mutate_phenotype() def life_and_death(self): """Checks if cell mass is great enough for division or low enough to cause death.""" """Brings new cells into existance or removes cell if conditions are true.""" if self.mass >= self.div_mass and self.energy >= self.div_energy: #Statistics for child cells newMass = self.mass/self.emRatio newEnergy = (self.energy - 3.0)/self.emRatio #Create child 1 x1 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y1 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) self.determine_phenotype() World.cell_list.append(Cell(x1,y1,newMass,newEnergy,self.vel.x,self.vel.y,self.phenotype)) #Create child 2 x2 = random.uniform(self.pos.x-0.01,self.pos.x+0.01) y2 = random.uniform(self.pos.y-0.01,self.pos.y+0.01) self.determine_phenotype() World.cell_list.append(Cell(x2,y2,newMass,newEnergy,self.vel.x,self.vel.y,self.phenotype)) #Instantiates children at slightly different positions World.remove_cell(self) #Kills cell elif self.mass <= 0.1: World.kill_cell(self) def one_tick(self): """What a cell does every arbitrary unit of time.""" self.TaskTable[self.task]() self.update_coords() self.weight_management() self.life_and_death() def collideWith(self, foe): """assumed cells are colliding""" #get distance between cell radii as a vector selfPos = self.pos foePos = foe.pos xDiff = selfPos.x - foePos.x yDiff = selfPos.y - foePos.y dist = math.sqrt(xDiff**2 + yDiff**2) dist += 5 distVec = Vector(xDiff, yDiff) distVec.x = round(distVec.x,3) distVec.y = round(distVec.y,3) unitVec = distVec/dist unitVec.x = round(unitVec.x, 3) unitVec.y = round(unitVec.y, 3) #make a force vector forcApp = 1/dist forcApp = round(forcApp, 3) forcVec = unitVec * forcApp forcVec.x = round(forcVec.x, 3) forcVec.y = round(forcVec.y, 3) #apply the force vector to other cell #the target's acceration is changed #by F/target's mass targetPushVec = forcVec/foe.mass targetPushVec.x = round(targetPushVec.x, 3) targetPushVec.y = round(targetPushVec.y, 3) foe.acl += -targetPushVec def guessedKey(self, vKey): vKeyO = vKey % 10 #gets the number in the ones place in vKey vKeyT = (vKey - vKeyO)/10 #gets the number in the tens place in vKey if self.keyList[vKeyT][vKeyO] == True : #if the cell already knows the key return True randN = round(random.random(),2)*100 randNO = randN % 10 randNT = (randN - randNO)/10 #if the guess shares the same tens value and is at least 2 units away from the ones value if vKeyT == randNT and vKeyO < randNT + 2 and vKeyO >= randNT - 2: self.keyList[randNT][randNO] = True return True return False #if this is reached, all guesses have failed def randExponent(curve,maximum): x=random.randint(0,maximum*100.0)/100.0 base=(((maximum+curve)/curve))**(1.0/maximum) y=curve*(base**x)-curve return y
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')