def move_tangent_line(self): print "IN TANGENT LINE" slope_to_center = ( -self.circumnavigation_obstacle.center.y + self.position.y) / ( -self.circumnavigation_obstacle.center.x + self.position.x) tangent_line_slope = (-1 / slope_to_center) if (self.position.y > self.circumnavigation_obstacle.center.y): self.direction = Vector2D(1, tangent_line_slope) elif (self.position.y < self.circumnavigation_obstacle.center.y and self.position.x < self.circumnavigation_obstacle.center.x): self.direction = Vector2D(-1, abs(tangent_line_slope)) else: self.direction = Vector2D(-1, -abs(tangent_line_slope)) self.direction.normalize() self.visited_points.append(Point(self.position.x, self.position.y)) self.distance_traveled += 1 self.circumnavigation_travel += 1 if (self.position.distance_to(self.goal) < self.circumnavigation_closest_point.distance_to(self.goal)): self.circumnavigation_closest_point = Point( self.position.x, self.position.y) self.position.x += self.direction.x self.position.y += self.direction.y
def targetPrey(predator, boids): if predator.currHunger <= PredatorBehavior.maxKillTimeout: return Vec() closestBoid = None closestBoidDistance = None preyVec = Vec() for boid in boids: distance = predator.position.distanceTo(boid.position) if distance < closestBoidDistance or closestBoidDistance is None: closestBoidDistance = distance closestBoid = boid if closestBoid is not None: preyVec = closestBoid.position.subVec(predator.position) preyVec = preyVec.setMag(PredatorBehavior.maxVelocity) preyVec = preyVec.subVec(predator.velocity) preyVec = preyVec.limit(PredatorBehavior.maxForce) return preyVec
def randomise(self): # create points self.points = [] for y in range(self.h + 1): for x in range(self.w + 1): vec = Vector2D((x * self.resolution), (y * self.resolution)) vec.data["state"] = randint(0, 1) self.points.append(vec) # create squares self.grid = [] for y in range(self.h + 1): for x in range(self.w + 1): vec = Vector2D((x * self.resolution) + self.resolution / 2, (y * self.resolution) + self.resolution / 2) dist = [] for point in self.points: dist.append(int(point.dist(vec))) dist = min(dist) temp = [] for point in self.points: if int(point.dist(vec)) == dist: temp.append(point) if len(temp) == 4: self.grid.append(temp)
def make_particles(width, height, particles_count, cut_off_distance, velocity_mul=0): cols_count = int((particles_count * width / height)**0.5) rows_count = int(particles_count // cols_count) delta_w = width / cols_count delta_h = height / rows_count particles = [] for i in range(rows_count): for j in range(cols_count): particle = Particle(center=Vector2D(delta_w * j + 0.5 * delta_w, delta_h * i + 0.5 * delta_h), radius=0.5, velocity=Vector2D(random() - 0.5, random() - 0.5) * velocity_mul) particles.append(particle) cells = ParticlesCells(width, height, cut_off_distance) cells.update_cells(particles) return cells
def __init__(self, position=(0, 0)): super(Player, self).__init__() self.animation = { "right": Animation((pygame.transform.rotate(sprite, -90) for sprite in settings.SPRITES["pacman"]), 0.17), "left": Animation((pygame.transform.rotate(sprite, 90) for sprite in settings.SPRITES["pacman"]), 0.17), "up": Animation((pygame.transform.rotate(sprite, 180) for sprite in settings.SPRITES["pacman"]), 0.17), "down": Animation((pygame.transform.rotate(sprite, 0) for sprite in settings.SPRITES["pacman"]), 0.17), "death": OneTimeAnimation(settings.SPRITES["death"], 0.17) } self.image = self.animation["right"].sprites[0] self.rect = self.image.get_rect(center=position) self.position = Vector2D(*position) self.tile_index = settings.get_tile_index(position) self.moving = False self.target = self.position self.direction = Vector2D(0, 0) self.radius = self.rect.width // 3 self.energized = True self.dead = False
def from_grid(self, grid): # create points self.points = [] for y in range(self.h + 1): for x in range(self.w + 1): vec = Vector2D((x * self.resolution), (y * self.resolution)) vec.data["state"] = not grid[y][x] self.points.append(vec) # create squares self.grid = [] for y in range(self.h + 1): for x in range(self.w + 1): vec = Vector2D((x * self.resolution) + self.resolution / 2, (y * self.resolution) + self.resolution / 2) dist = [] for point in self.points: dist.append(int(point.dist(vec, use_sqrt=False))) dist = min(dist) temp = [] for point in self.points: if int(point.dist(vec, use_sqrt=False)) == dist: temp.append(point) if len(temp) == 4: self.grid.append(temp)
def tree(self, x, y, rootheight, depth): y2 = y - rootheight if self.isgrowdown: y2 = y + rootheight self.canvas.line((x, y, x, y - rootheight), fill=self.rgb, width=self.lwidth) self.__branch(Vector2D(x, y), Vector2D(x, y - rootheight), depth)
def init(): canvas = document.getElementById("gl-canvas") global gl gl = WebGLUtils.setupWebGL(canvas) if not gl: alert("WebGL isn't available") vertices = [ Vector2D(-1, -1).as_list(), Vector2D(1, 1).as_list(), Vector2D(1, -1).as_list(), Vector2D(-1, 1).as_list(), ] gl.viewport(0, 0, canvas.width, canvas.height) gl.clearColor(1.0, 1.0, 1.0, 1.0) program = initShaders(gl, "vertex-shader", "fragment-shader") gl.useProgram(program) vPositionLoc = gl.getAttribLocation(program, "vPosition") bufferId = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, bufferId) gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW) gl.enableVertexAttribArray(vPositionLoc) gl.vertexAttribPointer(vPositionLoc, 2, gl.FLOAT, False, 0, 0) render()
def click(event): global x, y, click_flag, vecs if click_flag: # Criar o vetor vec = Vector2D(x, y, event.x, event.y) vec.name = "v" + str(len(vecs) + 1) vec.color = "black" vecs.append(vec) # Desenhar o vetor na tela draw_vec(vec) # Desenha o vetor soma if (len(vecs) > 1): sum_vec = Vector2D(vecs[0].x1, vecs[0].y1, 0, 0) for vect in vecs: sum_vec += vect sum_vec.name = "vR" sum_vec.color = "#c314ce" remove_vec( sum_vec ) # Se achar um vetor já desenhado com essa tag, deleta ele draw_vec(sum_vec, False) # Setar ponto de origem para o próximo vetor x, y = event.x, event.y else: # Setar a origem x, y = event.x, event.y click_flag = True
def main(): v1 = Vector2D(2, -2) print(v1) v2 = Vector2D(2, 3) print(v2) v3 = v1 + v2 print(v3) print('Hello world')
def draw(self, screen: pygame.Surface) -> None: screen.blit(self.image, tuple(self.top_left_point)) scrrect = Rect(Color(0, 0, 0), Vector2D(0, 0), Vector2D(screen.get_width(), screen.get_height()), 0) radius = self.width / 2 if self.center.x - radius < 0 or self.center.x + radius > screen.get_width(): self.speed = Vector2D(-self.speed.x, self.speed.y) if self.center.y - radius < 0 or self.center.y + radius > screen.get_height(): self.speed = Vector2D(self.speed.x, -self.speed.y)
def main(): v1 = Vector2D(2, -2) print(v1) v2 = Vector2D(2, 3) print(v2) v3 = v1 + v2 print(v3) print("Hello world") print("Another world!")
def calc_impulse(self, n, vr, r1, r2, m1, m2, I1, I2, e): top = vr.scaled(-(1.0 + e)).dot(n) bottom = (1/m1)*(n.dot(r1)**2) + (1/m2)*(n.dot(r2)**2) z1 = r1.cross2(n)*(1/I1) z2 = r2.cross2(n)*(1/I2) bottom += (Vector2D.cross3(z1, r1).add(Vector2D.cross3(z2,r2))).dot(n) return top/bottom
def main(): app = Game(None) platform = Platform(Color(255, 0, 0), Vector2D(350, 550), Vector2D(450, 600), 0) app.add_game_object(platform) app.add_handler(platform.left_down) app.add_handler(platform.left_up) app.add_handler(platform.right_down) app.add_handler(platform.right_up) app.run()
def __init__(self, position, mass, radius): self.position = position self.velocity = Vector2D(0, 0) self.force = Vector2D(0, 0) self.mass = mass self.radius = radius self.collider_radius = self.radius * 0.5 self.is_dynamic = True self.to_delete = False self.check_collisions = True
def snowflake(self, x, y, r): center = Vector2D(x, y) radius = Vector2D(r, 0) points = [ center + radius.rotate(math.radians(-45)), center + radius.rotate(math.radians(90)), center + radius.rotate(math.radians(-135)) ] self.curve(points[0], points[2]) self.curve(points[1], points[0]) self.curve(points[2], points[1])
def contains(self, point): #return pygame.rect.Rect(self.left, self.top, self.width, self.height).collidepoint(point.x, point.y) # p = point, a,b,d = corners on rectangles top_left = Point(self.left, self.top) top_right = Point(self.left + self.width, self.top) bottom_left = Point(self.left, self.top + self.height) tLeft_to_point = Vector2D.from_points(top_left, point) tLeft_to_tRight = Vector2D.from_points(top_left, top_right) tLeft_to_bLeft = Vector2D.from_points(top_left, bottom_left) return (0 < tLeft_to_point.dot(tLeft_to_tRight) and tLeft_to_point.dot(tLeft_to_tRight) < tLeft_to_tRight.dot(tLeft_to_tRight)) and (0 < tLeft_to_point.dot(tLeft_to_bLeft) and tLeft_to_point.dot(tLeft_to_bLeft) < tLeft_to_bLeft.dot(tLeft_to_bLeft))
def reset_game(self): if self.score > self.highScore: self.highScore = self.score self.score = 0 self.snakeElementsToBeAdded = 0 self.snakeElements.clear() self.pushedKeys.clear() center = self.mapSize // 2 head = SnakeElement(self.snakeColour, Vector2D(center, center), Vector2D(0, -1)) self.snakeElements.append(head) for _ in range(2): add_next_element(self.snakeElements) place_egg(self)
def __init__(self, center: Vector2D, radius: float, velocity: Vector2D = None, color=None): Particle.last_particle_id += 1 self.id = Particle.last_particle_id self.radius = radius self.center = center if (velocity is None): velocity = Vector2D() self.velocity = velocity self.color = color self.acceleration = Vector2D() self.potential = 0.0 self.mass = 1
def __init__(self, color: Color, top_left: Vector2D, bottom_right: Vector2D, brush_width: int): super(Platform, self).__init__(color, top_left, bottom_right, brush_width) self.left_down = KeyboardHandler(self.on_left_key_down, pygame.KEYDOWN, [ord('a')]) self.left_up = KeyboardHandler(self.on_left_key_up, pygame.KEYUP, [ord('a')]) self.right_down = KeyboardHandler(self.on_right_key_down, pygame.KEYDOWN, [ord('d')]) self.right_up = KeyboardHandler(self.on_right_key_up, pygame.KEYUP, [ord('d')]) self.max_abs_speed = Vector2D(7, 0) self.current_shift = Vector2D(0, 0) self.current_speed = Vector2D(0, 0)
def add_next_element(snakeElements): snakeElements.append(deepcopy(snakeElements[-1])) tail = snakeElements[-1] if tail.colour[2] < 255: tail.colour[2] = tail.colour[2] + 1 if tail.velocity.x > 0: tail.position -= Vector2D(1, 0) elif tail.velocity.x < 0: tail.position += Vector2D(1, 0) elif tail.velocity.y > 0: tail.position -= Vector2D(0, 1) elif tail.velocity.y < 0: tail.position += Vector2D(0, 1)
def check_collisions(self, obj1, obj2, dt): ''' Check for collision between two objects This would be better if it used the Separating axis theorem instead of the naive way of checking for intersections for all faces for both polygons. http://en.wikipedia.org/wiki/Hyperplane_separation_theorem ''' collision = None geometry1 = obj1.get_oriented_geometry(obj1.next_orientation) geometry2 = obj2.get_oriented_geometry(obj2.next_orientation) # app for obj1 hitting obj2 faces = geometry2[1] verts = geometry1[0] i = 0 for vert in verts: a1 = vert.addition(obj1.position) a2 = a1.addition(obj1.vert_abs_velocity(i).scaled(dt)) i += 1 for face in faces: b1 = face[0].addition(obj2.next_position) b2 = face[1].addition(obj2.next_position) col = Vector2D.intersection(a1, a2, b1, b2) if col != None and (collision == None or col[1] < collision.time): normal = face[1].addition(face[0].reversed()).normal() # collision normal collision = Dynamics.Collision(obj1, obj2, col[0], normal, col[1]) return collision
def __init__(self, pos=None, vel=None, color=None): self._pos = pos or Vector2D( randint(0, Config.SCREEN_X), randint(0, Config.SCREEN_Y)) angle = uniform(-math.pi, math.pi) self.vel = vel or Vector2D( Config.MAX_SPEED * math.cos(angle), Config.MAX_SPEED * math.sin(angle)) self.color = color or ( randint(99, 150), randint(99, 255), randint(200, 255)) self.turn = 0
def teleport(self, tile_map): """Teleports the ghost between one of the tiles outside the tunnel, depending on the current tile position.""" row = -2 if self.tile_index[1] == 29 else 28 self.handle_tile_content(tile_map[(self.tile_index[0], row)], tile_map) self.prev_tile_index = self.tile_index self.tile_index = (self.tile_index[0], row) self.position = Vector2D(*settings.get_position(self.tile_index))
def _spawnbrOfBoids(): # Get a list of random and non-overlapping position tuples spawnPositions = BoidEcosystem._getBoidSpawns() logbook.log("[START] Initializing {} new boids".format( BoidEcosystem.nbrOfBoids)) # For each new boid: for n in range(BoidEcosystem.nbrOfBoids): # Get new boid at next spawn position: newBoid = BoidEcosystem._getNewBoid(spawnPositions[n]) newBoid.ID = n # Breathe some life into it by setting a random velocity newBoid.velocity = Vec.getRandVec(BoidBehavior.maxVelocity) # Add to new list of boids BoidEcosystem.boids.append(newBoid) # logbook.log("[START] New Boid: {}".format(newBoid.getStats())) # Log the geno and phenotype data bStats.logGenotype(newBoid.getChromosomes()) bStats.logPhenotype(newBoid.getPhenotypes())
def __init__(self, environment): self.environment = environment self.images = Images(FilePath("data").child("img2")) self.images.load() self.actions = deque() self.action = None self.center = Vector2D((0, 0))
def logOrder(orientationVectors): vectorSum = Vec() for v in orientationVectors: vectorSum = vectorSum.addVec(v) vectorSum = vectorSum.divScalar( float(len(orientationVectors)) ) order = vectorSum.getMag() BoidMetrics.orderOutput.write("{}\t{}\t{:.3f}\n".format( BoidMetrics.generation, BoidMetrics.ticker, order)) BoidMetrics.orderOutput.flush()
def string2particle(str): args = str.split(';') return Particle( #int(args[0]), center=Vector2D( float(args[1]), float(args[2]), ), radius=0.5, velocity=Vector2D( float(args[3]), float(args[4]), ) # float(args[5]), # float(args[6]), # float(args[7]), )
def _spawnbrOfPredators(): for predator in range(0, BoidEcosystem.nbrOfPredators): randPos = BoidEcosystem._getRandPos() newPred = PredatorBoid(randPos) newPred.velocity = Vec.getRandVec(PredatorBehavior.maxVelocity) BoidEcosystem.predators.append(newPred)
def screenCoord(self, p): width = self.screen.get_width() height = self.screen.get_height() (cx, cy) = self.screen.get_rect().center return Vector2D((((p.x - self.center[0]) / (self.environment.width / 2)) * width) + cx, (((p.y - self.center[1]) / (self.environment.height / 2)) * height) + cy)
def move(self): if self.state == State.Motion: scan_result = self.scan_for_obstacles() if scan_result == None: self.visited_points.append(Point(self.position.x, self.position.y)) self.position.x += self.direction.x self.position.y += self.direction.y self.updateHeading() self.distance_traveled += 1 else: # in range of an obstacle self.circumnavigation_obstacle = scan_result self.state = State.Circumnavigation self.found_closest_point = False self.circumnavigation_end_point = Point(self.position.x, self.position.y) self.circumnavigation_closest_point = Point(self.position.x, self.position.y) self.circumnavigation_travel = 0 self.circumnavigation_perimeter = 2 * math.pi * self.circumnavigation_obstacle.radius self.circumnavigation_start = Point(self.position.x, self.position.y) self.move_tangent_line() else: # circumnavigating if self.circumnavigation_travel > self.circumnavigation_perimeter: self.position.x = self.circumnavigation_start.x self.position.y = self.circumnavigation_start.y self.circumnavigation_travel = 0 if self.position == self.circumnavigation_end_point and not self.found_closest_point: self.circumnavigation_end_point = self.circumnavigation_closest_point self.found_closest_point = True self.visited_points = [] elif self.position == self.circumnavigation_end_point and self.found_closest_point: self.state = State.Motion self.direction = Vector2D.from_points(self.position, self.goal) self.direction.normalize() self.circumnavigation_travel = 0 self.circumnavigation_perimeter = 0 self.circumnavigation_start = None self.circumnavigation_obstacle = None self.found_closest_point = False self.circumnavigation_end_point = None self.circumnavigation_closest_point = None else: # normal circumnavigation self.move_tangent_line()
def test_mul(self): ''' Tests the multiplication operator. ''' result1 = self.v1 * 5 expected_result1 = Vector2D(0.0, 0.0) self.assertEqual(result1, expected_result1) result2 = self.v1 * self.v2 expected_result2 = 0.0 self.assertEqual(result2, expected_result2)
def clear_path(self): # get vector from point to goal heading_to_goal = Vector2D.from_points(self.point, self.goal) #heading_to_goal.normalize() point = Point(self.position.x + heading_to_goal.x, self.position.y + heading_to_goal.y) # check next point if in obstacle print "clear_path ??? {0}".format(not self.point_on_boundaries(point)) return not self.point_on_boundaries(point)
def go_left(snakeElements): element_iterator = iter(snakeElements) head = next(element_iterator) if head.velocity.x == 0: change_position_cords = head.position head.velocity.set_values(-1, 0) for element in element_iterator: element.moves_to_make.append( Move(change_position_cords, Vector2D(-1, 0)))
def contains(self, point): #return pygame.rect.Rect(self.left, self.top, self.width, self.height).collidepoint(point.x, point.y) # p = point, a,b,d = corners on rectangles top_left = Point(self.left, self.top) top_right = Point(self.left + self.width, self.top) bottom_left = Point(self.left, self.top + self.height) tLeft_to_point = Vector2D.from_points(top_left, point) tLeft_to_tRight = Vector2D.from_points(top_left, top_right) tLeft_to_bLeft = Vector2D.from_points(top_left, bottom_left) return (0 < tLeft_to_point.dot(tLeft_to_tRight) and tLeft_to_point.dot(tLeft_to_tRight) < tLeft_to_tRight.dot(tLeft_to_tRight)) and ( 0 < tLeft_to_point.dot(tLeft_to_bLeft) and tLeft_to_point.dot(tLeft_to_bLeft) < tLeft_to_bLeft.dot(tLeft_to_bLeft))
def move(self): if self.state == State.Circumnavigation: if (self.on_m_line()) and self.clear_path() and not (self.position.x, self.position.y) in self.jump_points: self.state = State.Motion self.direction = Vector2D.from_points(self.position, self.goal) self.direction.normalize() self.jump_points.append((self.position.x, self.position.y)) self.position.x += self.direction.x self.position.y += self.direction.y elif self.in_obstacle() or not self.on_obstacle_boundary() or self.hasVisited(): # go back one step, and turn 90 degrees print "circumnavigating but not on boundary of obstacle, or inside.or repeat point" self.position.x -= self.direction.x self.position.y -= self.direction.y self.visited_points.pop(len(self.visited_points)-1) new_heading = math.radians(round(math.degrees(math.atan2(self.direction.y, self.direction.x))) + 90) print " NEW HEADING -> {0}".format(new_heading) self.direction = Vector2D(math.cos(new_heading), math.sin(new_heading)) else: print "normal circumnavigate" self.visited_points.append(Point(self.position.x, self.position.y)) self.position.x += self.direction.x self.position.y += self.direction.y self.distance_traveled += 1 elif not self.in_obstacle() and not self.on_obstacle_boundary(): self.visited_points.append(Point(self.position.x, self.position.y)) self.position.x += self.direction.x self.position.y += self.direction.y self.updateHeading() self.distance_traveled += 1 self.state = State.Motion print "not on obstacle!" else: # new obstacle..begin circumnavigation new_heading = math.radians(round(math.degrees(math.atan2(self.direction.y, self.direction.x))) + 90) print " NEW HEADING -> {0}".format(new_heading) self.direction = Vector2D(math.cos(new_heading), math.sin(new_heading)) #self.direction.rotate(math.pi/2) self.visited_points.append(Point(self.position.x, self.position.y)) # set 'end point' and variable for 'closest point' self.position.x += 2 * self.direction.x self.position.y += 2 * self.direction.y self.distance_traveled += 1 self.state = State.Circumnavigation
def __init__(self, obstacles, start, goal): self.jump_points = [] slope_vector = Vector2D.from_points(start, goal) if slope_vector.x == 0: self.slope = None else: self.slope = slope_vector.y/slope_vector.x self.point = Point(goal.x, goal.y) super(BugTwo, self).__init__(obstacles, start, goal)
def __init__(self, obstacles, start, goal): self.obstacles = obstacles self.position = start self.goal = goal self.direction = Vector2D.from_points(start, goal) self.direction.normalize() self.distance_traveled = 0 self.visited_points = [] self.state = State.Motion self.euclidean_distance = self.position.distance_to(self.goal)
def __init__(self, pos=Vector2D(320, 240)): self.pos = pos side_length = 4 self.rect = pygame.rect.Rect(0, 0, 2 * side_length, 2 * side_length) self.diag = math.sqrt(side_length ** 2 + (side_length / 2) ** 2) self.points = [pos, pos, pos] self.exhaust = [pos, pos, pos, pos, pos, pos, pos] self.aspeed = math.pi / 45.0 self.angle = 0 self.maxspeed = 2.0 self.speed = Vector2D(0, -0.05) self.velocity = Vector2D.zeros() self.color = pygame.Color('white') self.ret_color = pygame.Color(24, 24, 24) self.health = 100 self.lives = 3 self.alive = True self.score = 0 self.update(0.0)
def move(self): if self.state == State.Motion: scan_result = self.scan_for_obstacles() if scan_result == None: self.visited_points.append(Point(self.position.x, self.position.y)) self.position.x += self.direction.x self.position.y += self.direction.y self.updateHeading() self.distance_traveled += 1 else: # in range of an obstacle self.circumnavigation_obstacle = scan_result self.state = State.Circumnavigation self.move_tangent_line() else: # circumnavigating # check for on m-line if self.on_m_line() and self.clear_path(): self.visited_points = [] self.state = State.Motion self.direction = Vector2D.from_points(self.position, self.goal) self.direction.normalize() self.circumnavigation_obstacle = None else: # normal circumnavigation self.move_tangent_line()
def updateHeading(self): self.direction = Vector2D.from_points(self.position, self.goal) self.direction.normalize()