def get_output(self, packet: GameTickPacket) -> SimpleControllerState: # Read packet if not self.data.field_info_loaded: self.data.read_field_info(self.get_field_info()) if not self.data.field_info_loaded: return SimpleControllerState() self.data.read_packet(packet) # Check if match is over if packet.game_info.is_match_ended: return celebrate(self) self.renderer.begin_rendering() # This is where the logic happens ctrl = self.use_brain() # Additional rendering draw_ball_path(self, 4, 5) car_pos = self.data.my_car.pos self.renderer.draw_string_3d(car_pos, 1, 1, self.state.__class__.__name__, self.renderer.team_color(alt_color=True)) if self.data.car_spiking_ball is not None: self.renderer.draw_rect_3d( self.data.car_spiking_ball.pos + Vec3(z=20), 30, 30, True, self.renderer.purple()) self.renderer.end_rendering() # Save some stuff for next frame self.feedback(ctrl) return ctrl
def get_output_flatbuffer(self, game_tick_flatbuffer): if game_tick_flatbuffer is None or game_tick_flatbuffer.PlayersLength( ) - 1 < self.index: friendly_state = SimpleControllerState() else: friendly_state = self.get_output(game_tick_flatbuffer) builder = flatbuffers.Builder(0) ControllerState.ControllerStateStart(builder) ControllerState.ControllerStateAddSteer(builder, friendly_state.steer) ControllerState.ControllerStateAddThrottle(builder, friendly_state.throttle) ControllerState.ControllerStateAddPitch(builder, friendly_state.pitch) ControllerState.ControllerStateAddYaw(builder, friendly_state.yaw) ControllerState.ControllerStateAddRoll(builder, friendly_state.roll) ControllerState.ControllerStateAddJump(builder, friendly_state.jump) ControllerState.ControllerStateAddBoost(builder, friendly_state.boost) ControllerState.ControllerStateAddHandbrake(builder, friendly_state.handbrake) ControllerState.ControllerStateAddUseItem(builder, friendly_state.use_item) controller_state = ControllerState.ControllerStateEnd(builder) PlayerInput.PlayerInputStart(builder) PlayerInput.PlayerInputAddPlayerIndex(builder, self.index) PlayerInput.PlayerInputAddControllerState(builder, controller_state) player_input = PlayerInput.PlayerInputEnd(builder) builder.Finish(player_input) return builder
def get_output(self, game_tick_packet: GameTickPacket) -> SimpleControllerState: seconds = game_tick_packet.game_info.seconds_elapsed controller_state = SimpleControllerState() controller_state.steer = 0 controller_state.handbrake = 0 return controller_state
def __init__(self, name, team, index): super().__init__(name, team, index) self.info = GameInfo(index, team) self.last_turn_time = 0 self.controls = SimpleControllerState() self.controls.throttle = 1 self.controls.boost = 1
def __init__(self, name, team, index): self.index = index self.controller = SimpleControllerState() # Contants self.DODGE_TIME = 0.2 self.DISTANCE_TO_DODGE = 500 # Controller inputs self.throttle = 0 self.steer = 0 self.pitch = 0 self.yaw = 0 self.roll = 0 self.boost = False self.jump = False self.powerslide = False # Game values self.bot_pos = None self.bot_rot = None self.ball_pos = None self.bot_yaw = None # Dodging self.should_dodge = False self.on_second_jump = False self.next_dodge_time = 0
def __init__(self, name, team, index): super().__init__(name, team, index) import torch sys.path.insert(0, os.path.dirname( os.path.abspath(__file__))) # this is for separate process imports from examples.levi.torch_model import SymmetricModel self.ga = GeneticAlgorithm() self.Model = SymmetricModel self.torch = torch self.controller_state = SimpleControllerState() self.frame = 0 # frame counter for timed reset self.brain = 0 # bot counter for generation reset self.pop = 10 # population for bot looping self.num_best = 5 self.gen = 0 self.pos = 0 self.max_frames = 5000 self.bot_list = [self.Model() for _ in range(self.pop) ] # list of Individual() objects self.bot_list[-self.num_best:] = [ self.Model() ] * self.num_best # make sure last bots are the same self.bot_fitness = [0] * self.pop self.fittest = None # fittest object self.mut_rate = 0.2 # mutation rate self.distance_to_ball = [ math.inf ] * self.max_frames # set high for easy minimum self.input_formatter = LeviInputFormatter(team, index) self.output_formatter = LeviOutputFormatter(index)
def frugalController(agent, target, speed): controller_state = SimpleControllerState() location = toLocal(target, agent.me) angle_to_target = math.atan2(location.data[1], location.data[0]) controller_state.steer = steer(angle_to_target) speed -= ((angle_to_target**2) * 300) current_speed = velocity1D(agent.me).data[1] if current_speed < speed: controller_state.throttle = 1.0 elif current_speed - 50 > speed: controller_state.throttle = -1.0 else: controller_state.throttle = 0 time_difference = time.time() - agent.start if time_difference > 2.2 and distance2D( target, agent.me) > (velocity2D(agent.me) * 2.3) and abs( angle_to_target ) < 0.9 and current_speed < speed and current_speed > 220: agent.start = time.time() elif time_difference <= 0.1: controller_state.jump = True controller_state.pitch = -1 elif time_difference >= 0.1 and time_difference <= 0.15: controller_state.jump = False controller_state.pitch = -1 elif time_difference > 0.15 and time_difference < 1: controller_state.jump = True controller_state.yaw = controller_state.steer controller_state.pitch = -1 return controller_state
def fix_orientation(data: Data, point=None): controller = SimpleControllerState() strength = 0.22 ori = data.car.orientation if point is None and data.car.velocity.flat().length2() != 0: point = data.car.location + data.car.velocity.flat().rescale(500) pitch_error = -ori.pitch * strength controller.pitch = data.agent.pid_pitch.calc(pitch_error) roll_error = -ori.roll * strength controller.roll = data.agent.pid_roll.calc(roll_error) if point is not None: # yaw rotation can f up the other's so we scale it down until we are more confident about landing on the wheels car_to_point = point - data.car.location yaw_error = ori.front.ang_to_flat(car_to_point) * strength * 1.5 land_on_wheels01 = 1 - ori.up.ang_to(UP) / (math.pi * 2) controller.yaw = data.agent.pid_yaw.calc(yaw_error) * (land_on_wheels01 **6) # ! controller.throttle = 1 return controller
def go_to_and_stop(data: Data, point, boost=True, slide=True): controller_state = SimpleControllerState() car_to_point = point - data.car.location point_rel = data.car.relative_location(point) dist = car_to_point.length() steer_correction_radians = point_rel.ang() set_normal_steering_and_slide(controller_state, steer_correction_radians, dist, slide) vel_f = data.car.velocity.proj_onto_size(data.car.orientation.front) ex_brake_dist = (vel_f**2) / 2800 if dist > ex_brake_dist * 1.05: controller_state.throttle = 1 if dist > ex_brake_dist * 1.5 and boost: if not data.car.is_on_wall and not controller_state.handbrake and data.car.velocity.length( ) < 2000: if is_heading_towards2(steer_correction_radians, car_to_point.length()): if data.car.orientation.up.ang_to(UP) < math.pi * 0.3: controller_state.boost = True elif dist < ex_brake_dist: controller_state.throttle = -1 return controller_state
def go_towards_point_with_timing(data: Data, point: Vec3, eta: float, slide=False, alpha=1.25): controller_state = SimpleControllerState() car_to_point = point - data.car.location point_rel = data.car.relative_location(point) steer_correction_radians = point_rel.ang() dist = car_to_point.length() set_normal_steering_and_slide(controller_state, steer_correction_radians, dist, slide) vel_f = data.car.velocity.proj_onto(car_to_point).length() avg_vel_f = dist / eta target_vel_f = rlmath.lerp(vel_f, avg_vel_f, alpha) if vel_f < target_vel_f: controller_state.throttle = 1.0 # boost? if target_vel_f > 1410: if not data.car.is_on_wall and not controller_state.handbrake and data.car.velocity.length( ) < 2000: if is_heading_towards2(steer_correction_radians, dist): if data.car.orientation.up.ang_to(UP) < math.pi * 0.3: controller_state.boost = True elif (vel_f - target_vel_f) > 80: controller_state.throttle = -0.6 elif (vel_f - target_vel_f) > 100: controller_state.throttle = -1.0 return controller_state
def reach_point_with_timing_and_vel(data: Data, point: Vec3, eta: float, vel_d: float, slide=False): controller_state = SimpleControllerState() car_to_point = point.flat() - data.car.location point_rel = data.car.relative_location(point) steer_correction_radians = point_rel.ang() dist = car_to_point.length() set_normal_steering_and_slide(controller_state, steer_correction_radians, dist, slide) vel_f = data.car.velocity.proj_onto(car_to_point).length() acc_f = -2 * (2 * vel_f * eta + eta * vel_d - 3 * dist) / (eta * eta) if abs(steer_correction_radians) > 1: acc_f = acc_f * steer_correction_radians * steer_correction_radians force = acc_f / (1410 - vel_f) controller_state.throttle = min(max(-1, force), 1) # boost? if force > 1: if not data.car.is_on_wall and not controller_state.handbrake and data.car.velocity.length( ) < 2000: if is_heading_towards2(steer_correction_radians, dist): if data.car.orientation.up.ang_to(UP) < math.pi * 0.3: controller_state.boost = True return controller_state
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: # Read packet if not self.info.field_info_loaded: self.info.read_field_info(self.get_field_info()) if not self.info.field_info_loaded: return SimpleControllerState() self.info.read_packet(packet, self.get_field_info()) self.time = self.info.time dt = self.time - self.prev_time self.prev_time = self.time draw_debug(self.renderer, self.info.my_car, self.info.ball, self) # choose maneuver if self.maneuver is None: self.maneuver = self.choose_maneuver() if self.maneuver is not None: self.maneuver.step(dt) self.controls = self.maneuver.controls if self.maneuver.finished: self.maneuver = None self.renderer.end_rendering() return self.controls
def initialize_agent(self): self.interpreter = None cwd = os.getcwd() path = os.path.dirname(os.path.realpath(__file__)) os.chdir(path) env = Env() env.io = IOCallbacksStorageConstructor(get_input, on_output, on_finish, on_error, on_microtick) env.io.env = env program_dir = os.path.dirname(os.path.realpath(FILE_NAME)) with open(FILE_NAME, encoding='utf-8') as file: program = file.read() self.interpreter = AsciiDotsInterpreter(env, program, program_dir, True) self.p_time = 0 self.game_packet = [] self.controller_state = SimpleControllerState() os.chdir(cwd)
def exec(self, bot) -> SimpleControllerState: ct = bot.info.time - self._start_time controls = SimpleControllerState() controls.throttle = 1 car = bot.info.my_car # Target is allowed to be a function that takes bot as a parameter. Check what it is if callable(self.target): target = self.target(bot) else: target = self.target # To boost or not to boost, that is the question car_to_target = target - car.pos vel_p = proj_onto_size(car.vel, car_to_target) angle = angle_between(car_to_target, car.forward) controls.boost = self.boost and angle < self._boost_ang_req and vel_p < self._max_speed # States of dodge (note reversed order) # Land on ground if ct >= self._t_finishing: self._almost_finished = True if car.on_ground: self.done = True else: bot.maneuver = RecoveryManeuver(bot) self.done = True return controls elif ct >= self._t_second_unjump: # Stop pressing jump and rotate and wait for flip is done pass elif ct >= self._t_aim: if ct >= self._t_second_jump: controls.jump = 1 # Direction, yaw, pitch, roll if self.target is None: controls.roll = 0 controls.pitch = -1 controls.yaw = 0 else: target_local = dot(car_to_target, car.rot) target_local.z = 0 direction = normalize(target_local) controls.roll = 0 controls.pitch = -direction.x controls.yaw = sign(car.rot.get(2, 2)) * direction.y # Stop pressing jump elif ct >= self._t_first_unjump: pass # First jump else: controls.jump = 1 return controls
def deltaC(info: Info, target: Vector3, jt): #this controller takes a vector containing the required acceleration to reach a target, and then gets the car there c = SimpleControllerState() target_local = info.car_matrix.dot(target) if info.car.has_wheel_contact: #if on the ground if jt + 1.5 > info.game_time: #if we haven't jumped in the last 1.5 seconds c.jump = True else: c.jump = False jt = info.game_time else: c.steer,c.yaw,c.pitch,c.roll,error = default_pd(info, target_local, True) if target.length > 25: #stops boosting when "close enough" c.boost = True if error > 0.9: #don't boost if we're not facing the right way c.boost = False tsj = info.game_time - jt #time since jump if tsj < 0.215: c.jump = True elif tsj < 0.25: c.jump = False elif tsj >=0.25 and tsj < 0.27 and target.z > 560: #considers a double-jump if we still need to go up a lot c.jump = True c.boost = False c.yaw = c.pitch = c.roll = 0 else: c.jump = False c.throttle = 1 return c, jt
def get_controls(game_info, sub_state_machine): controls = SimpleControllerState() controls = FrontDodge(game_info.me).input() persistent = game_info.persistent return controls, persistent
def __init__(self): self.controls = SimpleControllerState() self.dodge = None self.last_point = None self.last_dodge_end_time = 0 self.dodge_cooldown = 0.26 self.recovery = None
def __init__(self, name, team, index): super().__init__(name, team, index) self.controller = SimpleControllerState() #TODO read from cfg instead of hardcoding # Game values self.logger.info("\n\nMy car index is {}\n\n".format(self.index)) self.bot_pos = None self.bot_vel = None self.bot_yaw = None self.bot_to_ball = 0 # Contants self.scale = 1 if self.team == 0: self.scale = -1 self.TEAM_OFFSET = 75 if self.team == 0: self.TEAM_OFFSET = -75 self.DODGE_TIME = 0.2 self.DODGE_HEIGHT = 300 self.DISTANCE_TO_DODGE = 550 self.DISTANCE_FROM_BALL_TO_BOOST = 1500 # The minimum distance the ball needs to be away from the bot for the bot to boost # The angle (from the front of the bot to the ball) at 1which the bot should start to powerslide. self.POWERSLIDE_ANGLE = 3 # Dodging self.should_dodge = False self.on_second_jump = False self.next_dodge_time = 0
def initialize_agent(self): self.controller_state = SimpleControllerState() self.me = physicsObject() self.ball = physicsObject() self.me.team = self.team self.allies = [] self.enemies = [] self.start = 5 self.flipStart = 0 self.flipping = False self.controller = None self.flipTimer = time.time() self.activeState = Kickoff(self) self.gameInfo = None self.onSurface = False self.boosts = [] self.fieldInfo = [] self.positions = [] self.time = 0 self.deltaTime = 0 self.maxSpd = 2200 self.ballPred = [] self.selectedBallPred = None self.ballDelay = 0 self.renderCalls = [] self.ballPredObj = None self.carHeight = 84 self.forward = True self.velAngle = 0 self.onWall = False self.stateTimer = time.time() self.contested = True self.flipTimer = time.time() self.goalPred = None
def begin_front_flip(self, packet, angle=0.0, right=1): # Do a flip. We will be committed to this for a few seconds and the bot will ignore other # logic during that time because we are setting the active_sequence. mult = 1 if right < 0: mult = -1 rad = math.radians(0) # set to 0 for now self.active_sequence = Sequence([ ControlStep(duration=0.05, controls=SimpleControllerState(jump=True)), ControlStep(duration=0.05, controls=SimpleControllerState(jump=False)), ControlStep(duration=0.1, controls=SimpleControllerState(jump=True, pitch=-math.cos(rad), yaw=mult * math.sin(rad))), ControlStep(duration=0.8, controls=SimpleControllerState()), ]) # Return the controls associated with the beginning of the sequence so we can start right away. return self.active_sequence.tick(packet)
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: # Read packet if not self.info.field_info_loaded: self.info.read_field_info(self.get_field_info()) if not self.info.field_info_loaded: return SimpleControllerState() self.info.read_packet(packet) # Check if match is over if packet.game_info.is_match_ended: return moves.celebrate(self) # Assuming we win! self.renderer.begin_rendering() controller = self.use_brain() # Additional rendering if self.do_rendering: draw_ball_path(self, 4, 5) doing = self.maneuver or self.choice if doing is not None: status_str = f'{self.name}: {doing.__class__.__name__}' self.renderer.draw_string_2d( 300, 700 + self.index * 20, 1, 1, status_str, self.renderer.team_color(alt_color=True)) self.renderer.end_rendering() # Save some stuff for next tick self.feedback(controller) return controller
def exampleController(agent, target_object, target_speed): location = toLocal(target_object, agent.me) controller_state = SimpleControllerState() angle_to_ball = math.atan2(location.data[1], location.data[0]) current_speed = velocity2D(agent.me) #steering controller_state.steer = steer(angle_to_ball) #throttle if target_speed > current_speed: controller_state.throttle = 1.0 if target_speed > 1400 and agent.start > 2.2 and current_speed < 2250: controller_state.boost = True elif target_speed < current_speed: controller_state.throttle = 0 #dodging time_difference = time.time() - agent.start if time_difference > 2.2 and distance2D(target_object, agent.me) > ( velocity2D(agent.me) * 2.5) and abs(angle_to_ball) < 1.3: agent.start = time.time() elif time_difference <= 0.1: controller_state.jump = True controller_state.pitch = -1 elif time_difference >= 0.1 and time_difference <= 0.15: controller_state.jump = False controller_state.pitch = -1 elif time_difference > 0.15 and time_difference < 1: controller_state.jump = True controller_state.yaw = controller_state.steer controller_state.pitch = -1 return controller_state
def initialize_agent(self): mutators = self.get_match_settings().MutatorSettings() gravity = [ Vector3(0, 0, -650), Vector3(0, 0, -325), Vector3(0, 0, -1137.5), Vector3(0, 0, -3250) ] self.gravity = gravity[mutators.GravityOption()] #A list of cars for both teammates and opponents self.friends = [] self.foes = [] #This holds the carobject for our agent self.me = car_object(self.index) self.ball = ball_object() self.game = game_object() #A list of boosts self.boosts = [] #goals self.friend_goal = goal_object(self.team) self.foe_goal = goal_object(not self.team) #A list that acts as the routines stack self.stack = [] #Game time self.time = 0.0 #Whether or not GoslingAgent has run its get_ready() function self.ready = False #the controller that is returned to the framework after every tick self.controller = SimpleControllerState() #a flag that tells us when kickoff is happening self.kickoff_flag = False
def CeilingRushController( agent, target_object1, target_object2): #target_object es un objeto tipo obj controller_state = SimpleControllerState() '''if distance2D(agent.me,agent.pointA)<distance2D(agent.me,agent.pointB) and agent.me.location.data[2]>2800: target_object = target_object2 location = agent.pointB.local_location angle_to_target = math.atan2(location.data[1],location.data[0]) else: target_object = target_object1 location = agent.pointA.local_location angle_to_target = math.atan2(location.data[1],location.data[0])''' target_object = target_object1 location = agent.pointA.local_location angle_to_target = math.atan2(location.data[1], location.data[0]) draw_debug(agent, agent.renderer, target_object.location.data) angle_velocity = math.atan2(agent.me.velocity.data[1], agent.me.velocity.data[1]) #draw_debug(agent.renderer,target_object.location.data) current_speed = velocity2D(agent.me) #steering if abs(angle_to_target) < math.pi / 4: controller_state.handbrake = False elif abs(angle_to_target) < math.pi and abs(angle_to_target) > math.pi / 2: controller_state.handbrake = True if agent.me.location.data[2] < 1800: controller_state.steer = sign(angle_to_target) * min( 1, abs(2 * angle_to_target)) else: controller_state.steer = 0 #throttle controller_state.throttle = 1 return controller_state
def exampleController(agent, target_object,target_speed): distance = distance2D(agent.me.location,target_object.location) if distance > 400: #print("switching to efficient") agent.state = efficientMover return efficientMover(agent,target_object,target_speed) controller_state = SimpleControllerState() controller_state.handbrake = False car_direction = get_car_facing_vector(agent.me) car_to_ball = agent.me.location - target_object.location steer_correction_radians = steer(car_direction.correction_to(car_to_ball)) current_speed = getVelocity(agent.me.velocity) #steering controller_state.steer = steer(steer_correction_radians) #throttle if target_speed > current_speed: controller_state.throttle = 1.0 if target_speed > 1400 and current_speed < 2250: controller_state.boost = True elif target_speed < current_speed: controller_state.throttle = 0 return controller_state
def exampleController(agent, target_object): #target_object es un objeto tipo obj location = target_object.local_location controller_state = SimpleControllerState() angle_to_target = math.atan2(location.data[1], location.data[0]) angle_velocity = math.atan2(agent.me.velocity.data[1], agent.me.velocity.data[1]) #draw_debug(agent.renderer,location.data) draw_debug(agent, agent.renderer, target_object.location.data) current_speed = velocity2D(agent.me) #steering if abs(angle_to_target) < math.pi / 4: if agent.me.has_wheel_contact == True: controller_state.boost = True controller_state.handbrake = False else: controller_state.boost = False controller_state.handbrake = True controller_state.steer = sign(angle_to_target) * min( 1, abs(2 * angle_to_target)) controller_state.throttle = 1 #dodging if abs(angle_to_target) < math.pi / 2 and abs( angle_velocity) < math.pi / 3: dodging(agent, target_object, controller_state, angle_to_target) return controller_state
def initialize_agent(self): self.controller_state = SimpleControllerState() self.frame = 0 # frame counter for timed reset self.brain = -1 # bot counter for generation reset self.pop = 10 # population for bot looping self.out = [None] * self.pop # output of nets self.gen = 0 self.pos = 0 self.botList = [] #list of Individual() objects self.fittest = Fittest() #fittest object self.mutRate = 0.1 #mutation rate self.distance_to_ball = [10000] * 10000 #set high for easy minumum #CREATE BOTS AND NETS for i in range(self.pop): self.botList.append(Individual()) self.botList[i].create_node() self.botList[i].name = "Bot " + str(i) #ASSIGN WEIGHTS for i in self.botList: print("INIT: " + i.name) for p in range(0, len(i.weights)): i.weights[p] = random.uniform(-self.mutRate, self.mutRate) print("----" + str(i.weights[p]))
def follow_line(self, current_state): controller_input = SimpleControllerState() controller_input = GroundTurn( current_state, current_state.copy_state(pos=self.piece.end)).input() return controller_input
def __init__(self, name, team, index): super().__init__(name, team, index) self.controller_state = SimpleControllerState() self.ball_pos = vec3(0, 0, 0) self.defensive_goal = vec3(0, -5120, 0) self.offensive_goal = vec3(0, 5120, 0) if team == 1: self.defensive_goal = vec3(0, 5120, 0) self.offensive_goal = vec3(0, -5120, 0) self.action = self.kickoff self.action_display = "none" self.pos = None self.yaw = None self.pitch = None self.next_dodge_time = 0 self.on_second_jump = False self.field_info = None # CONSTANTS self.POWERSLIDE_ANGLE = 3 # radians self.TURN_THRESHOLD = 5 # degrees self.DODGE_THRESHOLD = 300 # unreal units self.DODGE_TIME = 0.2 # seconds self.BALL_FAR_AWAY_DISTANCE = 1500
def __init__(self, name, team, index): super().__init__(name, team, index) self.oldTime = time.time() self.halfflipping = False self.flip_start_time = 0.0 self.dodging = False self.dodge_target = None self.dodge_pitch = 0 self.dodge_roll = 0 self.next_dodge_time = 0 self.location = Vector3() self.rotation = Rotator() self.velocity = Vector3() self.speed = 0 self.output = SimpleControllerState() self.boost_pads = list() self.boost_locations = list() self.boost = 0 self.supersonic = False self.on_ground = True if self.team == 0: self.goal = blue_goal self.enemy_goal = orange_goal else: self.goal = orange_goal self.enemy_goal = blue_goal self.start = time.time() self.opponents = list() self.teammates = list()