def __init__(self, surface, target, dna=None, start=None): self.surface = surface self.target = target x = surface.get_width() y = surface.get_height() if not start: self.start = Vector2D(x / 2, y - 100) else: self.start = start self.pos = self.start.add(Vector2D(0, -20)) self.velocity = Vector2D.zero_vector() gravity = Vector2D(0, 9.807) zero = Vector2D.zero_vector() self.acceleration = zero if dna: self.dna = dna else: self.dna = DNA() self.done = False self.detonated = False self.crashed = False self.step = 0 self.fitness = 0 self.distances = [] self.obstacle = pg.Rect((x * 0.30, y * 0.6), (x * 0.4, 20)) self.isParent = False self.min_dist = 99999
def update(self): gravity = Vector2D(0, 9.807) zero = Vector2D.zero_vector() if self.pos.distance(self.target) < self.min_dist: self.min_dist = self.pos.distance(self.target) # if self.pos.x > self.surface.get_width() or self.pos.x < 0: # self.crashed = True # # # if self.pos.y > self.surface.get_height() or self.pos.y < 0: # self.crashed = True if self.obstacle.collidepoint(*self.pos()): self.crashed = True if self.pos.distance(self.target) < 20: self.done = True self.pos = Vector2D(*self.target()) if not self.done: self.distances.append(self.pos.distance(self.target)) self.apply_force(gravity.div(200)) self.apply_force(self.dna.genes[self.step]) self.velocity = self.velocity.add(self.acceleration) self.pos = self.pos.add(self.velocity) self.acceleration = zero self.step += 1 else: pass
def fromPoints(cls, a: Union[Vector2D, tuple], b: Union[Vector2D, tuple]) -> linline: """Create a line from points with a limited domain. Create a line from two vectors or tuples. The domain will be limited to the two points including. Args: a: `Vector2D | tuple` Point A of the line b: `Vector2D | tuple` Point B of the line Returns: `linline` A linear line with a limited domain. """ if (type(a) == tuple): a = Vector2D.fromTuple(a) if (type(b) == tuple): b = Vector2D.fromTuple(b) rc = (b.y - a.y) / (b.x - a.x) p = a.y - rc * a.x limit = [a.x, b.x] print(f"Limit: {limit}") return cls(rc, p, sorted(limit))
def draw_calls(self): def call(method, *vargs, **kwargs): return method, vargs, kwargs calls = [] screen_offset = Vector2D((self.world_width / 2, 10)) screen_offset += self.position scale = 6 # rotate and position the rocket points = [Vector2D(xy) for xy in self.rocket_vertices] points = [ v.rotate_around(self.rotation_point, self.rotation) for v in points ] points = [scale * v + screen_offset for v in points] points = [(v.x, self.world_height - v.y) for v in points] calls.append( call("create_polygon", points, fill="blue", outline="lightgrey")) if self.engine_throttle: # rotate and position the engine flame points = [ Vector2D((x, y * self.engine_throttle)) for x, y in self.engine_flame_vertices ] points = [ v.rotate_around(self.rotation_point, self.rotation) for v in points ] points = [scale * v + screen_offset for v in points] points = [(v.x, self.world_height - v.y) for v in points] calls.append( call("create_polygon", points, outline="orange", fill="yellow")) # rotate and position the left and right thrusters points = [Vector2D(xy) for xy in self.thruster_positions] points = [ v.rotate_around(self.rotation_point, self.rotation) for v in points ] points = [scale * v + screen_offset for v in points] points = [(v.x, self.world_height - v.y) for v in points] if self.left_thruster_on: calls.append( call("create_oval", points[0][0] - 3, points[0][1] - 3, points[0][0] + 3, points[0][1] + 3, outline="orange", fill="yellow")) if self.right_thruster_on: calls.append( call("create_oval", points[1][0] - 3, points[1][1] - 3, points[1][0] + 3, points[1][1] + 3, outline="orange", fill="yellow")) return calls
def set_touchdown_position(self, x_position): self.position = Vector2D((x_position, 0)) self.velocity = Vector2D((0, 0)) self.acceleration = Vector2D((0, 0)) self.rotation = 0.0 self.rotation_speed = 0.0 self.rotation_acceleration = 0.0 self.crashed = False self.touchdown = True self.engine_throttle = 0.0 self.right_thruster_on = False self.left_thruster_on = False
class Physics(object): def __init__(self): self.position = Vector(0, 0) self.velocity = Vector(0, 0) self.acceleration = Vector(0, 0) self.mass = 0.0 def update(self): self.position = self.position.add(self.velocity) self.velocity = self.velocity.add(self.acceleration) self.acceleration.mul(0) def apply_force(self, force): self.acceleration = self.acceleration.add(force)
def __init__(self, x, y, energy=None): self.position = Vector2D(x, y) if energy: self.energy = energy else: self.energy = 100 self.eaten = False
def __mul__(self, other): self.checkType(Vector2D, other, 'Rotate2D can only multiply Vector2Ds.') cosAngle = cos(self.angle.radians) sinAngle = sin(self.angle.radians) return Vector2D(x=(cosAngle * other.x - sinAngle * other.y), y=(sinAngle * other.x + cosAngle * other.y))
def intersect(self, other: linline) -> Vector2D: """Calculate the point on which the two lines intersect The two lines intersect on one point. Intersect() calculates that point and give back a vector. Args: other: a linline; the line that intersects """ new_x = (other.b - self.b) / (self.rc - other.rc) return Vector2D(new_x, self.calc(new_x))
def main() -> None: res_x = 1024 res_y = 768 pygame.init() # screen = pygame.display.set_mode((res_x, res_y), pygame.FULLSCREEN) screen = pygame.display.set_mode((res_x, res_y)) screen_center = Vector2D(res_x / 2, res_y / 2) scale = res_y / (2.5 * ONE_AU) sun = Vector2D(0, 0) earth = Vector2D(0, ONE_AU) velocity = Vector2D(INITIAL_EARTH_VELOCITY, 0) acceleration = Vector2D(0, 0) delta_t = 3.65 * 86400 # in s. The delta_time for each frame. running = True screen.fill(BLACK) while running: #update force = F(EARTH_M, SUN_M, (earth - sun).norm) accel_norm = A(force, EARTH_M) acceleration = sun - earth acceleration.norm = accel_norm velocity = velocity + acceleration * delta_t earth = earth + velocity * delta_t # screen.fill(BLACK) draw(screen, earth * scale + screen_center, size=3, color=BLUE) draw(screen, sun * scale + screen_center, color=YELLOW) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: key = event.key if key in (pygame.K_q, pygame.K_ESCAPE): running = False
def update(self): self.framecounter += 1 if self.rocket.engine_throttle: # accelate engine_force = Vector2D( (0, .2 * self.rocket.engine_throttle)).rotate( self.rocket.rotation) self.rocket.apply_force(engine_force) if self.rocket.right_thruster_on: self.rocket.apply_rotation(0.005) if self.rocket.left_thruster_on: self.rocket.apply_rotation(-0.005) self.rocket.apply_gravity(0.1) self.rocket.update()
def show(self, heading): font = pg.font.SysFont('Comic Sans MS', 12) self.heading = heading pg.draw.circle(self.surface, (255, 255, 255), self.pos.floor()(), self.radius + 5, 1) x = self.pos.x + self.radius * math.cos(heading) y = self.pos.y + self.radius * math.sin(heading) end = Vector2D(x, y) pg.draw.line(self.surface, (255, 255, 255), self.pos(), end(), 1) title_text = font.render(self.title, True, (255, 255, 255)) self.surface.blit( title_text, (self.pos.x - self.radius, self.pos.y + self.radius + 10))
def __init__(self, lifespan=None, genes=None): if not lifespan: self.lifespan = 300 else: self.lifespan = lifespan if genes: self.genes = genes else: self.genes = [] force = Vector2D.zero_vector() for _ in range(self.lifespan): g_force = force.random_vector() g_force.set_magnitude(0.1) self.genes.append(g_force) self.isMutant = False
def intersect(self, other: linline) -> Vector2D: """Calculate the point on which the two lines intersect The two lines intersect on one point. Intersect() calculates that point and give back a vector. Args: other: a linline; the line that intersects Returns:\n `Vector2D` A vector if a match is found \n `None` None if no match is found """ new_x = (other.b - self.b) / (self.rc - other.rc) if self.limit[0] <= new_x <= self.limit[1] and other.limit[ 0] <= new_x <= other.limit[1]: return Vector2D(new_x, self.calc(new_x)) else: return None
def __init__(self, surface, pos, dna): super().__init__() self.surface = surface self.position = pos self.dna = dna self.energy = 500.0 self.age = 1.0 self.alive = True self.sex = random.choice([True, False]) self.max_size = dna.genes['max_size'] self.growth_rate = dna.genes['growth_rate'] self.max_speed = dna.genes['max_speed'] self.prev_acc = Vector2D(0, 0) self.state = "wandering" self.target = None self.targetReached = True self.lifespan = dna.genes['lifespan'] self.breeding_age = dna.genes['breeding_age'] self.breeding_cost = dna.genes['breeding_cost'] self.feeding_behaviour = dna.genes['feeding_behaviour']
pygame.draw.rect(screen, RED, ((vector.x-size/2, vector.y-size/2),(size, size))) res_x = 1024 res_y = 768 pygame.init() # screen = pygame.display.set_mode((res_x, res_y), pygame.FULLSCREEN) screen = pygame.display.set_mode((res_x, res_y)) def border(screen): pygame.draw.line(screen, RED, (0, 0), (res_x, 0), 1) pygame.draw.line(screen, RED, (0, 0), (0, res_y), 1) pygame.draw.line(screen, RED, (res_x, 0), (res_x, res_y), 1) pygame.draw.line(screen, RED, (0, res_y), (res_x, res_y), 1) position = Vector2D(10, 100) velocity = Vector2D(30, 0) acceleration = Vector2D(0, 20) delta_t = .1 running = True interrupt = False while running: #update border(screen) position = position + velocity*delta_t velocity = velocity + acceleration*delta_t if position.y > res_y: position.y = res_y velocity.y = -.7*velocity.y
def apply_gravity(self, gravity): if not self.touchdown: self.apply_force(Vector2D((0, -gravity)))
def __init__(self): self.position = Vector(0, 0) self.velocity = Vector(0, 0) self.acceleration = Vector(0, 0) self.mass = 0.0
if 'win' in sys.platform: try: ctypes.windll.shcore.SetProcessDpiAwareness(1) except: pass disp_bg_color = (0, 0, 0) disp_w = 1500 disp_h = 800 canvas = pg.display.set_mode((disp_w, disp_h)) canvas.fill(disp_bg_color) WIDTH = canvas.get_width() HEIGHT = canvas.get_height() pos = Vector2D(WIDTH / 2, HEIGHT / 2) arm = Armature(canvas, pos, 10, 0.5, 25, -math.pi / 2) seg = Segment(canvas, base=pos, length=10, theta=math.pi / 2) while True: # pg.time.wait(100) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit(1) if event.type == pg.MOUSEBUTTONDOWN: canvas.fill(disp_bg_color) # arm.draw() # arm.orbit(0.1) # seg.draw() # seg.rotate(0.1)
def move(self, arg): self.position = Vector2D(arg[0], arg[1])
def __init__(self): self.position = Vector2D(0, 0)
def calculate_end(self, theta): dx = math.cos(theta) dy = math.sin(theta) self.end = Vector2D(self.base.x + self.length * dx, self.base.y + self.length * dy)
font = pg.font.SysFont('Comic Sans MS', 12) disp_bg_color = (0, 0, 0) disp_w = 1500 disp_h = 800 canvas = pg.display.set_mode((disp_w, disp_h)) canvas.fill(disp_bg_color) WIDTH = canvas.get_width() HEIGHT = canvas.get_height() environment = { "food": [], "creatures": [ Creature( canvas, Vector2D(random.randrange(0, WIDTH), random.randrange(0, HEIGHT)), DNA()) for _ in range(50) ] } theta = 0 food_field_radius = 400 for _ in range(100): environment['food'].append( Food(disp_w / 2 + food_field_radius * math.cos(theta), disp_h / 2 + food_field_radius * math.sin(theta))) theta += .13 class Target: def __init__(self): self.position = Vector2D(0, 0)
WHITE = (255, 255, 255) BLUE = (0, 0, 255) def draw(screen, vector, size=10, color=RED): pygame.draw.rect(screen, color, ((vector.x - size / 2, vector.y - size / 2), (size, size))) res_x = 1024 res_y = 768 pygame.init() screen = pygame.display.set_mode((res_x, res_y), pygame.FULLSCREEN) sun = Vector2D(res_x / 2, res_y / 2) position = Vector2D(res_x / 2, res_y / 4) velocity = Vector2D(50, 0) acceleration = Vector2D(0, 0) delta_t = .1 running = True while running: #update acceleration = sun - position acceleration.norm = 20 velocity = velocity + acceleration * delta_t position = position + velocity * delta_t screen.fill(BLACK) draw(screen, position, color=BLUE)
def calculate_head(self, theta): dx = math.cos(theta) dy = math.sin(theta) self.base = Vector2D(self.end.x - self.length * dx, self.end.y - self.length * dy)
v = Vector(*data) / s for name, datum in zip(names, data): assert getattr(v, name) == datum / s @mark.parametrize(("Vector", "data"), ((Vector2D, (1, )), (Vector2D, (1, 2, 3)), (Vector('abc'), (1, 2)), (Vector('abcde'), range(10)))) def test_constructor_should_raise_TypeError_on_wrong_number_of_args( Vector, data): with raises(TypeError): Vector(*data) equality_data = ("l r result".split(), ((Vector2D(1, 2), Vector2D(1, 2), True), (Vector2D(1, 2), Vector2D(2, 1), False), (Vector3D(2, 3, 5), Vector3D(2, 3, 5), True), (Vector3D(2, 3, 5), Vector3D(2, 3, 4), False), (Vector('abcd')(9, 8, 7, 6), Vector('abcd')(9, 8, 7, 6), True))) @mark.parametrize(*equality_data) def test_vector_equality_operator_should_work(l, r, result): assert (l == r) == result @mark.parametrize(*equality_data) def test_vector_inequality_operator_should_work(l, r, result):
if 'win' in sys.platform: try: ctypes.windll.shcore.SetProcessDpiAwareness(1) except: pass disp_bg_color = (0, 0, 0) disp_w = 1500 disp_h = 800 canvas = pg.display.set_mode((disp_w, disp_h)) canvas.fill(disp_bg_color) WIDTH = canvas.get_width() HEIGHT = canvas.get_height() target = Vector2D(WIDTH * 0.5, HEIGHT * 0.5) population = Population(canvas, 100, target) isGrabbed = False while True: # pg.time.wait(100) for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit(1) if event.type == pg.MOUSEBUTTONDOWN: isGrabbed = True print(isGrabbed) if event.type == pg.MOUSEBUTTONUP: isGrabbed = False print(isGrabbed)
def fromVector(cls, direction, location=Vector2D(0, 0)): rc = direction.y / direction.x b = direction.x * location.y - direction.y * location.x return cls(rc, b)
def direction0(self): return Vector2D(x=-1, y=0)