예제 #1
0
class Agent(BaseAgent):

    def __init__(self, name, team, index):
        Game.set_mode("soccar")
        self.game = Game(index, team)

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.game.read_game_information(packet, self.get_rigid_body_tick(), self.get_field_info())

        # make a copy of the ball's info that we can change
        b = Ball(self.game.ball)

        ball_predictions = []
        for i in range(360):

            # simulate the forces acting on the ball for 1 frame
            b.step(1.0 / 120.0)

            # and add a copy of new ball position to the list of predictions
            ball_predictions.append(vec3(b.location))

        self.renderer.begin_rendering()
        red = self.renderer.create_color(255, 255, 30, 30)
        self.renderer.draw_polyline_3d(ball_predictions, red)
        self.renderer.end_rendering()

        return controller.get_output()
예제 #2
0
class BaseTestAgent(BaseAgent):

    def __init__(self, name, team, index):
        super(BaseTestAgent, self).__init__(name, team, index)
        self.info = Game(index, team)
        self.action = self.create_action()
        self.initialized = False

    def get_output(self, game_tick_packet: GameTickPacket) -> SimpleControllerState:
        self.info.read_game_information(game_tick_packet,
                                        self.get_rigid_body_tick(),
                                        self.get_field_info())
        self.action.update_status(self.info)
        self.test_process(game_tick_packet)
        return self.action.get_output(self.info)

    def create_action(self) -> BaseAction:
        raise NotImplementedError

    def test_process(self, game_tick_packet: GameTickPacket):
        if not self.initialized and not self.matchcomms.incoming_broadcast.empty():
            self.matchcomms.incoming_broadcast.get_nowait()
            self.initialized = True

        if self.initialized:
            self.action.update_status(self.info)

        if self.initialized and self.action.finished:
            self.matchcomms.outgoing_broadcast.put_nowait('done')
            self.initialized = False
예제 #3
0
 def __init__(self, name, team, index):
     """Initializing all parameters of the bot"""
     super().__init__(name, team, index)
     Game.set_mode("soccar")
     self.info = Game(index, team)
     self.team = team
     self.index = index
     self.drive = None
     self.dodge = None
     self.halfflip = None
     self.controls = SimpleControllerState()
     self.kickoff = False
     self.prev_kickoff = False
     self.in_front_off_ball = False
     self.conceding = False
     self.kickoff_Start = None
     self.step = Step.Shooting
     self.time = 0
     self.my_goal = None
     self.their_goal = None
     self.teammates = []
     self.has_to_go = False
     self.closest_to_ball = False
     self.defending = False
     self.set_state = False
     self.ball_prediction_np = []
예제 #4
0
    def __init__(self, name, team, index):
        self.game = Game(index, team)
        self.controls = SimpleControllerState()

        self.timer = 0.0
        self.action = None
        random.seed(0)
예제 #5
0
class BaseTestAgent(BaseAgent):
    def __init__(self, name, team, index):
        super(BaseTestAgent, self).__init__(name, team, index)
        self.info = Game(index, team)
        self.mechanic = self.create_mechanic()

    def get_output(self,
                   game_tick_packet: GameTickPacket) -> SimpleControllerState:
        self.info.read_game_information(game_tick_packet,
                                        self.get_rigid_body_tick(),
                                        self.get_field_info())
        self.test_process(game_tick_packet)
        return self.get_mechanic_controls()

    def create_mechanic(self) -> BaseMechanic:
        raise NotImplementedError

    def get_mechanic_controls(self) -> SimpleControllerState:
        raise NotImplementedError

    def test_process(self, game_tick_packet: GameTickPacket):
        pass

    def initialize_agent(self):
        pass
예제 #6
0
파일: derevo.py 프로젝트: robbai/NVDerevo
 def __init__(self, name, team, index):
     """Initializing all parameters of the bot"""
     super().__init__(name, team, index)
     Game.set_mode("soccar")
     self.info = Game(index, team)
     self.team = team
     self.index = index
     self.defending = False
     self.conceding = False
     self.bounces = []
     self.drive = None
     self.catching = None
     self.dodge = None
     self.halfflip = None
     self.dribble = None
     self.controls = SimpleControllerState()
     self.kickoff = False
     self.prev_kickoff = False
     self.in_front_off_the_ball = False
     self.kickoff_Start = None
     self.step = Step.Catching
     self.time = 0
     self.my_goal = None
     self.their_goal = None
     self.ball_bouncing = False
예제 #7
0
 def __init__(self, name, team, index):
     Game.set_mode("soccar")
     self.game = Game(index, team)
     self.time = 0
     self.index = index
     self.name = name
     self.team = team
예제 #8
0
    def initialize_agent(self):
        # This runs once before the bot starts up
        self.controllerState = SimpleControllerState()
        self.stateMachine = StateMachine(self)
        self.spikeWatcher = SpikeWatcher()

        self.lastTime = 0
        self.realLastTime = 0
        self.doneTicks = 0
        self.skippedTicks = 0
        self.ticksThisPacket = 0
        self.FPS = 120
        self.lastQuickChatTime = 0
        self.secondMessage = None
        self.currentTick = 0
        self.firstTpsReport = True

        self.game = Game()
        self.game.set_mode("soccar")
        self.car = self.game.cars[self.index]
        self.reorientML = ReorientML(self.car)

        self.lastJumpTick = -math.inf
        self.maxDodgeTick = 0
        self.jumpReleased = True
        self.lastDodgeTick = -math.inf
        self.lastController = SimpleControllerState()
예제 #9
0
    def __init__(self, name, team, index):
        self.game = Game(index, team)
        self.controls = SimpleControllerState()

        self.timer = 0.0
        self.timeout = 3.0

        self.action = None
        self.state = State.RESET
예제 #10
0
    def initialize_agent(self):
        # This runs once before the bot starts up
        self.controls = SimpleControllerState()

        self.info = Game(self.team)
        self.car = self.info.cars[self.index]
        self.hover = Hover(self.car, self.info)
        self.kickoff = Kickoff(self.car, self.info)
        self.sign = 2 * self.team - 1  # 1 if orange, else -1
