def seperation(self): steering_force = Vector2D() for agent in self.world.agents: if(agent is not self and agent.tagged): toBot = self.pos - agent.pos steering_force += Vector2D.normalise(toBot)/Vector2D.length(toBot) return steering_force
def flee(self, hunter_pos): if(Vector2D.distance(self.pos, hunter_pos) < 100): desired_vel = (self.pos - hunter_pos).normalise() * self.max_speed return (desired_vel - self.vel) elif(Vector2D.distance(self.pos, hunter_pos) > 300): return self.seek(hunter_pos) #TODO: Replace with wander function call else: return Vector2D()
def __init__(self, firing_pos, target_pos): self.init_pos = Vector2D.copy(firing_pos) self.pos = self.init_pos self.direction = Vector2D.normalise(target_pos - self.init_pos) self.velocity = 10 self.radius = 5 self.collision = None self.active = True
def flee(self, hunter_pos): ''' move away from hunter position ''' ## add panic distance (second) ## add flee calculations (first) if(Vector2D.distance(self.pos, hunter_pos) < 100): desired_vel = (self.pos - hunter_pos).normalise() * self.max_speed return (desired_vel - self.vel) elif(Vector2D.distance(self.pos, hunter_pos) > 300): return self.seek(hunter_pos) #TODO: Replace with wander function call else: return Vector2D()
def pursuit(self, evader): evader.mode = 'wander' ## OPTIONAL EXTRA... pursuit (you'll need something to pursue!) self.toEvader = evader.pos - self.pos self.relHeading = Vector2D.dot(evader.heading, self.heading) if(Vector2D.dot(self.toEvader, self.heading) > 0 and self.relHeading < -0.95): return self.seek(evader.pos) lookAheadTime = Vector2D.length(self.toEvader) / (self.max_speed + evader.speed()) return self.seek(evader.pos + evader.vel * lookAheadTime)
def pursuit(self, evader): ''' this behaviour predicts where an agent will be in time T and seeks towards that point to intercept it. ''' evader.mode = 'flee' ## OPTIONAL EXTRA... pursuit (you'll need something to pursue!) self.toEvader = evader.pos - self.pos self.relHeading = Vector2D.dot(evader.heading, self.heading) if(Vector2D.dot(self.toEvader, self.heading) > 0 and self.relHeading < -0.95): return self.seek(evader.pos) lookAheadTime = Vector2D.length(self.toEvader) / (self.max_speed + evader.speed()) return self.seek(evader.pos + evader.vel * lookAheadTime)
def find_prey(self, radius): tagged_prey = [] for prey in self.world.preyList: if Vector2D.distance(self.pos, prey.pos) < radius: tagged_prey.append(prey) shortest_dist = 999999999999999 closest_prey = None for prey in tagged_prey: if Vector2D.distance(self.pos, prey.pos) < shortest_dist: shortest_dist = Vector2D.distance(self.pos, prey.pos) closest_prey = prey return closest_prey
def update_vertex_list(self): offset_angle = (self.offset2 - self.offset1).direction p1_to_back = -self.offset1 p1_to_back.direction -= offset_angle back_distance = p1_to_back.y back_offset_vector = Vector2D.from_polar(back_distance, offset_angle + pi / 2) front_distance = -copysign(PocketRenderer.FRONT_DISTANCE, back_distance) front_offset_vector = Vector2D.from_polar(front_distance, offset_angle + pi / 2) points = [ self.offset1 + back_offset_vector + self.position, self.offset2 + back_offset_vector + self.position, self.offset2 + front_offset_vector + self.position, self.offset1 + front_offset_vector + self.position, ] self._vertex_list.vertices[:] = [number for point in points for number in point] self._vertex_list.colors[:] = self.color * 4
def follow_path(self): if(self.path is None): self.path = self.randomise_path() if(Vector2D.distance(self.path.current_pt(), self.pos) <= self.waypoint_threshold): self.path.inc_current_pt() return self.arrive(self.path.current_pt(), 'normal')
def tag_neighbours(self, radius): self.untag() for otherAgents in self.world.agents: to = self.pos - otherAgents.pos gap = radius + otherAgents.tag_radius if Vector2D.length_sq(to) < gap**2: otherAgents.tagged = True;
def tag_obs(self, radius): self.untag_obs() for otherAgents in self.world.obstacles: to = self.pos - otherAgents.pos gap = radius + otherAgents.radius if Vector2D.length_sq(to) < gap**2: otherAgents.tagged = True;
def update(self, delta): self.pos += (self.direction * self.velocity) * delta if (self.pos.x > self.world.cx or self.pos.x < 0) or (self.pos.y > self.world.cy or self.pos.y < 0): self.active = False return elif Vector2D.distance(self.pos, self.world.prey.pos) <= (self.radius - 10)**2: self.active = False self.world.prey.color = 'BLUE' return
def hide(self, hunter_pos, delta): if self.world.hunter is self: return self.wander(delta) best_hiding_spot = None best_hiding_dist = 99999999999 for obs in self.world.obstacles: boundary_dist = obs.radius + (obs.radius/2) hiding_spot = obs.pos + Vector2D.get_normalised(obs.pos - hunter_pos) * boundary_dist hiding_dist = Vector2D.distance(self.pos, hiding_spot)**2 if hiding_dist < best_hiding_dist: best_hiding_spot = hiding_spot best_hiding_dist = hiding_dist egi.green_pen() egi.cross(hiding_spot,10) return self.arrive(best_hiding_spot, "fast")
def addRocks(self, num=10): for i in range(num): newRock = Rock(world=self) newRock.vel = Vector2D.random(newRock.maxSpeed) newRock.vel.y = 0 newRock.pos = self.tank.randomPosition() while(self.obstacleOverlapsOtherObstacles(newRock)): newRock.pos = self.tank.randomPosition() self.obstacles.append(newRock)
def __init__(self, x, y): """ Create new boid at position x,y with a random unit velocity and no acceleration """ self.position = Vector2D(x,y) self.velocity = Vector2D.random2D() self.acceleration = Vector2D(0,0) """ experiment by changing the constants above """ self.size = boidSize self.maxspeed = boidSpeed self.maxaccel = boidAccel
def aim(self, enemy): timeToHit = Vector2D.distance(enemy.pos, self.init_pos) / self.bullet_speed return enemy.pos + enemy.vel * timeToHit
def update_firing_pos(self, firing_pos): self.init_pos = Vector2D.copy(firing_pos)
def bullet_path(self, hostile): diff = hostile.pos - self.pos x_inc = diff.x / 10 y_inc = diff.y / 10 self.avg = Vector2D(x_inc, y_inc)
def __init__(self, world=None, scale=30.0, mass=1.0, mode=None, color=None): # keep a reference to the world object self.world = world self.mode = mode # where am i and where am i going? random start pos dir = radians(random() * 360) self.pos = Vector2D(randrange(world.cx), randrange(world.cy)) self.vel = Vector2D() self.heading = Vector2D(sin(dir), cos(dir)) self.side = self.heading.perp() self.scale = Vector2D(scale, scale) # easy scaling of agent size self.force = Vector2D() # current steering force self.accel = Vector2D() # current acceleration due to force self.mass = mass # Force and speed limiting code self.max_speed = 2.0 * scale self.max_force = 5.0 * scale # data for drawing this agent self.color = color self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D(1.0, 0.0), Point2D(-1.0, -0.6) ] # wander details self.wander_target = Vector2D(1, 0) self.wander_dist = 1.0 * scale self.wander_radius = 1.0 * scale self.wander_jitter = 10.0 * scale self.bRadius = scale # group based weight values self.wander_wt = 1.0 self.align_wt = 1.0 self.cohesion_wt = 1.0 self.separate_wt = 1.0 self.neighbours = [] self.neighbour_radius = 150 # debug draw info? self.show_info = False # data for drawing walls self.walls = [ Vector2D(10.0, 490.0), Vector2D(490.0, 490.0), Vector2D(490.0, 10.0), Vector2D(10.0, 10.0) ]
def point_to_vector(self, point): if self.position_ == Position.CENTER: vector = Vector2D(point, self) rotated_vector = self.rotation_.rotate_vector(vector) return rotated_vector
def enemy_health(self): self.enemy.health -= 20 self.ammo -= 1 self.step_count = 0 self.bullet_pos = Vector2D()
def __init__(self, firing_pos, world=None, mode="Rifle"): self.init_pos = Vector2D.copy(firing_pos) self.world = world self.mode = mode self.bullet_speed = self.BULLET_VELOCITY[mode]
def __init__(self, x, y, r, c): self.pos = Vector2D(x, y) self.r = r self.c = c
def __init__(self, filename): self.width = 800 self.height = 600 self.start = Vector2D(0, 0) self.goal = Vector2D(800, 600) self.obstacles = [] self.points = [] #store all of the points in the problem self.sides_point1 = [] self.sides_point2 = [] self.neighbor = [ ] #a two-dimensional list if point j can not be successor point of i, neighbor[i][j]=-1, else store the distace between the two points self.start.polygon_num = -1 self.goal.polygon_num = -2 self.points.append(self.start) self.points.append(self.goal) f = open(filename, 'r') envtxt = f.readlines() f.close() polygonstxt, *resttxt = envtxt polygons = int(polygonstxt) for polygon_number in range(polygons): ntxt, *resttxt = resttxt n = int(ntxt) p = Polygon(n) for line in resttxt[:n]: [x, y] = [float(x) for x in line.split()] p.vertices.append(Vector2D(x, y)) resttxt = resttxt[n:] self.obstacles.append(p) #put all of the points into self.points for i in range(len(self.obstacles)): for j in range(len(self.obstacles[i].vertices)): if abs(self.obstacles[i].vertices[j].x - self.obstacles[i].vertices[ (j + 1) % self.obstacles[i].sides].x) > 0.000001 or abs( self.obstacles[i].vertices[j].y - self.obstacles[i].vertices[ (j + 1) % self.obstacles[i].sides].y) > 0.000001: self.sides_point1.append(self.obstacles[i].vertices[j]) self.sides_point2.append( self.obstacles[i].vertices[(j + 1) % self.obstacles[i].sides]) point = self.obstacles[i].vertices[j] point.polygon_num = i point.point_num = j self.points.append(point) #Building a two-dimensional list self.neighbor for i in range(len(self.points)): pl = list([]) for j in range(len(self.points)): dist = math.sqrt((self.points[i].x - self.points[j].x) * (self.points[i].x - self.points[j].x) + (self.points[i].y - self.points[j].y) * (self.points[i].y - self.points[j].y)) if i == j: pl.append(-1) else: if self.points[i].polygon_num == self.points[ j].polygon_num: nn = self.obstacles[self.points[i].polygon_num].sides if (self.points[i].point_num - self.points[j].point_num + nn) % nn == 1 or ( self.points[j].point_num - self.points[i].point_num + nn) % nn == 1: pl.append(dist) else: pl.append(-1) else: flag = 0 for k in range(len(self.sides_point1)): if IsIntersec(self.points[i], self.points[j], self.sides_point1[k], self.sides_point2[k]) == 1: flag = 1 if flag == 1: pl.append(-1) else: pl.append(dist) self.neighbor.append(pl)
def get_neighbours(self, bots, radius): for bot in bots: bot.tagged = False dist = Vector2D.distance_sq(self.pos, bot.pos) if dist < (radius + bot.bRadius) ** 2: bot.tagged = True
def on_mouse_release(x, y, button, modifiers): # print (x, y, button) if button == 1: # left #print (x,y) world.target = Vector2D(x, y)
def convert_vector(self, vector): if self.position_ == Position.TOPLEFT and vector.coordinate_system().position() == Position.CENTER: original_point = vector.original_point() new_vector = Vector2D(original_point, self, invert_y = True) return new_vector
import furniture import game import constants import util import logger from vector2d import Vector2D import random import os ## Maps direction names to vectors describing those directions directionToVectorMap = { 'up' : Vector2D(0, -1), 'down' : Vector2D(0, 1), 'left' : Vector2D(-1, 0), 'right' : Vector2D(1, 0), } ## Much like SceneryManager, this class loads the furnitureConfig files that # describe what furniture to place and how. class FurnitureManager: def __init__(self): ## Maps terrain to furniture config for that terrain. self.furnitureConfigCache = dict() ## Return a Furniture instance that matches the provided terrain and local # surface normal. Or return None if there's no good match. def pickFurniture(self, terrain, loc, surfaceNormal): # Map the local surface normal to a direction string direction = 'down'
def triangulate(self): print "Generating a triangulation from", len(self.nodes), "nodes" # 1. Pick seed node. seed = random.choice(self.nodes) # nodeSet is the set of nodes not currently in the triangulation. nodeSet = set(self.nodes) nodeSet.remove(seed) exteriorNodes = list(nodeSet) # 2. Sort by distance to seed node. exteriorNodes.sort(sortByDistanceTo(seed)) # 3. Find node closest to seed node. closestNode = exteriorNodes[0] nodeSet.remove(closestNode) # 4. Find node that creates smallest circumcircle. Equation for a # circumcircle's coordinates can be found at # http://en.wikipedia.org/wiki/Circumcircle#Coordinates_of_circumcenter # Treat calculations as if seed were at the center bPrime = closestNode.sub(seed) smallestRadius = None bestNode = None bestCenter = None for node in nodeSet: cPrime = node.sub(seed) d = 2 * (bPrime.x * cPrime.y - bPrime.y * cPrime.x) if d == 0: # Three nodes are collinear; there's no such thing as an # inscribed circumcircle in this case. continue centerX = (cPrime.y * (bPrime.x ** 2 + bPrime.y ** 2) - \ bPrime.y * (cPrime.x ** 2 + cPrime.y ** 2)) / d centerY = (bPrime.x * (cPrime.x ** 2 + cPrime.y ** 2) - \ cPrime.x * (bPrime.x ** 2 + bPrime.y ** 2)) / d center = Vector2D(centerX, centerY).add(seed) radius = center.sub(seed).magnitudeSquared() if smallestRadius is None or radius < smallestRadius: smallestRadius = radius bestNode = node bestCenter = center nodeSet.remove(bestNode) # 5. Force order to be right-handed; form starting convex hull. hull = [seed, closestNode, bestNode] a = closestNode.sub(seed) b = bestNode.sub(seed) direction = cmp(a.x * b.y - a.y * b.x, 0) if direction < 0: hull = [seed, bestNode, closestNode] # Construct edge mapping. for i in xrange(3): self.edges[hull[i]] = set([hull[(i - 1) % 3], hull[(i + 1) % 3]]) # List of all nodes contained by the hull. interiorNodes = list(hull) # 6. Resort remaining nodes by distance to the center of the # circumcircle; this is the order we will add the nodes to the # triangulation. exteriorNodes = list(nodeSet) exteriorNodes.sort(sortByDistanceTo(bestCenter)) # 7. Expand convex hull to encompass each new node in turn, adding # triangles to all visible nodes. while exteriorNodes: node = exteriorNodes.pop(0) # hull is now a list of nodes in the convex hull of the # triangulation thus far. Prune out occluded edges. visibleEdges = [] # Track how many times we are able to see each node: should be # 2 for nodes that are made interior by the new node, 1 for # nodes that are connected to the new node but still exterior, and # 0 otherwise. nodeSeenCount = dict([(n, 0) for n in hull]) for edge in [(n, hull[(i + 1) % len(hull)]) for i, n in enumerate(hull)]: a = edge[0].sub(node) b = edge[1].sub(edge[0]) direction = cmp(a.x * b.y - a.y * b.x, 0) if direction < 0: visibleEdges.append(edge) nodeSeenCount[edge[0]] += 1 nodeSeenCount[edge[1]] += 1 self.edges[node] = set() for a, b in visibleEdges: # Connect the new node to all visible exterior nodes. self.edges[a].add(node) self.edges[b].add(node) self.edges[node].add(a) self.edges[node].add(b) # Insert the new node into the hull. We have two cases here: # * Some nodes are rendered interior by the new node. In that case, # we remove those edges from the hull, and insert the new node # where they were. # * No nodes were rendered interior by the new node. That means that # the new node connects only to two old nodes, and should go # between them in the hull. if len(visibleEdges) > 1: # Find nodes that show up twice in visibleEdges; those nodes are # no longer in the hull. newHull = [] newNodeIndex = None for i, n in enumerate(hull): if nodeSeenCount[n] < 2: newHull.append(n) else: newNodeIndex = len(newHull) newHull.insert(newNodeIndex, node) hull = newHull else: newHull = list(hull) # Find the two visible nodes in the hull, insert new node # between them. for i, n in enumerate(hull): j = (i + 1) % len(hull) n2 = hull[j] if (n, n2) in visibleEdges: newHull.insert(j, node) break hull = newHull interiorNodes.append(node)
def valid_sensing(self, point): return abs(point - Vector2D(self.pose.x, self.pose.y) ) < self.valid_sensing_range
def pursuit(self, evader): ''' this behaviour predicts where an agent will be in time T and seeks towards that point to intercept it. ''' ## OPTIONAL EXTRA... pursuit (you'll need something to pursue!) return Vector2D()
############################### back = 'Stock/sushiplate.jpg' sprite = 'Stock/fugu.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(back).convert() sprite = pygame.image.load(sprite).convert_alpha() clock = pygame.time.Clock() sprite_pos = Vector2D(200, 150) sprite_speed = 300. sprite_rotation = 0. sprite_rotation_speed = 360. # Degrees per second pygame.mouse.set_visible(False) pygame.event.set_grab(True) while True: for event in pygame.event.get(): if event.type == QUIT: exit() pressed_keys = pygame.key.get_pressed() pressed_mouse = pygame.mouse.get_pressed()
#### Programme principal : #### ############################### back = 'Stock/sushiplate.jpg' sprite = 'Stock/fugu.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(back).convert() sprite = pygame.image.load(sprite).convert_alpha() clock = pygame.time.Clock() spritePos = Vector2D(200, 150) spriteSpeed = 300. while True: for event in pygame.event.get(): if event.type == QUIT: exit() pressed_keys = pygame.key.get_pressed() # Le vecteur permet de stocke une information en x et en y ( ---> diag) direction = Vector2D(0, 0) if pressed_keys[K_LEFT]: direction[0] = -1 print(direction) elif pressed_keys[K_RIGHT]: direction[0] = +1
win = window.Window(width=500, height=500, vsync=True, resizable=True) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_press) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) # add one agent main = Agent(world, Vector2D(world.target.x, world.target.y), 30.0, 1.0, 'soldier', 'GREEN', 2.0) world.agents.append(main) world.soldier = main # unpause the world ready for movement world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render() fps_display.draw() # swap the double buffer
def cube_to_cat(self, cube): # convert from cube coordinate to cartesian coodinate # project cube y and z onto cat y, where cube coordiante has a constraint x + y + z = 0 return Vector2D(cube.x * 1.5 * self.radius, (cube.y - cube.z) * sqrt(3) / 2 * self.radius)
# for v1, v2 in zip(self._transform_vertices(), # moved_bounding_polygon.transform_vertices()): # for u1, u2 in other_sides: # c=collides_at( v1, v2-v1, u1, u2 ) # if ( c is not None and 0.0 <= c < earliest_collision ): # earliest_collision = c # if earliest_collision == 9999.9: # return None # else: # return earliest_collision if __name__=="__main__": bounding_box=BoundingPolygon( (Vector2D(-1.0, -1.0), Vector2D(1.0, -1.0), Vector2D(1.0, 1.0), Vector2D(-1.0, 1.0)) ) bounding_box.position=Vector2D(1.0, 1.0) bounding_box.angle=45.0 bounding_box.update() print bounding_box.test_collision( Vector2D(-2.0, 0.0), Vector2D(4.0, 0.0) )
def Main(): vec1 = Vector2D(5, 6) vec2 = Vector2D(1, 1) Vec = (vec1, vec2) print(Vec[0], Vec[1])
def aim(self): timeToHit = Vector2D.distance(self.world.prey.pos, self.init_pos) / self.bullet_speed return self.world.prey.pos + self.world.prey.vel * timeToHit
def __init__(self, simulate=False): # setup motor controller. The PWM controller can control up to 16 # different devices. We have to add devices, one for each thruster that # we can control. The first parameter is the human-friendly name of the # device. That is used for logging to the console and/or a database. The # next parameter indicates which PWM connector this device is connected # to. This is refered to as the PWM channel. The last two values # indicate at what time intervals (ticks) the PWM should turn on and # off, respectively. We simply start each device at 0 time and control # the duration of the pulses by adjusting the off time. Note that we may # be able to shuffle on/off times to even out the current draw from the # thrusters, but so far, that hasn't been an issue. It's even possible # that the PWM controller may do that for us already. if simulate is False: from pwm_controller import PWMController self.motor_controller = PWMController() self.motor_controller.add_device("HL", HL, 0, NEUTRAL) self.motor_controller.add_device("VL", VL, 0, NEUTRAL) self.motor_controller.add_device("VC", VC, 0, NEUTRAL) self.motor_controller.add_device("VR", VR, 0, NEUTRAL) self.motor_controller.add_device("HR", HR, 0, NEUTRAL) self.motor_controller.add_device("LIGHT", LIGHT, 0, FULL_REVERSE) else: self.motor_controller = None # setup the joysticks. We use a 2D vector to represent the x and y # values of the joysticks. self.j1 = Vector2D() self.j2 = Vector2D() # create interpolators self.horizontal_left = Interpolator() self.vertical_left = Interpolator() self.vertical_center = Interpolator() self.vertical_right = Interpolator() self.horizontal_right = Interpolator() # setup interpolators from a file or manually if os.path.isfile(SETTINGS_FILE): with open(SETTINGS_FILE, 'r') as f: self.set_settings(json.load(f), False) else: # Set the sensitivity to be applied to each thruster. 0 indicates a # linear response which is the default when no sensitivity is applied. 1 # indicates full sensitivity. Values between 0 and 1 can be used to # increase and to decrease the overall sensitivity. Increasing sensivity # dampens lower values and amplifies larger values giving more precision # at lower power levels. self.sensitivity = 0.7 # We use a cubic to apply sensitivity. If you find that full sensitivity # (dampening) does not give you fine enough control, you can increase\ # the degree of the polynomial used for dampening. Note that this must # be a positive odd number. Any other values will cause unexpected # results. self.power = 3 # setup the various interpolators for each thruster. Each item we add # to the interpolator consists of two values: an angle in degrees and a # thrust value. An interpolator works by returning a value for any given # input value. More specifically in this case, we will give each # interpolator an angle and it will return a thrust value for that # angle. Since we have only given the interpolator values for very # specific angles, it will have to determine values for angles we have # not provided. It does this using linear interpolation. self.horizontal_left.addIndexValue(0.0, -1.0) self.horizontal_left.addIndexValue(90.0, 1.0) self.horizontal_left.addIndexValue(180.0, 1.0) self.horizontal_left.addIndexValue(270.0, -1.0) self.horizontal_left.addIndexValue(360.0, -1.0) self.vertical_left.addIndexValue(0.0, 1.0) self.vertical_left.addIndexValue(90.0, -1.0) self.vertical_left.addIndexValue(180.0, -1.0) self.vertical_left.addIndexValue(270.0, 1.0) self.vertical_left.addIndexValue(360.0, 1.0) self.vertical_center.addIndexValue(0.0, 0.0) self.vertical_center.addIndexValue(90.0, 1.0) self.vertical_center.addIndexValue(180.0, 0.0) self.vertical_center.addIndexValue(270.0, -1.0) self.vertical_center.addIndexValue(360.0, 0.0) self.vertical_right.addIndexValue(0.0, -1.0) self.vertical_right.addIndexValue(90.0, -1.0) self.vertical_right.addIndexValue(180.0, 1.0) self.vertical_right.addIndexValue(270.0, 1.0) self.vertical_right.addIndexValue(360.0, -1.0) self.horizontal_right.addIndexValue(0.0, 1.0) self.horizontal_right.addIndexValue(90.0, 1.0) self.horizontal_right.addIndexValue(180.0, -1.0) self.horizontal_right.addIndexValue(270.0, -1.0) self.horizontal_right.addIndexValue(360.0, 1.0) # setup ascent/descent controllers self.ascent = -1.0 self.descent = -1.0 # setup light self.light = 0.0
def get_sector_3(): objects = [] enemies = [ enemy.StrongEnemy(Vector2D(525, 25), 7), enemy.TinyEnemy(Vector2D(610, 32), 0), enemy.TinyEnemy(Vector2D(620, 37), 0), enemy.TinyEnemy(Vector2D(610, 42), 0) ] objects.append(enemies) obstacles = [ Obstacle(Vector2D(380, 3), 8), Obstacle(Vector2D(430, 27), 7), Obstacle(Vector2D(525, 3), 5), Obstacle(Vector2D(525, 48), 6), Obstacle(Vector2D(590, 3), 8), Obstacle(Vector2D(610, 3), 8), Obstacle(Vector2D(630, 3), 8) ] objects.append(obstacles) powerups = [] objects.append(powerups) return objects
def __init__(self): self.pos = Vector2D(10, 10) self.color = 'GREEN' self.path = Path()
def get_sector_end(): objects = [] enemies = [enemy.Boss(Vector2D(720, 20), 6)] objects.append(enemies) obstacles = [ Obstacle(Vector2D(525, 3), 5), Obstacle(Vector2D(525, 48), 6), Obstacle(Vector2D(590, 3), 8), Obstacle(Vector2D(610, 3), 8), Obstacle(Vector2D(630, 3), 8), Obstacle(Vector2D(705, 3), 2), Obstacle(Vector2D(705, 39), 1) ] objects.append(obstacles) powerups = [ PowerUp(Vector2D(670, 4), 2), PowerUp(Vector2D(685, 4), 3), PowerUp(Vector2D(670, 7), 2), PowerUp(Vector2D(685, 7), 3), PowerUp(Vector2D(670, 45), 1), PowerUp(Vector2D(685, 45), 1) ] objects.append(powerups) return objects
def adjustLocForCenter(loc, center, rect): rect.centerx = center.x rect.centery = center.y return Vector2D(loc.x - rect.topleft[0], loc.y - rect.topleft[1])
def __init__(self, world, radius = 10): #Position of this object in the world, is random self.pos = Vector2D(randrange(world.cx), randrange(world.cy)) #Value of this objects radius self.radius = radius
from ...base import terrestrialobject import game import logger import constants from vector2d import Vector2D from ...base.terrestrialstates import groundedattackstate from ...base.terrestrialstates import flinchstate def getClassName(): return 'Player' energyDisplayLoc = Vector2D(20, 20) energyDisplayColor = (250, 250, 100, 150) ## The Player class handles the player's avatar in the game. class Player(terrestrialobject.TerrestrialObject): ## Instantiate a Player object # \todo (Long-term) Add support for the female version def __init__(self): terrestrialobject.TerrestrialObject.__init__(self, game.map.getStartLoc().toRealspace(), 'maleplayer') self.canHang = True self.faction = 'player' ## Amount of health remaining before dying self.health = 100 ## Invincibility time after getting hit self.invincibilityTimer = 0 ## Velocity to impart when hit (when facing right) self.flinchVel = Vector2D(-40, -10) ## Number of frames of invincibility to get after getting hit self.mercyInvincibilityFrames = 45
def reinit(self, world): #Position of this object in the world, is random self.pos = Vector2D(randrange(world.cx), randrange(world.cy))
def on_mouse_press(x, y, button, modifiers): if button == 1: # left world.target = Vector2D(x, y)
class Cat(Pet): def __init__(self, name, age): #Calling super class methods super().__init__(name, age) #Initializing Objects thePet = Pet("Pet", 1) #Returns boolean isinstance(thePet, Pet) #Modulating Code import vector2d vec1 = vector2d.Vector2D(5, 6) from vector2d import Vector2D #alternatively a * for everything vec1 = Vector2D(5, 6) #Templates from string import Template def Main(): cart = [] cart.append(dict(item="Coke", price=8, qty=2)) t = Template("qty x $item = $price") print(t.safe_substitue(cart[0])) #Argparse import argparse parser = argparse.ArugmentParser() #Muterally exclusive group
def __init__(self, world=None, post=Vector2D(0, 0)): self.world = world self.radius = 30 self.pos = post
def __init__(self, target, actor_ball, balls): """ :type target: ShotTarget :type actor_ball: Ball :type balls: BallGroup """ self._position = actor_ball.position # get a pair of vectors pointing at the pocket v1 = target.point1 - actor_ball.position v2 = target.point2 - actor_ball.position # find ball radius offsets if (abs(v2.direction - (v1.direction + pi / 2)) < abs(v2.direction - (v1.direction - pi / 2))): sign = 1 else: sign = -1 off1 = Vector2D.from_polar(Ball.RADIUS * 2, v1.direction - sign * pi / 2) off2 = Vector2D.from_polar(Ball.RADIUS * 2, v2.direction + sign * pi / 2) # derive a system of inequalities from the vectors and offsets p1 = actor_ball.position + off1 p2 = actor_ball.position + off2 v1quad = v1.direction.quadrant v2quad = v2.direction.quadrant hem = None def get_east_west_cmp(): if v1.normalized().y < v2.normalized().y: return 1, -1 else: return -1, 1 if v1quad in Hemisphere.EAST and v2quad in Hemisphere.EAST: hem = Hemisphere.EAST cmp1, cmp2 = get_east_west_cmp() elif v1quad in Hemisphere.WEST and v2quad in Hemisphere.WEST: hem = Hemisphere.WEST cmp1, cmp2 = get_east_west_cmp() elif (v1.direction - v2.direction > pi / 2 == v1quad in Hemisphere.WEST): cmp1 = cmp2 = 1 else: cmp1 = cmp2 = -1 def is_possible_collision(x, y): in_correct_hemisphere = ( ((Vector2D((x, y)) - self.position).direction.quadrant in hem) if hem is not None else True ) return (cmp(y - p1.y, tan(v1.direction) * (x - p1.x)) == cmp1 and cmp(y - p2.y, tan(v2.direction) * (x - p2.x)) == cmp2 and in_correct_hemisphere) # restrict shot angles based on obstacles for other_ball in balls: if is_possible_collision(*other_ball.position): p1_to_ball = other_ball.position - p1 p2_to_ball = other_ball.position - p2 a1 = abs(p1_to_ball.direction - v1.direction) a2 = abs(p2_to_ball.direction - v2.direction) if min(a1, a2) > abs(v1.direction - v2.direction): raise ImpossibleShotError("Shot fully obstructed by balls.") if a1 < a2: v1.direction = p1_to_ball.direction else: v2.direction = p2_to_ball.direction # assert not is_possible_collision(*other_ball.position) # calculate necessary force to transfer to target, and sum with the # length of the shot v1_v2_avg = Vector2D(v1 + v2) / 2 force_offset_angle = abs(target.force.direction - v1_v2_avg.direction) if force_offset_angle > pi / 2: raise ImpossibleShotError("Positive force cannot be applied due to " "shot angle.") force_magnitude = (target.force.magnitude / cos(force_offset_angle) + v1_v2_avg.magnitude) # calculate target from shot vectors and necessary force target_p1 = self.position + Vector2D.from_polar(-Ball.RADIUS * 2, v1.direction) target_p2 = self.position + Vector2D.from_polar(-Ball.RADIUS * 2, v2.direction) target_force = Vector2D.from_polar(force_magnitude, v1_v2_avg.direction) self._target = ShotTarget(target_p1, target_p2, target_force) # save shot vectors self._vector1 = v1 self._vector2 = v2 # create renderer self._renderer = ShotSegmentRenderer(actor_ball.number, self.position, self.target, self.vector1, self.vector2)