def createJunction(self): if not self.isJunction(): return # We're going to lay claim to some points during this process. Update # their ownership when we're done so we don't let ones we've already # claimed convince us that it's okay to take more. claimedPoints = set() center = self.start.toGridspace() radius = int(self.getJunctionRadius() / constants.blockSize) # Iterate over points in the accepted area, claiming them if they belong # to edges that we're related to. for x in xrange(max(center.ix - radius, 1), min(center.ix + radius, game.map.numCols - 1)): for y in xrange(max(center.iy - radius, 1), min(center.iy + radius, game.map.numRows - 1)): point = Vector2D(x, y) if point in game.map.deadSeeds: if self.start.isEdgeRelated( game.map.deadSeeds[point].owner): claimedPoints.add(point) # Convert each claimed point into open space. Then check its neighbors, # and fill them with walls if they aren't related to us. for point in claimedPoints: game.map.assignSpace(point, self) if game.map.blocks[point.ix][point.iy] != generator.BLOCK_EMPTY: game.map.blocks[point.ix][point.iy] = generator.BLOCK_EMPTY # Patch walls around the deleted space for nearPoint in point.perimeter(): if not game.map.getIsInBounds(nearPoint): continue # If we hit a space that's not a wall or open space, or # if we hit a space that's owned by a node of the graph # that we aren't connected to, put a wall in. altEdge = None if nearPoint in game.map.deadSeeds: altEdge = game.map.deadSeeds[nearPoint].owner if (game.map.blocks[nearPoint.ix][nearPoint.iy] == generator.BLOCK_UNALLOCATED or (altEdge is not None and not self.start.isEdgeRelated(altEdge))): game.map.blocks[nearPoint.ix][ nearPoint.iy] = generator.BLOCK_WALL game.map.deadSeeds[nearPoint] = seed.Seed( self, 0, constants.BIGNUM)
def get_acceleration(self, delta): # Returns the updated acceleration based on the current behaviour if self.mode == 'Wander': return self.wander(delta) elif self.mode == 'Seek': return self.seek(self.world.target) elif self.mode == 'Arrive': return self.arrive(self.world.target) elif self.mode == 'Flee': return self.flee(self.world.target) elif self.mode == 'Follow path': return self.follow_path() elif self.mode == 'Weighted sum': return self.weighted_sum(self.world.target, delta) else: return Vector2D()
def addFood(self, x, y=None, num=1): # If no y was given then use the standard food distance above the tank if (y is None): y = self.height - self.foodDistance else: y = Util.clamp(self.tank.box.bottom, y, self.height) # Make sure the food will go in the tank x = Util.clamp(self.tank.box.left, x, self.tank.box.right) # Add the foods for _ in range(num): newFood = Food(world=self) newFood.pos = Vector2D(x, y) self.food.append(newFood)
def crop_image(self, resolution, left_position, right_position, bottom_position, top_position, coordinate_system): # create cropped image cropped_image = self.image_.crop( (int(left_position / resolution), int(top_position / resolution), int(right_position / resolution), int(bottom_position / resolution))) print "coordinate_system: " + str(coordinate_system) print "left: " + str(left_position) print "top: " + str(top_position) print "right: " + str(right_position) print "bottom: " + str(bottom_position) return cropped_image, Vector2D(Point2D(left_position, bottom_position), coordinate_system, transpose=False)
def __init__(self, world=None, scale=30.0, mass=2.0, mode='seek'): # 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 # data for drawing this agent. self.color = 'ORANGE' self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D( 1.0, 0.0), Point2D(-1.0, -0.6) ] ### follow path mode edit 1. ### self.path = Path() self.randomise_path() # <-- Doesn’t exist yet but you’ll create it. self.waypoint_threshold = 0.0 # <-- Work out a value for this as you test! ### end follow path mode edit 1. ### ### added wonder info part 2. ### # NEW WANDER INFO. ### 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 # Force and speed limiting code. # max speed is here. # limits? self.max_speed = 20.0 * scale self.max_force = 500.0 ### end add wander infor part 2. ### # debug draw info? self.show_info = False
def foodSteer(self, delta): steeringForce = Vector2D() bestFood = self.findBestFood(self.food) if (bestFood is not None): steeringForce = self.pursuit(bestFood) # else: # steeringForce = self.idleSteer(delta) if (self.chosenOne and self.world.drawDebug): egi.orange_pen() egi.line_by_pos(self.pos, self.pos + steeringForce) return steeringForce
def wander(self, delta): # Generate random jitter jitter = Vector2D( uniform(-1, 1) * self.wander_jitter * delta, uniform(-1, 1) * self.wander_jitter * delta) # Apply jitter to wander_target and map to circle self.wander_target = (self.wander_target + jitter).normalise() * self.wander_radius # Take a copy (important) and position ahead of agent wander_target_position = self.wander_target.copy() wander_target_position.x += self.wander_distance # Transform to world space world_target = self.world.transform_point(wander_target_position, self.position, self.heading, self.side) return self.seek(world_target)
def __init__(self, world=None, scale=5.0, mass=1.0, mode='hide'): # 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 # data for drawing this agent self.color = 'ORANGE' self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D( 1.0, 0.0), Point2D(-1.0, -0.6) ] self.path = Path() self.waypoint_threshold = 9.0 self.randomise_path() ### 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 self.tagged = False self.botList = self.world.agents self.overlapping = False self.neighbour_radius = 6 * scale # Force and speed limiting code self.max_speed = self.world.botMaxSpeed self.max_force = 500.0 # debug draw info? self.show_info = False
def __init__(self, world=None, scale=10.0, mass=1.0, mode='wander'): # keep a reference to the world object self.world = world self.mode = mode self.tagged = False # 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 # data for drawing this agent self.color = 'ORANGE' self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D(1.0, 0.0), Point2D(-1.0, -0.6) ] ### path to follow? self.path = Path() self.randomise_path() self.waypoint_threshold = 20 ### wander details # self.wander_?? ... 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 #Neighbourhood radius self.tag_radius = 5.0 * scale self.cohesion_toggle = False self.alignment_toggle = False self.seperation_toggle = False # limits? self.max_speed = 20.0 * scale ## max_force ?? self.max_force = 500.0 # debug draw info? self.show_info = False
def calculate(self, delta): # calculate the current steering force mode = self.mode if mode == 'aim': force = self.aim() elif mode == 'rifle': force = self.rifle() elif mode == 'rocket': force = self.rocket() elif mode == 'handgun': force = self.handgun() elif mode == 'grenade': force = self.grenade() else: force = Vector2D() self.force = force return force
def calculate(self, delta): force = Vector2D() # calculate the current steering force #force += self.wander(delta) * 0.1 #force += self.obstacle_avoidance() force += self.hide(self.world.hunter.pos, delta) if(self.cohesion_toggle): force += self.cohesion() * GROUPING_VALUES['cohesion'] if self.seperation_toggle: force += self.seperation() * GROUPING_VALUES['seperation'] if self.alignment_toggle: force += self.alignment() * GROUPING_VALUES['alignment'] self.force = force return force
def avoidHuntersSteer(self, delta): hunterPositions = [h.pos for h in self.world.hunters] count = len(hunterPositions) if (count == 0): return Vector2D() total = reduce(lambda x, y: x + y, hunterPositions) avg = total / float(count) distance = self.pos.distanceTo(avg) lengthSq = distance.lengthSq()**1.1 steer = -5000000 * distance.normalise() / lengthSq return steer, lengthSq
def __init__(self, world=None, scale=30.0, mass=1.0, mode='combined'): # 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 self.neighbours = [] # data for drawing this agent self.color = 'ORANGE' self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D( 1.0, 0.0), Point2D(-1.0, -0.6) ] ### path to follow? self.path = Path() self.randomise_path() # <-- Doesn’t exist yet but you’ll create it self.waypoint_threshold = 0.0 # <-- Work out a value for this as you test ### wander details self.wander_target = Vector2D(1, 0) self.wander_dist = 3.9 * scale self.wander_radius = 0.2 * scale self.wander_jitter = 4.3 * scale self.bRadius = scale # Force and speed limiting code # limits self.max_speed = 20.0 * scale ## max_force self.max_force = 500.0 # debug draw info? self.show_info = False #group variables self.wander_var = 1 self.alignment_var = 1 self.cohesion_var = 1
def flee(self, hunter_pos, speed, pursuit_speed): ''' move away from hunter position ''' decel_rate = self.DECELERATION_SPEEDS[speed] flee_target = self.pos - hunter_pos dist = flee_target.length() if dist > 100: if AGENT_MODES is 'flee': ## For stationary targets speed = dist / decel_rate speed = min(speed, self.max_speed) desired_vel = flee_target * (speed / dist) return (desired_vel - self.vel) else: ## for moving targets pursuit_speed = dist / decel_rate pursuit_speed = min(pursuit_speed, self.max_speed) desired_vel = flee_target * (pursuit_speed / dist) return (desired_vel - self.vel) return Vector2D()
def follow_path(self): if self.path.is_at_end_of_path(): if self.pos.distance( self.path.current_pt()) <= self.waypoint_threshold: self.path.inc_current_pt() else: # arrive at current point return self.arrive(self.path.current_pt(), 'slow') else: # if within threashold distance of current point, inc_current_point if self.pos.distance( self.path.current_pt()) <= self.waypoint_threshold: self.path.inc_current_pt() # Else Seek current point else: return self.seek(self.path.current_pt()) return Vector2D(0, 0)
def arrive(self, target_pos, speed): ''' this behaviour is similar to seek() but it attempts to arrive at the target position with a zero velocity''' decel_rate = self.DECELERATION_SPEEDS[speed] to_target = target_pos - self.pos dist = to_target.length() if dist > 0: # calculate the speed required to reach the target given the # desired deceleration rate speed = dist / decel_rate # make sure the velocity does not exceed the max speed = min(speed, self.max_speed) # from here proceed just like Seek except we don't need to # normalize the to_target vector because we have already gone to the # trouble of calculating its length for dist. desired_vel = to_target * (speed / dist) return (desired_vel - self.vel) return Vector2D(0, 0)
def __init__(self, cx, cy): self.cx = cx self.cy = cy self.target = Vector2D(cx / 2, cy / 2) self.obstacle = [] self.hunter = None self.agents = [] self.paused = True self.show_info = True self.marksman = None self.hitpoint = None self.bullet = [] self.cohesion = 0.0 self.separation = 0.0 self.alignment = 0.0 self.radius = 10.0
def hit(self): self.health -= 25 if self.health <= 0: cx = self.world.cx # width cy = self.world.cy # height margin = min(cx, cy) * (1 / 6) # use this for padding in the next line minx = int(0 + margin) maxx = int(cx - margin) miny = int(0 + margin) maxy = int(cy - margin) new_x = random.randint(minx,maxx) new_y = random.randint(miny,maxy) self.pos = Vector2D(new_x,new_y) self.health = 50
def follow_path(self, path): target = self.path.current_pt() # If heading to final point (is_finished?). if self.path.is_finished(): # Return a slow down force vector (Arrive). target == Vector2D(self.path.current_pt().x, self.path.current_pt().y) return self.arrive(target, 'slow') # Else else: dist = target - self.pos # If within threshold distance of current way point, inc to next in path. if dist.length() < self.waypoint_threshold: self.path.inc_current_pt() # Return a force vector to head to current point at full speed (Seek). return self.arrive(target, 'fast') else: return self.seek(target)
def get_sector_2(): objects = [] enemies = [ enemy.TinyEnemy(Vector2D(500, 10), 7), enemy.TinyEnemy(Vector2D(500, 15), 7), enemy.TinyEnemy(Vector2D(500, 35), 7), enemy.TinyEnemy(Vector2D(500, 40), 7) ] objects.append(enemies) obstacles = [ Obstacle(Vector2D(230, 3), 2), Obstacle(Vector2D(230, 39), 1), Obstacle(Vector2D(380, 3), 8), Obstacle(Vector2D(430, 27), 7) ] objects.append(obstacles) powerups = [] objects.append(powerups) return objects
def draw_score(self): temp_objects = [ Obj(Vector2D(self.view.pos.x + 5, 1), load_texture("other", 2)), Obj(Vector2D(self.view.pos.x + 5, 7), load_texture("other", 3)), Obj(Vector2D(self.view.pos.x + 5, 15), load_texture("other", 4)), Obj(Vector2D(self.view.pos.x + 5, 22), load_texture("other", 4)), Obj(Vector2D(self.view.pos.x + 8, 17), "Your Score : " + str(self.score)), Obj(Vector2D(self.view.pos.x + 8, 24), "Press enter to continue...") ] self.last_matrix = Graphics.draw(temp_objects, self.view)
def __init__(self, world=None, scale=30.0, mass=1.0, mode='patrol'): # keep a reference to the world object.py 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 # data for drawing this agent self.color = 'ORANGE' self.vehicle_shape = [ Point2D(-1.0, 0.6), Point2D(1.0, 0.0), Point2D(-1.0, -0.6) ] ### path to follow? # self.path = ?? self.path = Path() self.randomise_path(10) self.waypoint_threshold = 10.0 ### wander details # self.wander_?? ... 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 # limits? self.max_speed = 100.0 self.max_force = 200.0 self.bulletspeed = 500.0 self.bullets = 6 self.reload_time = 1 self.current_reload_time = 0.0 self.gun_state = 'loaded' # debug draw info? self.show_info = False
def getRockShape(self): radius = self.boundingRadius edges = self.edges angle = 2 * pi / edges pts = [] variance = 0.18 variation = (1 - variance, 1 + variance) for i in range(edges): v = Vector2D(cos(i * angle), sin(i * angle)) * radius v.x *= uniform(variation[0], variation[1]) v.y *= uniform(variation[0], variation[1]) pts.append(v) return pts
def flee(self, hunter_pos, speed, pursuit_speed): ''' move away from hunter position ''' ## add panic distance (second) ## add flee calculations (first) decel_rate = self.DECELERATION_SPEEDS[speed] flee_target = self.pos - hunter_pos dist = flee_target.length() if dist > 15: if AGENT_MODES is 'flee': speed = dist / decel_rate speed = min(speed, self.max_speed) desired_vel = flee_target * (speed / dist) return (desired_vel - self.vel) else: pursuit_speed = dist / decel_rate pursuit_speed = min(pursuit_speed, self.max_speed) desired_vel = flee_target * (pursuit_speed / dist) return (desired_vel - self.vel) return Vector2D()
def _transform_vertex(self, vertex): xfrm_v=Vector2D(vertex[0], vertex[1]) # scale xfrm_v.x *= self.scale.x xfrm_v.y *= self.scale.y # rotate theta = math.radians(self.angle) new_x = xfrm_v.x*math.cos(theta) - xfrm_v.y*math.sin(theta) new_y = xfrm_v.x*math.sin(theta) + xfrm_v.y*math.cos(theta) xfrm_v.x = new_x xfrm_v.y = new_y # translate xfrm_v += (self.position-self.origin) return xfrm_v
def calculate(self): # reset the steering force mode = self.mode if mode == 'seek': accel = self.seek(self.world.target) elif mode == 'arrive_slow': accel = self.arrive(self.world.target, 'slow') elif mode == 'arrive_normal': accel = self.arrive(self.world.target, 'normal') elif mode == 'arrive_fast': accel = self.arrive(self.world.target, 'fast') elif mode == 'flee': accel = self.flee(self.world.target) ## elif mode == 'pursuit': ## force = self.pursuit(self.world.hunter) else: accel = Vector2D() self.acceleration = accel return accel
def update(self, delta): ''' update vehicle position and orientation ''' force = self.calculate(delta) force.truncate(self.max_force) # new velocity self.vel += force * delta for obst in self.world.obstacles: if self.flee(obst.coords, 50) != Vector2D(0, 0): self.vel = self.flee(obst.coords, 50) * delta * 20 # check for limits of new velocity self.vel.truncate(self.max_speed) # update position self.pos += self.vel * delta # update heading is non-zero velocity (moving) if self.vel.length_sq() > 0.00000001: self.heading = self.vel.get_normalised() self.side = self.heading.perp() # treat world as continuous space - wrap new position if needed self.world.wrap_around(self.pos)
def calculate(self, delta): # reset the steering force mode = self.mode if mode == 'seek': force = self.seek(self.world.target) elif mode == 'arrive_slow': force = self.arrive(self.world.target, 'slow') elif mode == 'arrive_normal': force = self.arrive(self.world.target, 'normal') elif mode == 'arrive_fast': force = self.arrive(self.world.target, 'fast') elif mode == 'flee': force = self.flee(self.world.target) elif mode == 'pursuit': force = self.pursuit(self.world.hunter) else: force = Vector2D() self.force = force return force
def calculate(self, delta): # calculate the current steering force mode = self.mode if mode == 'seek': force = self.seek(self.world.target) elif mode == 'arrive_slow': force = self.arrive(self.world.target, 'slow') elif mode == 'flee': force = self.flee(self.world.target) elif mode == 'pursuit': force = self.pursuit(self.world.hunter) elif mode == 'wander': force = self.wander(delta) elif mode == 'hide': force = self.hide() else: force = Vector2D() self.force = force return force
def AvoidEnvironmentForce(self): totalforce = Vector2D(0, 0) for circle in Agent.world.walls: #use position or position +velocity to determine additive force based on which of the two is closer measerPosition = self.pos if (self.pos + self.vel).distance(circle.pos) < self.pos.distance( circle.pos): measerPosition = (self.pos + self.vel) edgeDistance = measerPosition.distance(circle.pos) - circle.radius if edgeDistance < Agent.distanceFromEnvironment * Agent.floatScale: if edgeDistance < 0: edgeDistance = 0 proportion = 1 - ( edgeDistance / (Agent.distanceFromEnvironment * Agent.floatScale)) totalforce += (self.pos - circle.pos).normalise( ) * Agent.max_speed * Agent.floatScale * proportion return totalforce