예제 #11
0
    def __init__(self, name, team, index):

        self.index = index
        self.json = Logger()
        self.controls = SimpleControllerState()

        self.game = Game(index, team)

        self.counter = 0
        self.log = None
예제 #12
0
파일: bot.py 프로젝트: RLBot/RLBotPack
    def initialize_agent(self):
        self.controls = SimpleControllerState()

        self.info = Game(self.team)
        self.car = self.info.cars[self.index]

        self.hover = GetToAirPoint(self.car, self.info)
        self.kickoff = Kickoff(self.car, self.info)

        self.sign = 2 * self.team - 1  # 1 if orange, else -1
예제 #13
0
    def __init__(self, name, team, index):
        super().__init__(name, team, index)
        Game.set_mode("soccar")
        self.game = Game(index, team)
        self.name = name
        self.controls = SimpleControllerState()
        self.timer = 0.0

        self.drive = Drive(self.game.my_car)
        self.dodge = None
        self.turn = None
        self.state = State.RESET
예제 #14
0
def get_hit_frame_numbers(df: pd.DataFrame):
    ball_df = df[DF_BALL_PREFIX]

    hit_frame_numbers = get_hit_frame_numbers_by_ball_ang_vel(df)
    # Filter by hit_team_no
    hit_frame_numbers = ball_df.loc[hit_frame_numbers].index[~ball_df.loc[
        hit_frame_numbers, "hit_team_no"].isna()].tolist()
    logger.info(f"hit: {hit_frame_numbers}")

    delta_df = df.loc[:, (DF_GAME_PREFIX, 'delta')]
    RLUGame.set_mode("soccar")
    filtered_hit_frame_numbers = []
    for frame_number in hit_frame_numbers:
        previous_frame_number = frame_number - 1
        ball_previous_frame = ball_df.loc[previous_frame_number, :]
        initial_ang_vel = ball_previous_frame.loc[[
            'ang_vel_x', 'ang_vel_y', 'ang_vel_z'
        ]].values

        ball = Ball()
        # noinspection PyPropertyAccess
        ball.location = vec3(
            *ball_previous_frame.loc[['pos_x', 'pos_y', 'pos_z']])
        # noinspection PyPropertyAccess
        ball.velocity = vec3(
            *ball_previous_frame.loc[['vel_x', 'vel_y', 'vel_z']])
        # noinspection PyPropertyAccess
        ball.angular_velocity = vec3(*initial_ang_vel)

        frame_delta = delta_df[frame_number]
        delta_simulated = 0
        while delta_simulated < frame_delta:
            dt = 1 / 120
            time_to_simulate = min(dt, frame_delta - delta_simulated)
            ball.step(time_to_simulate)
            delta_simulated += time_to_simulate

        simulated_ball_ang_vel = np.array([
            ball.angular_velocity[0], ball.angular_velocity[1],
            ball.angular_velocity[2]
        ])
        actual_ball_ang_vel = ball_df.loc[
            frame_number, ['ang_vel_x', 'ang_vel_y', 'ang_vel_z']].values
        actual_ang_vel_change = ((actual_ball_ang_vel -
                                  initial_ang_vel)**2).sum()**0.5
        end_ang_vel_difference = ((simulated_ball_ang_vel -
                                   actual_ball_ang_vel)**2).sum()**0.5

        relative_ang_vel_difference = end_ang_vel_difference / actual_ang_vel_change
        if relative_ang_vel_difference > 0.8:
            filtered_hit_frame_numbers.append(frame_number)
    return filtered_hit_frame_numbers
예제 #15
0
    def __init__(self, name, team, index):
        Game.set_mode("soccar")
        self.game = Game(index, team)
        self.controls = SimpleControllerState()

        self.timer = 0.0
        self.timeout = 5.0

        self.aerial = None
        self.turn = None
        self.state = State.RESET
        self.ball_predictions = None

        self.target_ball = None
예제 #16
0
class MyBot(BaseAgent):
    def initialize_agent(self):
        # This runs once before the bot starts up
        self.controls = SimpleControllerState()

        self.info = Game(self.team)
        self.car = self.info.cars[self.index]
        self.hover = Hover(self.car, self.info)
        self.kickoff = Kickoff(self.car, self.info)
        self.sign = 2 * self.team - 1  # 1 if orange, else -1

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.info.read_game_information(packet, self.get_field_info())

        if self.info.kickoff_pause and dist(self.info.ball.position,
                                            self.car.position) < 4000:
            self.kickoff.step(self.info.time_delta)
            self.controls = self.kickoff.controls
            return self.controls

        ball_prediction = self.get_ball_prediction_struct()
        future_goal = self.find_future_goal(ball_prediction)
        if future_goal and not packet.game_info.is_kickoff_pause:
            target = future_goal
        else:
            target = vec3(0, HOVER_IDLE_Y * self.sign, HOVER_IDLE_HEIGHT)

        # render target
        self.renderer.begin_rendering("target")
        self.renderer.draw_rect_3d(target, 10, 10, True, self.renderer.cyan())
        self.renderer.end_rendering()

        # update controls
        self.hover.target = target
        self.hover.step(self.info.time_delta)
        self.controls = self.hover.controls

        return self.controls

    def find_future_goal(self, ball_prediction):
        for step in ball_prediction.slices[:ball_prediction.num_slices]:
            pos = step.physics.location
            if sign(pos.y) != self.sign:
                continue
            if abs(pos.y) > HOVER_TARGET_Y and abs(
                    pos.x) < HOVER_MAX_SIDE and pos.z < HOVER_MAX_HEIGHT:
                return vec3(pos.x, pos.y,
                            pos.z if pos.z > 100 else HOVER_MIN_HEIGHT)
        return None
예제 #17
0
    def __init__(self, name, team, index):
        Game.set_mode("soccar")
        self.game = Game(index, team)
        self.controls = SimpleControllerState()

        self.timer = 0.0
        self.timeout = 5.0

        self.aerial = None
        self.turn = None
        self.state = State.RESET
        self.ball_predictions = None

        self.target_ball = None
        self.log = open("../../analysis/aerial/info.ndjson", "w")
