def on_touch_down(self, touch): if touch.button == 'left': return super().on_touch_down(touch) if touch.button == 'scrollup': self.evr.decal.zoom(Point(touch.x, touch.y)) if touch.button == 'scrolldown': self.evr.decal.dezoom(Point(touch.x, touch.y))
def __init__(self, room, startpoint, direction, energy, color, energyMin, lineLong): self.energyMax = energy self.lineLong = lineLong self.energy = energy self.direction = direction self.color = deepcopy(color) transp = 1 x0 = startpoint.x y0 = startpoint.y j = 0 while self.energy > energyMin: xline = x0 + self.lineLong * cos(self.direction) yline = y0 + self.lineLong * sin(self.direction) oldPt = Point(x0, y0) newPt = Point(xline, yline) for mur in room.walls: if mur.are2PointOnDifferentsSide(oldPt, newPt): self.bounce(mur) self.energy = self.energy * self.attenuation()**self.lineLong transp = self.energy / self.energyMax Color(self.color[0], self.color[1], self.color[2], transp) Line(points=[x0, y0, xline, yline], width=1) x0 = xline y0 = yline j = j+1
def collide_point(self, x, y): if self.isAlignedWith(Point(x, y)): return False minPoint = self.getNearestPointOnLine(Point(x, y)) dist = minPoint.dist(Point(x, y)) if dist < self.collidewidth: return True return False
def __init__(self, ax, ay, bx, by, evr): super(Mur, self).__init__(evr) self.a = Point(ax, ay) self.b = Point(bx, by) self.width = 150 self.pointsWidth = 20 self.collidewidth = 35 self.defColor = [.6, .1, .2] self.color = self.defColor self.isSelected = False
def __init__(self): self.pos = Point(0, 0, 0) # Translation self.rot = Point(0, 0, 0) # Rotation self.v = Point(0, 0, 0) # Velocity self.ω = Point(0, 0, 0) # Angular velocity self.rotating = False self.translating = False self.DEBUG = False
def isInterestedInMove(self, touch, x, y): distanceA = self.a.dist(Point(touch.x, touch.y)) distanceB = self.b.dist(Point(touch.x, touch.y)) if (distanceA < self.pointsWidth and distanceA <= distanceB): self.a.x += x self.a.y += y elif (distanceB < self.pointsWidth and distanceA > distanceB): self.b.x += x self.b.y += y else: self.decaler(x, y) return True
def drawe(self): with self.canvas: self.canvas.clear() Color(self.color[0], self.color[1], self.color[2]) a = self.evr.decale(Point(self.a.x, self.a.y)) b = self.evr.decale(Point(self.b.x, self.b.y)) Line(points=[a.x, a.y, b.x, b.y]) if self.isSelected: center = (a.x - self.pointsWidth / 2, a.y - self.pointsWidth / 2) Ellipse(pos=center, size=(self.pointsWidth, self.pointsWidth)) center = (b.x - self.pointsWidth / 2, b.y - self.pointsWidth / 2) Ellipse(pos=center, size=(self.pointsWidth, self.pointsWidth)) return self
def _calculate_two_theta(self, x_pixel, y_pixel): d = self.detector_distance if self.method == 1: #conduct the calculation #following fit2d paper: #create appropriate parameters x_distance = (x_pixel - self.center_in_pixel.x) * self.pixel_size y_distance = (y_pixel - self.center_in_pixel.y) * self.pixel_size phi = self.tilt_y / 180. * np.pi beta = self.tilt_x / 180. * np.pi first_term = cos(phi)**2 * (cos(beta) * x_distance + sin(beta) * y_distance)**2 second_term = (-sin(beta) * x_distance + cos(beta) * y_distance)**2 third_term = (d + sin(phi) * (cos(beta) * x_distance + sin(beta) * y_distance))**2 two_theta = arctan(sqrt( (first_term + second_term) / third_term)) * 180 / np.pi elif self.method == 2: #follwoing the Bob B. He: x_distance = (x_pixel - 1024) * self.pixel_size y_distance = (y_pixel - 1024) * self.pixel_size alpha = arcsin( distance(Point(1024, 1024), self.center_in_pixel) * self.pixel_size / d) two_theta = arccos( (x_distance * sin(alpha) + d * cos(alpha)) / np.sqrt(d ** 2 + x_distance ** 2 + y_distance ** 2)) \ * 180 / np.pi return two_theta
def __init__(self, posx, posy, power=5, room=None, color=[1, 1, 1]): self.lines = [] self.room = room self.pos = Point(posx, posy) self.nblignes = power**2 self.color = color self.energyPerBeam = 10
def add_point_load(self, loaded_joint: Point, load_force: float): """ Joint load must be applied between two supports """ external_forces_y_pos = None for support in self.supports: external_forces_y_pos = support.y break if external_forces_y_pos != loaded_joint.y: raise Exception("Joint load is not horizontally inline with supports.") supports_x_pos = sorted([support.x for support in self.supports]) for i, x_pos in enumerate(supports_x_pos): left_neighbour = None if i == 0 else supports_x_pos[i - 1] right_neighbour = None if i == len(supports_x_pos) - 1 else supports_x_pos[i + 1] # If outside of neighbours, no weight on me if left_neighbour is not None and loaded_joint.x <= left_neighbour: continue if right_neighbour is not None and loaded_joint.x >= right_neighbour: continue # Between current joint and right joint if loaded_joint.x > x_pos: if right_neighbour is None: raise Exception( "Joint load seems to be applied to the right of all supports. Must be between supports") reaction_force = load_force * (loaded_joint.x - x_pos) / (right_neighbour - x_pos) self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, reaction_force) # Between current joint and right joint elif loaded_joint.x < x_pos: if left_neighbour is None: raise Exception( "Joint load seems to be applied to the left of all supports. Must be between supports.") reaction_force = load_force * (x_pos - loaded_joint.x) / (x_pos - left_neighbour) self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, reaction_force) else: self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, load_force) self.bridge.joints[loaded_joint].external_force = Vector(0 * kN, -load_force)
def drawe(self): with self.canvas: self.canvas.clear() point = self.evr.decale(Point(self.posx, self.posy)) Color(self.color[0], self.color[1], self.color[2]) center = (point.x - self.larg / 2, point.y - self.larg / 2) self.e = Ellipse(pos=center, size=(self.larg, self.larg)) return self
def get_clusters(cmap, kmap, num_clusters): result = [[[], 0] for i in range(num_clusters)] for y in range(len(cmap)): for x in range(len(cmap[0])): if cmap[y][x] != -1: result[cmap[y][x]][0].append(Point(y, x)) result[cmap[y][x]][1] += kmap[y][x] return result
def adjustedToMatchExtremity(self, touch): distA = self.a.dist(Point(touch.x, touch.y)) if distA < self.collidewidth: touch.x = self.a.x touch.y = self.a.y return touch distB = self.b.dist(Point(touch.x, touch.y)) if distB < self.collidewidth: touch.x = self.b.x touch.y = self.b.y return touch nearest = self.getNearestPointOnLine(Point(touch.x, touch.y)) distance = Point(touch.x, touch.y).dist(nearest) if distance < self.collidewidth: touch.x = nearest.x touch.y = nearest.y return touch
def getNearestPointOnLine(self, point): perpVector = self.getPerpVector() if perpVector[0] == 0: perpVector[0] = 0.001 ap = perpVector[1] / perpVector[0] bp = -ap * point.x + point.y wallEq = self.getaxplusbEquation() xx = (bp - wallEq[1]) / (wallEq[0] - ap) return Point(xx, ap * xx + bp)
def drawSth(self, touch): if self.evr.shouldDrawWall(): for mur in self.room.walls: touch = mur.adjustedToMatchExtremity(touch) self.firstTouch = Point(touch.x, touch.y) elif self.evr.shouldDrawLight(): light = Lumiere(touch.x, touch.y, self.evr) self.room.lights.append(light) return touch
def get_beams_for_pratt_bridge(self, number_of_panels: int, span, angle_ratio: float): """ :param number_of_panels: The number of times the sequence repeats :param span: The span of the bridge :param angle_ratio: The height divided by the width of one panel """ beams = {} chord_length = span / number_of_panels height = chord_length * angle_ratio if number_of_panels % 2 == 1: raise Exception("Uneven number of panels. Can't build beams.") for i in range(number_of_panels): top_left = Point(chord_length * i, height) top_right = Point(chord_length * (i + 1), height) bottom_left = Point(chord_length * i, 0 * pq.m) bottom_right = Point(chord_length * (i + 1), 0 * pq.m) # Bottom chord beams[Beam(bottom_left, bottom_right)] = BeamProperties(self.hss_bottom_chord_set) # Vertical beam if i != 0: beams[Beam(bottom_left, top_left)] = BeamProperties(self.hss_web_set) # Top chord if i != 0 and i != number_of_panels - 1: beams[Beam(top_left, top_right)] = BeamProperties(self.hss_top_chord_set) # Slanted beams if i == 0: beams[Beam(bottom_left, top_right)] = BeamProperties(self.hss_web_set) elif i < number_of_panels / 2: beams[Beam(top_left, bottom_right)] = BeamProperties(self.hss_web_set) elif i < number_of_panels - 1: beams[Beam(top_right, bottom_left)] = BeamProperties(self.hss_web_set) else: beams[Beam(top_left, bottom_right)] = BeamProperties(self.hss_web_set) return beams
def add_og_poi(self): for unit in self.gc.my_units(): loc = unit.location.map_location() p = self.symmetry(Point(loc.y, loc.x)) flag = False for d in self.destinations: if d[p.y][p.x] and d[p.y][p.x][1] < 5: flag = True break if not flag: make_poi(self, p)
def add_uniformly_distributed_load(self, load_per_unit_length): external_forces_y_pos = None for support in self.supports: external_forces_y_pos = support.y break load_bearing_joints_x_pos = [] for joint in self.bridge.joints: if joint.y == external_forces_y_pos: load_bearing_joints_x_pos.append(joint.x) load_bearing_joints_x_pos = sorted(load_bearing_joints_x_pos) supports_x_pos = sorted([support.x for support in self.supports]) # Loop from left to right throughout the joints for i, x_pos in enumerate(load_bearing_joints_x_pos): if i == 0: dist_to_neighbouring_joints = (load_bearing_joints_x_pos[i + 1] - x_pos) elif i < len(load_bearing_joints_x_pos) - 1: dist_to_neighbouring_joints = (load_bearing_joints_x_pos[i + 1] - load_bearing_joints_x_pos[i - 1]) else: dist_to_neighbouring_joints = (x_pos - load_bearing_joints_x_pos[i - 1]) self.bridge.joints[ Point(x_pos, external_forces_y_pos)].external_force = Vector(0 * pq.N, dist_to_neighbouring_joints / -2 * load_per_unit_length) for i, x_pos in enumerate(supports_x_pos): if i == 0: dist_to_neighbouring_joints = (supports_x_pos[i + 1] - x_pos) elif i < len(supports_x_pos) - 1: dist_to_neighbouring_joints = (supports_x_pos[i + 1] - supports_x_pos[i - 1]) else: dist_to_neighbouring_joints = (x_pos - supports_x_pos[i - 1]) self.bridge.joints[Point(x_pos, external_forces_y_pos)] \ .external_force += Vector(0 * pq.N, dist_to_neighbouring_joints / 2 * load_per_unit_length)
def compute_waypoints_from_laneparams(update, currentGoalPoint): global laneParams global wpList global currentPos global pub_goal_debug global pub_goal_debug1 step = 0.5 numPoint = 20 dist = 0 wpList = [] if update: zero_x = currentGoalPoint.x zero_y = currentGoalPoint.y else: zero_x = currentPos.x zero_y = currentPos.y # compute lane points ahead of the vehicle for distIdx in range(0, numPoint): wpYorigin = 0.16667 * laneParams.rhoDot * numpy.power( dist, 3) + 0.5 * laneParams.rho * numpy.power( dist, 2) + laneParams.phi * dist + laneParams.y currPoint = numpy.array([dist, wpYorigin]) heading = currentPos.heading rotationMtrx = numpy.array([[numpy.cos(heading), -numpy.sin(heading)], [numpy.sin(heading), numpy.cos(heading)]]) # rotated_point_ = numpy.dot(currPoint, rotationMtrx) rotated_point = numpy.matmul(rotationMtrx, currPoint) # print('rotated b', rotated_point_b) wpX = rotated_point[0] + zero_x wpY = rotated_point[1] + zero_y wpList.append(Point(wpX, wpY)) print('original Points', dist, wpYorigin) print('rotated point', rotated_point) print('current pose', currentPos.x, currentPos.y, heading) print('goalPoint', wpX, wpY) print('getting new list') dist = dist + step print('rotation matrix', rotationMtrx) current_goalPoint = Point32(wpList[5].x, wpList[5].y, 0) current_goalPoint1 = Point32(wpList[10].x, wpList[10].y, 0) pub_goal_debug.publish(current_goalPoint) pub_goal_debug1.publish(current_goalPoint1) # raw_input() return (wpList)
def find_clusters(kmap, gap, directions): cmap = [[-1 for val in row] for row in kmap] neighbors = [[[] for val in row] for row in kmap] num_clusters = 0 for y in range(len(kmap)): for x in range(len(kmap[0])): if kmap[y][x] > 0 and cmap[y][x] == -1: find_neighbors(Point(y, x), num_clusters, gap, kmap, cmap, neighbors, directions) num_clusters += 1 return num_clusters, cmap, neighbors
def test_next(self): name = str(random()) cls = 'warrior' id = self.game_client.add_character(name=name, cls=cls) self.game_client.enter_game(id) self.game_client.move(Point(1, 2)) for x in self.game_client.get_message(): if x['id'] == str(id): self.assertEqual(x['name'], name, "Wrong name") self.assertEqual(x['cls'], cls, "Wrong class") self.assertEqual((x['dx'], x['dy']), ('1', '2'), "Wrong move method") break else: raise Exception('Missing character')
def get_beams_for_equilateral_bridge(self, number_of_panels: int, span): beams = {} side_length = span / number_of_panels height = side_length * math.sqrt(3) / 2 previous_top_corner = None for i in range(number_of_panels): # Corners left_corner = Point(side_length * i, 0 * pq.m) top_corner = Point(side_length * (i + 0.5), height) right_corner = Point(side_length * (i + 1), 0 * pq.m) beams[Beam(left_corner, right_corner)] = BeamProperties(self.hss_bottom_chord_set) beams[Beam(left_corner, top_corner)] = BeamProperties(self.hss_web_set) beams[Beam(right_corner, top_corner)] = BeamProperties(self.hss_web_set) if previous_top_corner is not None: beams[Beam(previous_top_corner, top_corner)] = BeamProperties(self.hss_top_chord_set) previous_top_corner = top_corner return beams
def main(): self = Container() UnitInfo.setup() print(os.getcwd()) print("pystarting") # A GameController is the main type that you talk to the game with. # Its constructor will connect to a running game. self.gc = bc.GameController() print("pystarted") # It's a good idea to try to keep your bots deterministic, to make debugging easier. # determinism isn't required, but it means that the same things will happen in every thing you run, # aside from turns taking slightly different amounts of time due to noise. random.seed(6137) # For the purposes of this program, (0, 0) is the UPPERLEFT corner and Point(y, x) <=> [y][x] <=> bc.MapLocation(self.planet, x, y) self.directions = [ Point(1, 0), Point(1, 1), Point(0, 1), Point(-1, 1), Point(-1, 0), Point(-1, -1), Point(0, -1), Point(1, -1) ] self.planet = self.gc.planet() self.planet_map = self.gc.starting_map(self.planet) self.team = self.gc.team() self.asteroids = self.gc.asteroid_pattern() self.orbit = self.gc.orbit_pattern() # self.kmap[row][col] is an amount of karbonite >= 0 or -1 if impassable self.kmap = phase0.generate_kmap(self) if self.planet == bc.Planet.Earth: main_earth(self) else: main_mars(self)
def perform_bfs(cluster, kmap, directions): result = [[None for val in row] for row in kmap] q = [] index = 0 for p in cluster: q.append((p, 0)) result[p.y][p.x] = Point(0, 0), 0 while index < len(q): dest, dist = q[index] for d in directions: new = dest + d if not out_of_bounds(new, kmap) and result[new.y][new.x] is None: result[new.y][new.x] = -d, dist + 1 q.append((new, dist + 1)) index += 1 return result
def get_symmetry(self): poss = [ lambda p: Point(len(self.kmap) - 1 - p.y, len(self.kmap[0]) - 1 - p.x), lambda p: Point(p.y, len(self.kmap[0]) - 1 - p.x), lambda p: Point(len(self.kmap) - 1 - p.y, p.x), lambda p: Point(p.x, p.y), lambda p: Point(len(self.kmap[0]) - 1 - p.x, len(self.kmap) - 1 - p.y) ] if len(self.kmap) != len(self.kmap[0]): poss = poss[:-2] for y in range(len(self.kmap)): for x in range(len(self.kmap[0])): for i in range(len(poss)): if poss[i]: p = poss[i](Point(y, x)) if self.kmap[p.y][p.x] != self.kmap[y][x]: poss[i] = None for s in poss: if s: return s
def iter_points(self) -> typing.Iterator[Point]: """Iterate through the cells' ``(x, y)`` points.""" for y, row in enumerate(self._cells): for x in range(len(row)): yield Point(x, y)
class Camera(object): ''' Animation data ''' def __init__(self): self.pos = Point(0, 0, 0) # Translation self.rot = Point(0, 0, 0) # Rotation self.v = Point(0, 0, 0) # Velocity self.ω = Point(0, 0, 0) # Angular velocity self.rotating = False self.translating = False self.DEBUG = False def set(self, attr, x=None, y=None, z=None): ''' Docstring goes here ''' # TODO: This API method is subject to change getattr(self, attr).set(x, y, z) # # for key, val in kwargs.items(): # setattr(self, key, val) def nudge(self, attr, x=None, y=None, z=None): ''' Increments a given attribute ''' attr = getattr(self, attr) attr += Point(x or 0, y or 0, z or 0) def rotate(self, x=None, y=None, z=None): ''' Rotates the camera from its current orientation ''' self.nudge('rot', x, y, z) self.rotating = True # TODO: Is this necessary? def setRotation(self, x=None, y=None, z=None): ''' Sets an absolute rotation ''' self.rot.set(x, y, z) def setTranslation(self, x=None, y=None, z=None): ''' Sets an absolute translation ''' self.pos.set(x, y, z) def translate(self, x=None, y=None, z=None): ''' Translates the camera from its current position ''' self.nudge('pos', x, y, z) self.translating = True # TODO: Is this necessary (animation flags in general)? def setVelocity(self, x=None, y=None, z=None): ''' Sets an absolute velocity ''' self.set('v', x, y, z) self.translating = True def accelerate(self, x=None, y=None, z=None): ''' Increases the velocity of the camera ''' self.nudge('v', x, y, z) self.translating = True def setRotating(self, rotating): self.rotating = rotating def setTranslating(self, translating): self.translating = translating def apply(self): ''' Apply transformations ''' # TODO: Decide in which order the transformations should be applied glTranslate(*self.pos) glRotate(self.rot.x, 1, 0, 0) glRotate(self.rot.y, 0, 1, 0) glRotate(self.rot.z, 0, 0, 1) def animate(self, dt=1): # TODO: Take time delta into account (?) if self.rotating: self.rot += self.ω if self.translating: self.pos += self.v def __str__(self): ''' Docstring goes here ''' return 'Camera | rot x={rx} y={ry} z={rz} | pos x={tx} y={ty} z={tz}'.format(rx=self.rx, ry=self.ry, rz=self.rz, tx=self.tx, ty=self.ty, tz=self.tz)
def process_units(state, units, factories, b_info, create_type): """ Controls workers in a general situation with the goal of building factories. Returns True if built a factory, else False. ASSUMES UnitQueue has been initialized for all units currently in units. ASSUMES units is a list of only robots """ ans = False gc = state.gc b_info.prevcount = b_info.count b_info.oprevcount = b_info.ocount b_info.count = 0 b_info.ocount = 0 for factory in factories: if not factory.structure_is_built(): continue sg = len(factory.structure_garrison()) ml = factory.location.map_location() if sg > 0: for direction in try_nearby_directions(bc.Direction.North): if gc.can_unload(factory.id, direction): gc.unload(factory.id, direction) new = gc.sense_unit_at_location(ml.add(direction)) units.append(new) if new.unit_type == bc.UnitType.Worker and b_info.prevcount < MIN_WORKERS: new.info().is_B_group = True sg -= 1 if sg == 0: break ct = create_type() if gc.can_produce_robot(factory.id, ct): gc.produce_robot(factory.id, ct) index = 0 while index < len(units): print(index) moved = False unit = units[index] if unit.location.is_in_garrison(): index += 1 continue ml = unit.location.map_location() ui = unit.info() if unit.unit_type == bc.UnitType.Worker: if (b_info.prevcount < MIN_WORKERS or b_info.oprevcount < MIN_WORKERS) and unit.ability_heat() < HEAT_LIMIT and gc.karbonite() > KARBONITE_FOR_REPLICATE: #panic and replicate print("REPLICATING: %d %d" % (b_info.prevcount, b_info.oprevcount)) for direction in try_nearby_directions(bc.Direction.North): if gc.can_replicate(unit.id, direction): gc.replicate(unit.id, direction) new = gc.sense_unit_at_location(ml.add(direction)) units.append(new) if (ui.is_B_group and b_info.oprevcount >= MIN_WORKERS) or b_info.prevcount < 3: new.info().is_B_group = True elif (not ui.is_B_group and b_info.prevcount >= MIN_WORKERS) or b_info.oprevcount < 3: new.info().is_B_group = False else: new.info().is_B_group = b_info.prevcount <= b_info.oprevcount break #continue as normal, don't replicate if ui.is_B_group: b_info.count += 1 built = False if b_info.factory_loc is None and len(factories) < MIN_FACTORIES and gc.karbonite() > FACTORY_BUILD_COST: # try build factory for direction in try_nearby_directions(bc.Direction.North): nloc = ml.add(direction) if gc.can_blueprint(unit.id, bc.UnitType.Factory, direction) and factory_loc_check_update(state, nloc): #must blueprint gc.blueprint(unit.id, bc.UnitType.Factory, direction) b_info.factory_loc = make_poi(state, Point(nloc.y, nloc.x), factory=True) b_info.factory_id = gc.sense_unit_at_location(nloc).id built = True break elif b_info.factory_loc is None and gc.karbonite() > ROCKET_BUILD_COST: # try build rocket for direction in try_nearby_directions(bc.Direction.North): nloc = ml.add(direction) if gc.can_blueprint(unit.id, bc.UnitType.Rocket, direction): gc.blueprint(unit.id, bc.UnitType.Rocket, direction) b_info.factory_loc = make_poi(state, Point(nloc.y, nloc.x), factory=True) b_info.factory_id = gc.sense_unit_at_location(nloc).id built = True break elif b_info.factory_loc is not None: # should go to factory if gc.is_move_ready(unit.id) and not moved: try: goal, dist = state.destinations[b_info.factory_loc][ml.y][ml.x] except: index += 1 continue goal = goal.to_Direction() if dist == 1: lg = goal.rotate_left() rg = goal.rotate_right() if gc.can_move(unit.id, lg) and gc.is_move_ready(unit.id): gc.move_robot(unit.id, lg) moved = True elif gc.can_move(unit.id, rg) and gc.is_move_ready(unit.id): gc.move_robot(unit.id, rg) moved = True #else do nothing if gc.can_build(unit.id, b_info.factory_id): gc.build(unit.id, b_info.factory_id) if gc.unit(b_info.factory_id).structure_is_built(): ans = True fac = gc.unit(b_info.factory_id).unit_type == bc.UnitType.Factory if not fac: destmap = state.destinations[b_info.factory_loc] destmap.rocket = True destmap.factory = False b_info.factory_loc = None b_info.target -= 1 b_info.factory_id = None else: print("should build but didn't") print(index) elif not moved and gc.is_move_ready(unit.id): for direction in try_nearby_directions(goal): if gc.can_move(unit.id, direction): gc.move_robot(unit.id, direction) moved = True break try_harvest(state, unit, bc.Direction.North) if not built and b_info.factory_loc is None: print("tset") # go to cluster or switch B cluster cluster = state.karb_clusters[b_info.target] if cluster.karb > 0 and cluster[ml.y][ml.x] is not None: goal, dist = cluster[ml.y][ml.x] goal = goal.to_Direction() if ui.arrived or goal == bc.Direction.Center: ui.arrived = True process_worker(state, gc.unit(unit.id)) moved = True elif not moved and gc.is_move_ready(unit.id): ui.arrived = False unit = gc.unit(unit.id) for direction in try_nearby_directions(goal): if gc.can_move(unit.id, direction): gc.move_robot(unit.id, direction) moved = True break try_harvest(state, unit, goal.opposite()) else: # switch B cluster prev = b_info.target cid = 0 score = -1 for i in range(len(state.karb_clusters)): s = _cluster_worker_score(ml, state.karb_clusters[i]) if s > score and i != prev: cid, score = i, s b_info.target = cid if cluster[ml.y][ml.x] is None: ui.is_B_group = False index += 1 continue goal, dist = cluster[ml.y][ml.x] goal = goal.to_Direction() if not moved and gc.is_move_ready(unit.id): for direction in try_nearby_directions(goal): if gc.can_move(unit.id, direction): gc.move_robot(unit.id, direction) moved = True break try_harvest(state, unit, goal.opposite()) if not ui.is_B_group: b_info.ocount += 1 # should just harvest process_worker(state, unit) else: process_attacker(state, unit) index += 1 return ans
from geometry_msgs.msg import Point32,Pose from utilities import Point, AckermannVehicle , PPController import transforms3d as tf import numpy as np import os import rospkg rospack = rospkg.RosPack() ### Define constants: pi = 3.141592653589793238 # Define global variables: global currentPos currentPos = Point() global file_name # file_name = rospy.get_param("/file_name") file_name = "dummy_wp.txt" # Callback function for subscriber to Position and orientation topic: def XYZcallback(data): global currentPos currentPos.x = data.position.x currentPos.y = data.position.y euler = tf.euler.quat2euler([data.orientation.x,data.orientation.y,data.orientation.z,data.orientation.w]) #euler[1] = euler[1] - 1.57 #euler[2] = euler[2] + 3.14
import quantities as pq from graphics import BridgeGUI # Follow the 3 steps below to calculate and display the forces in your bridge. Make sure it makes sense. if __name__ == "__main__": # 1. ADJUST BRIDGE CONSTANTS AREA_LOAD = (5 + 1 + 0.75) * kN / pq.m ** 2 WIDTH = 5.4 * pq.m SPAN = 107.96 / 3 * pq.m HEIGHT_WIDTH_RATIO = 4 / 3 # Not used for equilateral truss NUMBER_OF_PANELS = 8 # The number of times the pattern repeats in the bridge SUPPORTS = { Point(0 * pq.m, 0 * pq.m), Point(SPAN, 0 * pq.m) } bridge_factory = BridgeFactory() # 2. CHANGE THE METHOD TO MATCH YOUR BRIDGE beams = bridge_factory.get_beams_for_k_bridge(NUMBER_OF_PANELS, SPAN, HEIGHT_WIDTH_RATIO) bridge = BridgeData(beams) load_applier = LoadApplier(bridge, SUPPORTS) # 3. PICK BETWEEN POINT LOAD AND UNIFORMLY DISTRIBUTED LOAD load_applier.add_point_load(Point(SPAN / 2, 0 * pq.m), 1 * kN) #load_applier.add_uniformly_distributed_load(load_per_unit_length=AREA_LOAD * WIDTH / 2)
import time rospack = rospkg.RosPack() ### Define constants: # Define global variables: global currentPos global file_name global laneParams global wpList global simStart global maxVel wpList = [] currentPos = Point() laneParams = lane() moreLane = True laneParams.rhoDot = 0 laneParams.rho = 0 laneParams.phi = 0 laneParams.y = 0 trial = 0 simStart = False maxVel = 3 wpList.append(Point(currentPos.x, currentPos.y)) wpList.append(Point(currentPos.x, currentPos.y)) wpList.append(Point(currentPos.x, currentPos.y)) wpList.append(Point(currentPos.x, currentPos.y))
class Mur(Selectionable, ButtonBehavior): def __init__(self, ax, ay, bx, by, evr): super(Mur, self).__init__(evr) self.a = Point(ax, ay) self.b = Point(bx, by) self.width = 150 self.pointsWidth = 20 self.collidewidth = 35 self.defColor = [.6, .1, .2] self.color = self.defColor self.isSelected = False def drawe(self): with self.canvas: self.canvas.clear() Color(self.color[0], self.color[1], self.color[2]) a = self.evr.decale(Point(self.a.x, self.a.y)) b = self.evr.decale(Point(self.b.x, self.b.y)) Line(points=[a.x, a.y, b.x, b.y]) if self.isSelected: center = (a.x - self.pointsWidth / 2, a.y - self.pointsWidth / 2) Ellipse(pos=center, size=(self.pointsWidth, self.pointsWidth)) center = (b.x - self.pointsWidth / 2, b.y - self.pointsWidth / 2) Ellipse(pos=center, size=(self.pointsWidth, self.pointsWidth)) return self def getaxplusbEquation(self): if self.b.x != self.a.x: aw = (self.b.y - self.a.y) / (self.b.x - self.a.x) else: aw = 999999 bw = -aw * self.a.x + self.a.y return [aw, bw] def getVector(self): vec = [self.b.x - self.a.x, self.b.y - self.a.y] longVec = sqrt((vec[0]**2) + (vec[1]**2)) vec[0] = vec[0] / longVec vec[1] = vec[1] / longVec return vec def getPerpVector(self): wallVector = self.getVector() return [-wallVector[1], wallVector[0]] def getNearestPointOnLine(self, point): perpVector = self.getPerpVector() if perpVector[0] == 0: perpVector[0] = 0.001 ap = perpVector[1] / perpVector[0] bp = -ap * point.x + point.y wallEq = self.getaxplusbEquation() xx = (bp - wallEq[1]) / (wallEq[0] - ap) return Point(xx, ap * xx + bp) def are2PointOnDifferentsSide(self, pt1, pt2): if not self.isAlignedWith(pt1) or not self.isAlignedWith(pt2): return False eq = self.getaxplusbEquation() y1 = eq[0] * pt1.x + eq[1] y2 = eq[0] * pt2.x + eq[1] if (y1 > pt1.y and y2 > pt2.y): return False if (y1 < pt1.y and y2 < pt2.y): return False return True def isAlignedWith(self, pt): if ((pt.x >= self.a.x and pt.x >= self.b.x) or (pt.x <= self.a.x and pt.x <= self.b.x)): return True if ((pt.y >= self.a.y and pt.y >= self.b.y) or (pt.y <= self.a.y and pt.y <= self.b.y)): return True return False def collide_point(self, x, y): if self.isAlignedWith(Point(x, y)): return False minPoint = self.getNearestPointOnLine(Point(x, y)) dist = minPoint.dist(Point(x, y)) if dist < self.collidewidth: return True return False def decaler(self, x, y): self.a.x += x self.b.x += x self.a.y += y self.b.y += y def isInterestedInMove(self, touch, x, y): distanceA = self.a.dist(Point(touch.x, touch.y)) distanceB = self.b.dist(Point(touch.x, touch.y)) if (distanceA < self.pointsWidth and distanceA <= distanceB): self.a.x += x self.a.y += y elif (distanceB < self.pointsWidth and distanceA > distanceB): self.b.x += x self.b.y += y else: self.decaler(x, y) return True def adjustedToMatchExtremity(self, touch): distA = self.a.dist(Point(touch.x, touch.y)) if distA < self.collidewidth: touch.x = self.a.x touch.y = self.a.y return touch distB = self.b.dist(Point(touch.x, touch.y)) if distB < self.collidewidth: touch.x = self.b.x touch.y = self.b.y return touch nearest = self.getNearestPointOnLine(Point(touch.x, touch.y)) distance = Point(touch.x, touch.y).dist(nearest) if distance < self.collidewidth: touch.x = nearest.x touch.y = nearest.y return touch def manif(self): self.color = self.selecColor self.isSelected = True def demanif(self): self.color = self.defColor self.isSelected = False