예제 #18
0
 def __init__(self, name, team, index):
     """Initializing all parameters of the bot"""
     super().__init__(name, team, index)
     Game.set_mode("soccar")
     self.game = Game(index, team)
     self.name = name
     self.team = team
     self.index = index
     self.drive = None
     self.dodge = None
     self.controls = SimpleControllerState()
     self.kickoff = False
     self.prev_kickoff = False
     self.kickoffStart = None
     self.step = None
예제 #19
0
class Agent(BaseAgent):
    def __init__(self, name, team, index):
        self.game = Game(index, team)
        self.controls = SimpleControllerState()
        self.action = None

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        if not self.action:
            self.action = DrivePath(self.game.my_car)
            self.action.target = vec3(0, 5000, 0)
            self.action.arrival_tangent = vec3(pi * 5, 0, 0)
            self.action.arrival_speed = 2300
            self.action.recalculate_path()

        if controller.L1:
            time_estimate = self.action.recalculate_path()
            self.action.arrival_time = self.game.my_car.time + 1.1 * time_estimate

            self.controls = controller.get_output()

        else:
            self.action.step(self.game.time_delta)

            if self.action.finished:
                self.controls = SimpleControllerState()
            else:
                self.controls = self.action.controls

        if self.action:

            vertices = self.action.path.points

            self.renderer.begin_rendering("path")
            red = self.renderer.create_color(255, 230, 255, 30)
            for i in range(0, len(vertices) - 1):
                self.renderer.draw_line_3d(vertices[i], vertices[i + 1], red)

            self.renderer.draw_string_2d(
                50, 50, 3, 3,
                str(self.action.arrival_time - self.game.my_car.time), red)
            self.renderer.end_rendering()

        return self.controls
예제 #20
0
class Derevo(BaseAgent):
    """Main bot class"""
    def __init__(self, name, team, index):
        """Initializing all parameters of the bot"""
        super().__init__(name, team, index)
        Game.set_mode("soccar")
        self.game = Game(index, team)
        self.name = name
        self.team = team
        self.index = index
        self.drive = None
        self.dodge = None
        self.controls = SimpleControllerState()
        self.kickoff = False
        self.prev_kickoff = False
        self.kickoffStart = None
        self.step = None

    def initialize_agent(self):
        """Initializing all parameters which require the field info"""
        init_boostpads(self)
        self.drive = Drive(self.game.my_car)
        self.dodge = Dodge(self.game.my_car)

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        """The main method which receives the packets and outputs the controls"""
        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())
        update_boostpads(self, packet)
        self.prev_kickoff = self.kickoff
        self.kickoff = packet.game_info.is_kickoff_pause and norm(
            vec2(self.game.ball.location - vec3(0, 0, 0))) < 100
        if self.kickoff and not self.prev_kickoff:
            init_kickoff(self)
            self.prev_kickoff = True
        elif self.kickoff or self.step is Step.Dodge_2:
            kick_off(self)
        else:
            self.drive.target = self.game.ball.location
            self.drive.speed = 1410
            self.drive.step(self.game.time_delta)
            self.controls = self.drive.controls
        if not packet.game_info.is_round_active:
            self.controls.steer = 0
        return self.controls
예제 #21
0
    def __init__(self):
        super().__init__("Laser_boi")
        if TWITCH_CHAT_INTERACTION:
            self.action_broker = MyActionBroker(self)
        self.known_players: List[PlayerInfo] = []
        self.game = Game()
        self.game.set_mode("soccar")
        self.car_lasers = {}
        self.last_seconds_elapsed = 0
        self.forces = {}
        self.lastScore = 0
        self.isKickoff = -3
        self.isPaused = True
        self.boostContent = {}
        self.boost = {}

        self.lastFullSecond = 0
        self.ticksThisSecond = 0
예제 #22
0
class Agent(BaseAgent):
    def __init__(self, name, team, index):
        self.game = Game(index, team)
        self.controls = SimpleControllerState()
        self.action = None

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        if not self.action:
            self.action = Drive(self.game.my_car)
            self.action.speed = 1400

        self.action.target = self.game.ball.location
        self.action.step(self.game.time_delta)

        self.controls = self.action.controls

        return self.controls
예제 #23
0
class PythonExample(BaseAgent):
    def __init__(self, name, team, index):

        self.index = index
        self.json = Logger()
        self.controls = SimpleControllerState()

        self.game = Game(index, team)

        self.counter = 0
        self.log = None

    def get_output(self, packet):

        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        controls = controller.get_output()

        if controller.L1:

            if not self.log:
                self.log = open(f"log_{self.counter}.ndjson", "w")
                self.counter += 1

            then = time.perf_counter()
            self.log.write(f"{{\"car\":{self.game.my_car.to_json()},"
                           f"\"ball\":{self.game.ball.to_json()}}}\n")
            now = time.perf_counter()

            print(now - then)

        else:
            if self.log:
                self.log.close()
                self.log = None

        return controls
예제 #24
0
    def __init__(self, name, team, index):
        super().__init__(name, team, index)
        Game.set_mode("soccar")
        ie = webbrowser.get('windows-default')
        ie.open('https://www.twitch.tv/donutkiller_pro')
        self.game = Game(index, team)
        self.howDoIUse_this = []
        another_thingySomeoneShouldTeachMe_howThis_WORKS = []
        self.howDoIUse_this.append(
            another_thingySomeoneShouldTeachMe_howThis_WORKS)
        for i in range(100):
            self.howDoIUse_this.append(0)

        countyThingy_DONOTTOUCH = 0
        while countyThingy_DONOTTOUCH < 8:
            Number_iGuess = whoops(1, 101)
            if Number_iGuess not in another_thingySomeoneShouldTeachMe_howThis_WORKS:
                another_thingySomeoneShouldTeachMe_howThis_WORKS.append(
                    Number_iGuess)
                countyThingy_DONOTTOUCH += 1

        self.flippityThe_CAR = 0
        self.CountyTHIS_ALSOdonttuch = 0
        self.WHOOPITYScooPTI = 0
예제 #25
0
파일: bot.py 프로젝트: RLBot/RLBotPack
class MyBot(BaseAgent):
    @staticmethod
    def create_agent_configurations(config: ConfigObject):
        params = config.get_header(BOT_CONFIG_AGENT_HEADER)
        params.add_value("hover_min_height", int, default=140)

    def load_config(self, config_header):
        self.hover_min_height = config_header.getint("hover_min_height")

    def initialize_agent(self):
        self.controls = SimpleControllerState()

        self.info = Game(self.team)
        self.car = self.info.cars[self.index]

        self.hover = GetToAirPoint(self.car, self.info)
        self.kickoff = Kickoff(self.car, self.info)

        self.sign = 2 * self.team - 1  # 1 if orange, else -1

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.info.read_game_information(packet, self.get_field_info())

        if self.info.kickoff_pause and dist(self.info.ball.position,
                                            self.car.position) < 4000:
            self.kickoff.step(self.info.time_delta)
            self.controls = self.kickoff.controls
            return self.controls

        ball_prediction = self.get_ball_prediction_struct()
        future_goal = self.find_future_goal(ball_prediction)
        if future_goal and not packet.game_info.is_kickoff_pause:
            target = future_goal

            # the ball prediction is slightly wrong, the ball will be closer to the center of the goal
            target[0] *= 0.9
            target[2] *= 0.8

            target[2] += 50
        else:
            is_seeking_our_goal = sign(self.info.ball.velocity[1]) == sign(
                self.car.position[1])
            # even if the ball prediction didn't end up in our goal, move to the side of the ball to be ready
            idle_x = clip(self.info.ball.position[0], -700,
                          700) if is_seeking_our_goal else 0
            target = vec3(idle_x, HOVER_IDLE_Y * self.sign, HOVER_IDLE_HEIGHT)

        # render target and ball prediction
        polyline = [
            ball_prediction.slices[i].physics.location
            for i in range(0, 100, 5)
        ]
        self.renderer.draw_polyline_3d(polyline, self.renderer.yellow())
        self.renderer.draw_rect_3d(target, 10, 10, True, self.renderer.cyan())
        self.renderer.draw_line_3d(self.car.position, target,
                                   self.renderer.lime())

        # update controls
        self.hover.target = target
        self.hover.step(self.info.time_delta)
        self.controls = self.hover.controls

        return self.controls

    def find_future_goal(self, ball_prediction):
        for step in ball_prediction.slices[:ball_prediction.num_slices]:
            pos = step.physics.location
            if sign(pos.y) != self.sign:
                continue
            if abs(pos.y) > HOVER_TARGET_Y and abs(
                    pos.x) < HOVER_MAX_SIDE and pos.z < HOVER_MAX_HEIGHT:
                return vec3(
                    pos.x, pos.y, pos.z if pos.z > self.hover_min_height else
                    self.hover_min_height)
        return None
예제 #26
0
class Puffy(BaseAgent):
    def initialize_agent(self):
        # This runs once before the bot starts up
        self.controllerState = SimpleControllerState()
        self.stateMachine = StateMachine(self)
        self.spikeWatcher = SpikeWatcher()

        self.lastTime = 0
        self.realLastTime = 0
        self.doneTicks = 0
        self.skippedTicks = 0
        self.ticksThisPacket = 0
        self.FPS = 120
        self.lastQuickChatTime = 0
        self.secondMessage = None
        self.currentTick = 0
        self.firstTpsReport = True

        self.game = Game()
        self.game.set_mode("soccar")
        self.car = self.game.cars[self.index]
        self.reorientML = ReorientML(self.car)

        self.lastJumpTick = -math.inf
        self.maxDodgeTick = 0
        self.jumpReleased = True
        self.lastDodgeTick = -math.inf
        self.lastController = SimpleControllerState()

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        # self.renderer.begin_rendering()
        self.packet = packet

        self.handleTime()

        self.game.read_game_information(packet, self.get_field_info())
        self.spikeWatcher.read_packet(packet)

        ballY = packet.game_ball.physics.location.y

        if abs(
                ballY
        ) > 5120 + 60 and packet.game_info.seconds_elapsed - self.lastQuickChatTime > 15:
            teamDirection = 1 if packet.game_ball.latest_touch.team == 0 else -1
            firstByToucher = True
            if ballY * teamDirection > 0:
                if packet.game_ball.latest_touch.team == packet.game_cars[
                        self.index].team:
                    firstMessage, secondMessage = QuickChats.Compliments_NiceShot, QuickChats.Compliments_Thanks
                    firstByToucher = False
                else:
                    firstMessage, secondMessage = QuickChats.Apologies_Whoops, QuickChats.Apologies_NoProblem

            else:
                if packet.game_ball.latest_touch.team == packet.game_cars[
                        self.index].team:
                    firstMessage, secondMessage = QuickChats.Compliments_WhatASave, QuickChats.Apologies_NoProblem
                    firstByToucher = False
                else:
                    firstMessage, secondMessage = QuickChats.Compliments_WhatASave, QuickChats.Reactions_Savage

            bribbleBots = []
            latestTouchIsBribble = False
            for carIndex in range(packet.num_cars):
                car = packet.game_cars[carIndex]
                if car.team == self.team and "Puffy" in car.name:
                    bribbleBots.append(carIndex)
                    if packet.game_ball.latest_touch.player_index == carIndex:
                        latestTouchIsBribble = True

            if len(bribbleBots) == 1:
                self.send_quick_chat(QuickChats.CHAT_EVERYONE, firstMessage)
                self.secondMessage = secondMessage
            else:
                sendFirst = packet.game_ball.latest_touch.player_index == self.index or (
                    not latestTouchIsBribble
                    and self.index == min(bribbleBots))
                if not sendFirst ^ firstByToucher:
                    self.send_quick_chat(QuickChats.CHAT_EVERYONE,
                                         firstMessage)
                else:
                    self.secondMessage = secondMessage

            self.lastQuickChatTime = packet.game_info.seconds_elapsed

        elif packet.game_info.seconds_elapsed - self.lastQuickChatTime > 0.2 and self.secondMessage != None:
            self.send_quick_chat(QuickChats.CHAT_EVERYONE, self.secondMessage)
            self.secondMessage = None

        self.stateMachine.tick(packet)
        self.trackJump(self.stateMachine.currentState.controller)

        # self.renderer.end_rendering()
        return self.stateMachine.currentState.controller

    def trackJump(self, controller: SimpleControllerState):

        if controller.jump and not self.lastController.jump and self.car.on_ground and self.currentTick - self.lastJumpTick > 28:
            self.lastJumpTick = self.currentTick
            self.jumpReleased = False

        if self.car.on_ground:
            self.maxDodgeTick = math.inf
            self.lastJumpTick = -math.inf
            self.lastDodgeTick = -math.inf
        elif self.lastController.jump and self.currentTick - self.lastJumpTick > 28:
            if not controller.jump:
                self.maxDodgeTick = self.currentTick + 1.25 * 120
            elif self.lastJumpTick == -math.inf:
                self.maxDodgeTick = math.inf
            else:
                self.maxDodgeTick = self.lastJumpTick + 1.45 * 120

        if not self.car.on_ground and controller.jump and not self.car.double_jumped and self.currentTick <= self.maxDodgeTick:
            self.lastDodgeTick = self.currentTick

        if not self.jumpReleased and not controller.jump:
            self.jumpReleased = True

        self.lastController = controller

    def handleTime(self):
        # this is the most conservative possible approach, but it could lead to having a "backlog" of ticks if seconds_elapsed
        # isnt perfectly accurate.
        if not self.lastTime:
            self.lastTime = self.packet.game_info.seconds_elapsed
        else:
            if self.realLastTime == self.packet.game_info.seconds_elapsed:
                return

            if int(self.lastTime) != int(
                    self.packet.game_info.seconds_elapsed):
                # if self.skippedTicks > 0:
                print(f"did {self.doneTicks}, skipped {self.skippedTicks}")
                if self.firstTpsReport or self.packet.game_ball.physics.location.x == 0 and self.packet.game_ball.physics.location.y == 0:
                    self.firstTpsReport = False
                elif self.doneTicks < 110:
                    self.send_quick_chat(QuickChats.CHAT_EVERYONE,
                                         QuickChats.Custom_Excuses_Lag)
                self.skippedTicks = self.doneTicks = 0

            ticksPassed = round(
                max(1,
                    (self.packet.game_info.seconds_elapsed - self.lastTime) *
                    self.FPS))
            self.lastTime = min(self.packet.game_info.seconds_elapsed,
                                self.lastTime + ticksPassed)
            self.realLastTime = self.packet.game_info.seconds_elapsed
            self.currentTick += ticksPassed
            if ticksPassed > 1:
                # print(f"Skipped {ticksPassed - 1} ticks!")
                self.skippedTicks += ticksPassed - 1
            self.doneTicks += 1
예제 #27
0
class diabloBot(BaseAgent):
    def __init__(self, name, team, index):
        Game.set_mode("soccar")
        self.game = Game(index, team)
        self.index = index
        self.name = name
        self.team = team

    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 = Chase(self)
        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()

    def getActiveState(self):
        if type(self.activeState) == JumpingState:
            return 0
        if type(self.activeState) == Kickoff:
            return 1
        if type(self.activeState) == GetBoost:
            return 2
        if type(self.activeState) == Dribble:
            return 3
        if type(self.activeState) == GroundShot:
            return 4
        if type(self.activeState) == GroundDefend:
            return 5
        if type(self.activeState) == halfFlip:
            return 6

    def setHalfFlip(self):
        self.activeState = halfFlip(self)

    def determineFacing(self):
        offset = self.me.location + self.me.velocity
        #direction = self.me.location + offset
        loc = toLocal(offset, self.me)
        angle = math.degrees(math.atan2(loc[1], loc[0]))
        if angle < -180:
            angle += 360
        if angle > 180:
            angle -= 360

        if abs(angle) > 150 and self.getCurrentSpd() > 200:
            self.forward = False
        else:
            self.forward = True

        self.velAngle = angle
        #print(self.forward, angle)

    def setJumping(self, targetType):
        self.activeState = JumpingState(self, targetType)

    def getCurrentSpd(self):
        return Vector(self.me.velocity[:2]).magnitude()

    def updateSelectedBallPrediction(self, ballStruct):
        x = physicsObject()
        x.location = Vector([
            ballStruct.physics.location.x, ballStruct.physics.location.y,
            ballStruct.physics.location.z
        ])
        x.velocity = Vector([
            ballStruct.physics.velocity.x, ballStruct.physics.velocity.y,
            ballStruct.physics.velocity.z
        ])
        x.rotation = Vector([
            ballStruct.physics.rotation.pitch, ballStruct.physics.rotation.yaw,
            ballStruct.physics.rotation.roll
        ])
        x.avelocity = Vector([
            ballStruct.physics.angular_velocity.x,
            ballStruct.physics.angular_velocity.y,
            ballStruct.physics.angular_velocity.z
        ])
        x.local_location = localizeVector(x.location, self.me)
        self.ballPredObj = x

    def preprocess(self, game):
        self.ballPred = self.get_ball_prediction_struct()
        self.players = [self.index]
        self.game.read_game_information(game, self.get_rigid_body_tick(),
                                        self.get_field_info())
        car = game.game_cars[self.index]
        self.me.location = Vector([
            car.physics.location.x, car.physics.location.y,
            car.physics.location.z
        ])
        self.me.velocity = Vector([
            car.physics.velocity.x, car.physics.velocity.y,
            car.physics.velocity.z
        ])
        self.me.rotation = Vector([
            car.physics.rotation.pitch, car.physics.rotation.yaw,
            car.physics.rotation.roll
        ])
        #self.me.rotation = Rotation_Vector(car.physics.rotation)
        self.me.avelocity = Vector([
            car.physics.angular_velocity.x, car.physics.angular_velocity.y,
            car.physics.angular_velocity.z
        ])
        self.me.boostLevel = car.boost
        self.onSurface = car.has_wheel_contact
        self.positions.insert(0, self.me.location)
        if len(self.positions) > 200:
            self.positions = self.positions[:200]
        # t = time.time()
        # self.deltaTime = t-self.time
        # self.time = t
        self.deltaTime = clamp(1 / 60, 1 / 300, self.game.time_delta)
        # self.deltaList.insert(0,self.deltaTime)
        # if len(self.deltaList) > 200:
        #     self.deltaList = self.deltaList[:200]

        ball = game.game_ball.physics
        self.ball.location = Vector(
            [ball.location.x, ball.location.y, ball.location.z])
        self.ball.velocity = Vector(
            [ball.velocity.x, ball.velocity.y, ball.velocity.z])
        self.ball.rotation = Vector(
            [ball.rotation.pitch, ball.rotation.yaw, ball.rotation.roll])
        self.ball.avelocity = Vector([
            ball.angular_velocity.x, ball.angular_velocity.y,
            ball.angular_velocity.z
        ])
        self.me.matrix = rotator_to_matrix(self.me)
        self.ball.local_location = localizeVector(self.ball.location, self.me)
        self.determineFacing()
        self.onWall = False
        if self.onSurface:
            if self.me.location[2] > 70:
                self.onWall = True

        # collects info for all other cars in match, updates objects in self.players accordingly
        self.allies.clear()
        self.enemies.clear()
        for i in range(game.num_cars):
            if i != self.index:
                car = game.game_cars[i]
                _obj = physicsObject()
                _obj.index = i
                _obj.team = car.team
                _obj.location = Vector([
                    car.physics.location.x, car.physics.location.y,
                    car.physics.location.z
                ])
                _obj.velocity = Vector([
                    car.physics.velocity.x, car.physics.velocity.y,
                    car.physics.velocity.z
                ])
                _obj.rotation = Vector([
                    car.physics.rotation.pitch, car.physics.rotation.yaw,
                    car.physics.rotation.roll
                ])
                _obj.avelocity = Vector([
                    car.physics.angular_velocity.x,
                    car.physics.angular_velocity.y,
                    car.physics.angular_velocity.z
                ])
                _obj.boostLevel = car.boost
                _obj.local_location = localizeVector(_obj, self.me)

                if car.team == self.team:
                    self.allies.append(_obj)
                else:
                    self.enemies.append(_obj)
        self.gameInfo = game.game_info
        #print(self.Game.time_delta)

        #boost info
        self.boosts.clear()
        self.fieldInfo = self.get_field_info()
        for index in range(len(self.fieldInfo.boost_pads)):
            packetBoost = game.game_boosts[index]
            fieldInfoBoost = self.fieldInfo.boost_pads[index]
            self.boosts.append(
                Boost_obj([
                    fieldInfoBoost.location.x, fieldInfoBoost.location.y,
                    fieldInfoBoost.location.z
                ], fieldInfoBoost.is_full_boost, packetBoost.is_active))

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        self.preprocess(packet)
        #testFlight(self)
        #launchStateManager(self)
        if len(self.allies) >= 1:
            teamStateManager(self)
        else:
            soloStateManager(self)
        #soloStateAerialManager(self)
        action = self.activeState.update()

        self.renderer.begin_rendering()
        self.renderer.draw_string_2d(100, 100, 1, 1,
                                     str(type(self.activeState)),
                                     self.renderer.white())

        for each in self.renderCalls:
            each.run()
        self.renderer.end_rendering()
        self.renderCalls.clear()

        return action
예제 #28
0
class Agent(BaseAgent):
    def __init__(self, name, team, index):
        self.game = Game()
        self.controls = SimpleControllerState()
        self.my_car = self.game.cars[0]

        self.timer = 0.0
        self.action = None
        random.seed(0)

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:

        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        self.controls = SimpleControllerState()

        if not self.action:
            self.action = Reorient(self.my_car)
            self.action.eps_phi = 0.01
            self.action.eps_omega = 0.02

        if self.timer == 0.0:

            # randomly generate a proper orthogonal matrix
            self.action.target_orientation = axis_to_rotation(
                vec3(random.uniform(-2, 2), random.uniform(-2, 2),
                     random.uniform(-2, 2)))

        o = self.action.target_orientation
        f = vec3(o[0, 0], o[1, 0], o[2, 0])
        position = Vector3(0, 0, 1000)
        velocity = Vector3(0, 0, 0)

        car_state = CarState(
            physics=Physics(location=position, velocity=velocity))

        # spawn the ball in front of the desired orientation to visually indicate where we're trying to go
        ball_state = BallState(
            physics=Physics(location=Vector3(500 * f[0], 500 *
                                             f[1], 500 * f[2] + 1000),
                            velocity=Vector3(0, 0, 0),
                            angular_velocity=Vector3(0, 0, 0)))

        self.set_game_state(GameState(ball=ball_state, cars={0: car_state}))

        self.action.step(self.game.time_delta)
        self.controls = self.action.controls

        self.timer += self.game.time_delta
        if self.timer > 2.0:
            self.timer = 0.0

        error = angle_between(self.my_car.orientation,
                              self.action.target_orientation)

        self.renderer.begin_rendering("path")
        red = self.renderer.create_color(255, 230, 30, 30)
        self.renderer.draw_string_2d(50, 50, 3, 3,
                                     f"error: {error:.4f} radians", red)
        self.renderer.draw_string_2d(50, 100, 3, 3,
                                     f"Roll:   {self.controls.roll:+.2f}", red)
        self.renderer.draw_string_2d(50, 150, 3, 3,
                                     f"Pitch: {self.controls.pitch:+.2f}", red)
        self.renderer.draw_string_2d(50, 200, 3, 3,
                                     f"Yaw:  {self.controls.yaw:+.2f}", red)
        self.renderer.end_rendering()

        return self.controls
예제 #29
0
class HeartOfGold(BaseAgent):
    def __init__(self, name, team, index):
        super().__init__(name, team, index)
        self.active_sequence: Sequence = None
        self.ball_predictions = []
        self.not_hit_yet = True
        self.game = None
        self.aerial = None
        self.timer = 0.0
        self.action = None

        self.intercept = None
        self.target = None

        self.dodge = None
        self.dodge_started = False
        # self.dodge_error = None
        self.best_dodge = None
        self.best_dodge_sims = 0
        self.best_dodge_start_dist = 0

        self.time_estimate = None
        self.speed_estimate = None

    def initialize_agent(self):
        print('> Alphabot: I N I T I A L I Z E D')

    def reset_for_aerial(self):
        self.initial_ball_location = Vector3(0, 2000, 100)
        self.initial_ball_velocity = Vector3(randint(-250, 250),
                                             randint(-250, 250), 650 * 2)
        self.initial_car_location = Vector3(randint(-2000, 2000), 0, 0)
        self.initial_car_velocity = Vector3(0, 0, 0)
        self.not_hit_yet = True
        self.ball_predictions = []
        self.last_dist = None
        self.last_touch_location = Vec3(0, 0, 0)

    def reset_for_ground_shots(self):
        self.initial_ball_location = Vector3(0, 2000, 100)
        # self.initial_ball_velocity = Vector3(randint(-800, 800), randint(-800, 800), 0)
        self.initial_ball_velocity = Vector3(randint(-800, 800),
                                             randint(-800, 800), 0)
        self.initial_car_location = Vector3(randint(-800, 800), 0, 0)
        self.initial_car_velocity = Vector3(0, 0, 0)
        self.not_hit_yet = True
        self.ball_predictions = []
        self.last_dist = None
        self.last_touch_location = Vec3(0, 0, 0)

    def reset_gamestate(self):
        print('> reset_gamestate()')

        # Initialize inputs
        self.reset_for_ground_shots()
        t = self.target
        b = Ball(self.game.ball)
        c = Car(self.game.cars[self.index])
        b.location = to_vec3(self.initial_ball_location)
        b.velocity = to_vec3(self.initial_ball_velocity)
        c.location = to_vec3(self.initial_car_location)
        c.velocity = to_vec3(self.initial_car_velocity)

        # Point car at ball
        c.rotation = look_at(
            vec3(b.location[0] - c.location[0], b.location[1] - c.location[1],
                 0), vec3(0, 0, 1))
        rotator = rotation_to_euler(c.rotation)

        # Reset
        self.aerial = None
        self.dodge = None
        self.rotation_input = None
        self.timer = 0.0

        # Set gamestate
        car_state = CarState(boost_amount=100,
                             physics=Physics(
                                 location=self.initial_car_location,
                                 velocity=self.initial_car_velocity,
                                 rotation=rotator,
                                 angular_velocity=Vector3(0, 0, 0)))
        ball_state = BallState(
            Physics(location=self.initial_ball_location,
                    velocity=self.initial_ball_velocity,
                    rotation=Rotator(0, 0, 0),
                    angular_velocity=Vector3(0, 0, 0)))
        game_state = GameState(ball=ball_state, cars={self.index: car_state})
        self.set_game_state(game_state)

    def plan(self):
        self.intercept = Intercept.calculate(self.game.my_car, self.game.ball,
                                             self.target)

        # Clean up old dodge
        # if self.dodge is not None:
        #     if self.dodge.finished: self.dodge = None
        #     else: return

        # Calculate new intercept
        # not_ahead_of_ball = norm(self.game.my_car.location - self.target) > norm(self.game.ball.location - self.target)
        # on_ground = self.game.my_car.location[2] < 18
        # if on_ground and not_ahead_of_ball:
        #     self.intercept = Intercept.calculate(self.game.my_car, self.game.ball, self.target)
        #     if self.intercept is not None: return

        # # Otherwise, try to get in position
        # waypoint = vec3(self.game.ball.location)
        # waypoint[1] -= 2500
        # waypoint[2] = 0
        # self.intercept = Intercept(waypoint)
        # self.intercept.boost = False
        # self.intercept.purpose = 'position'

    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        # Record start time
        self.tick_start = time.time()

        # Gather some information about our car and the ball
        my_car: CarState = packet.game_cars[self.index]
        car_location = Vec3(my_car.physics.location)
        car_velocity = Vec3(my_car.physics.velocity)
        car_direction = car_velocity.ang_to(Vec3(
            1, 0, 0)) if car_velocity.length() > 0 else 0
        ball_location = Vec3(packet.game_ball.physics.location)
        ball_velocity = Vec3(packet.game_ball.physics.velocity)
        ball_direction = ball_velocity.ang_to(Vec3(
            1, 0, 0)) if ball_velocity.length() > 0 else 0
        reset = False

        # Initialize simulation game model
        if self.game == None:
            Game.set_mode('soccar')
            self.game = Game(self.index, self.team)
            self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                            self.get_field_info())
            self.target = vec3(
                0, 5120 + 880 / 2 if self.team is 0 else -(5120 + 880 / 2),
                642.775 / 2)  # Opposing net
            self.reset_gamestate()
            print('TEAM', self.team)
            return SimpleControllerState()

        # Update simulation
        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        # Check for car hit ball
        if self.last_touch_location != packet.game_ball.latest_touch.hit_location:
            self.last_touch_location = Vec3(
                packet.game_ball.latest_touch.hit_location)
            print(f'> Car hit ball')
            self.not_hit_yet = False

        # Recalculate intercept every frame
        self.plan()

        # Re-simulate the aerial every frame
        if self.aerial is not None and not self.aerial.finished:
            simulate_aerial(self)
            simulate_alternate_aerials(self)

        # Update dodge (init or clean up old)
        # try_init_dodge(self)

        # Rendering
        if len(self.ball_predictions) > 2:
            self.renderer.draw_polyline_3d(self.ball_predictions,
                                           self.renderer.red())
        if self.aerial != None and self.aerial.target:
            self.renderer.draw_rect_3d(self.aerial.target,
                                       8,
                                       8,
                                       True,
                                       self.renderer.green(),
                                       centered=True)
            self.renderer.draw_line_3d(car_location, self.aerial.target,
                                       self.renderer.white())
            self.renderer.draw_line_3d(vec3_to_Vec3(self.target),
                                       self.target + self.avg_aerial_error,
                                       self.renderer.cyan())
        if self.intercept != None:
            self.renderer.draw_rect_3d(self.intercept.location,
                                       8,
                                       8,
                                       True,
                                       self.renderer.green(),
                                       centered=True)
        self.renderer.draw_rect_3d(vec3_to_Vec3(self.target),
                                   8,
                                   8,
                                   True,
                                   self.renderer.green(),
                                   centered=True)

        # Controller state
        if reset:
            self.reset_gamestate()
            return SimpleControllerState()
        # "Do a flip!"
        elif self.dodge is not None:
            if self.dodge.finished:
                self.dodge = None
                return SimpleControllerState()
            self.dodge.step(self.game.time_delta)
            return self.dodge.controls
        # Just do an aerial :4head:
        elif self.aerial is not None:
            aerial_step(self.aerial, Car(self.game.my_car),
                        self.rotation_input, self.game.time_delta)
            return self.aerial.controls
        # Just hit the ball :4head:
        elif self.intercept is not None:
            if self.intercept.dodge and abs(self.game.time - self.intercept.
                                            jump_time) <= self.game.time_delta:
                print('im gonna nut')
                self.dodge = Dodge(self.game.my_car)
                self.dodge.duration = 0.2
                self.dodge.preorientation = self.intercept.dodge_preorientation
                self.dodge.delay = self.intercept.dodge_delay + 0.1
                self.dodge.direction = self.intercept.dodge_direction
                self.dodge.step(self.game.time_delta)
                return self.dodge.controls
            return self.intercept.get_controls(
                my_car, self.game.my_car
            )  #drive_at(self, my_car, self.intercept.location)

        return SimpleControllerState()
예제 #30
0
    def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
        # Record start time
        self.tick_start = time.time()

        # Gather some information about our car and the ball
        my_car: CarState = packet.game_cars[self.index]
        car_location = Vec3(my_car.physics.location)
        car_velocity = Vec3(my_car.physics.velocity)
        car_direction = car_velocity.ang_to(Vec3(
            1, 0, 0)) if car_velocity.length() > 0 else 0
        ball_location = Vec3(packet.game_ball.physics.location)
        ball_velocity = Vec3(packet.game_ball.physics.velocity)
        ball_direction = ball_velocity.ang_to(Vec3(
            1, 0, 0)) if ball_velocity.length() > 0 else 0
        reset = False

        # Initialize simulation game model
        if self.game == None:
            Game.set_mode('soccar')
            self.game = Game(self.index, self.team)
            self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                            self.get_field_info())
            self.target = vec3(
                0, 5120 + 880 / 2 if self.team is 0 else -(5120 + 880 / 2),
                642.775 / 2)  # Opposing net
            self.reset_gamestate()
            print('TEAM', self.team)
            return SimpleControllerState()

        # Update simulation
        self.game.read_game_information(packet, self.get_rigid_body_tick(),
                                        self.get_field_info())

        # Check for car hit ball
        if self.last_touch_location != packet.game_ball.latest_touch.hit_location:
            self.last_touch_location = Vec3(
                packet.game_ball.latest_touch.hit_location)
            print(f'> Car hit ball')
            self.not_hit_yet = False

        # Recalculate intercept every frame
        self.plan()

        # Re-simulate the aerial every frame
        if self.aerial is not None and not self.aerial.finished:
            simulate_aerial(self)
            simulate_alternate_aerials(self)

        # Update dodge (init or clean up old)
        # try_init_dodge(self)

        # Rendering
        if len(self.ball_predictions) > 2:
            self.renderer.draw_polyline_3d(self.ball_predictions,
                                           self.renderer.red())
        if self.aerial != None and self.aerial.target:
            self.renderer.draw_rect_3d(self.aerial.target,
                                       8,
                                       8,
                                       True,
                                       self.renderer.green(),
                                       centered=True)
            self.renderer.draw_line_3d(car_location, self.aerial.target,
                                       self.renderer.white())
            self.renderer.draw_line_3d(vec3_to_Vec3(self.target),
                                       self.target + self.avg_aerial_error,
                                       self.renderer.cyan())
        if self.intercept != None:
            self.renderer.draw_rect_3d(self.intercept.location,
                                       8,
                                       8,
                                       True,
                                       self.renderer.green(),
                                       centered=True)
        self.renderer.draw_rect_3d(vec3_to_Vec3(self.target),
                                   8,
                                   8,
                                   True,
                                   self.renderer.green(),
                                   centered=True)

        # Controller state
        if reset:
            self.reset_gamestate()
            return SimpleControllerState()
        # "Do a flip!"
        elif self.dodge is not None:
            if self.dodge.finished:
                self.dodge = None
                return SimpleControllerState()
            self.dodge.step(self.game.time_delta)
            return self.dodge.controls
        # Just do an aerial :4head:
        elif self.aerial is not None:
            aerial_step(self.aerial, Car(self.game.my_car),
                        self.rotation_input, self.game.time_delta)
            return self.aerial.controls
        # Just hit the ball :4head:
        elif self.intercept is not None:
            if self.intercept.dodge and abs(self.game.time - self.intercept.
                                            jump_time) <= self.game.time_delta:
                print('im gonna nut')
                self.dodge = Dodge(self.game.my_car)
                self.dodge.duration = 0.2
                self.dodge.preorientation = self.intercept.dodge_preorientation
                self.dodge.delay = self.intercept.dodge_delay + 0.1
                self.dodge.direction = self.intercept.dodge_direction
                self.dodge.step(self.game.time_delta)
                return self.dodge.controls
            return self.intercept.get_controls(
                my_car, self.game.my_car
            )  #drive_at(self, my_car, self.intercept.location)

        return SimpleControllerState()