Esempio n. 1
0
    def get_free_forward_team_mates(self,
                                    team,
                                    side,
                                    my_coord: Coordinate,
                                    max_data_age,
                                    min_distance_free,
                                    min_dist_from_me=3):
        free_team_mates: [ObservedPlayer
                          ] = self.get_free_team_mates(team, max_data_age,
                                                       min_distance_free)
        debug_msg("Free_team_mates={0}".format(free_team_mates), "OFFSIDE")
        if side == "l":
            free_forward_team_mates = list(
                filter(
                    lambda p: p.coord.pos_x > my_coord.pos_x and p.coord.
                    euclidean_distance_from(my_coord) > min_dist_from_me,
                    free_team_mates))
        else:
            free_forward_team_mates = list(
                filter(
                    lambda p: p.coord.pos_x < my_coord.pos_x and p.coord.
                    euclidean_distance_from(my_coord) > min_dist_from_me,
                    free_team_mates))

        return free_forward_team_mates
Esempio n. 2
0
    def get_free_team_mates(self,
                            team,
                            max_data_age,
                            min_distance=2) -> [ObservedPlayer]:
        team_mates: [ObservedPlayer
                     ] = self.get_teammates(team, max_data_age=max_data_age)
        opponents: [ObservedPlayer
                    ] = self.get_opponents(team, max_data_age=max_data_age)

        debug_msg(
            "Team_mates={0} | opponents={1} | other_players:{2}".format(
                team_mates, opponents, self.other_players), "OFFSIDE")

        free_team_mates = []

        if len(opponents) < 1:
            return team_mates

        for team_mate in team_mates:
            for opponent in opponents:
                tm: ObservedPlayer = team_mate
                op: ObservedPlayer = opponent
                if tm.coord.euclidean_distance_from(
                        op.coord) > min_distance and tm not in free_team_mates:
                    free_team_mates.append(tm)

        return free_team_mates
Esempio n. 3
0
def _optimal_midfielder_pos(state) -> Coordinate:
    side = 1 if state.world_view.side == 'l' else -1
    if not state.world_view.ball.is_value_known():
        return state.get_global_play_pos()
    ball: Coordinate = state.world_view.ball.get_value().coord
    play_position = state.get_global_play_pos()
    ball_delta_y = ball.pos_y - play_position.pos_y
    ball_delta_x = ball.pos_x - play_position.pos_x

    # Position player according to their starting position and the current ball position
    if side * ball.pos_x > 0:
        # Attacking
        optimal_x = clamp(
            play_position.pos_x + ball_delta_x * 0.4 + ball.pos_x * 0.6, -45,
            45)
    else:
        # Defending
        optimal_x = clamp(play_position.pos_x + ball.pos_x * 0.4, -45, 45)

    # Used to make players position themselves closer to the goal on the y-axis when far up/down the field
    y_goal_factor = 1 - (abs(optimal_x) -
                         35) * 0.05 if abs(optimal_x) > 35 else 1.0
    optimal_y = clamp(
        play_position.pos_y + ball_delta_y * 0.2 + ball.pos_y * 0.2, -25,
        25) * y_goal_factor

    if state.world_view.team_has_ball(state.team_name, max_data_age=4):
        opt_coord = Coordinate(optimal_x + (10 * side), optimal_y)
        free_pos = state.get_closest_free_position(opt_coord)
        if state.is_test_player():
            debug_msg("Free position:{0}".format(free_pos), "FREE_POSITION")
        return opt_coord if free_pos is None else free_pos

    return Coordinate(optimal_x, optimal_y)
Esempio n. 4
0
    def is_ball_inside_own_box(self) -> bool:
        pos: Coordinate = self.world_view.ball.get_value().coord

        result = True
        if self.world_view.side == "l":
            if pos.pos_x > -36 or (pos.pos_y < -20 or pos.pos_y > 20):
                result = False
        else:
            if pos.pos_x < 36 or (pos.pos_y < -20 or pos.pos_y > 20):
                result = False

        if self.is_test_player():
            debug_msg("is_inside_own_box={0}, Pos={1}".format(result, pos),
                      "GOALIE")

        return result
Esempio n. 5
0
def _optimal_striker_pos(state: PlayerState) -> Coordinate:
    side = 1 if state.world_view.side == 'l' else -1
    if not state.world_view.ball.is_value_known():
        return state.get_global_play_pos()
    ball: Coordinate = state.world_view.ball.get_value().coord
    play_position = state.get_global_play_pos()
    ball_delta_y = ball.pos_y - play_position.pos_y

    if side * ball.pos_x > 0:
        # Attacking
        x_offset = ball.pos_x + side * 5
        optimal_x = clamp(play_position.pos_x + x_offset, -45, 45)

        # Used to make players position themselves closer to the goal on the y-axis when far up/down the field
        y_goal_factor = 0.982888 + 0.002871167 * abs(
            optimal_x) - 0.0000807057 * pow(optimal_x, 2)

        optimal_y = clamp(
            play_position.pos_y + ball.pos_y * 0.2 + ball_delta_y * 0.4, -30,
            30) * y_goal_factor

        if state.world_view.team_has_ball(state.team_name, max_data_age=4):
            opt_coord = Coordinate(optimal_x + (10 * side), optimal_y)
            free_pos = state.get_closest_free_position(opt_coord)
            if state.is_test_player():
                debug_msg("Free position:{0}".format(free_pos),
                          "FREE_POSITION")
            return opt_coord if free_pos is None else free_pos

        return Coordinate(optimal_x, optimal_y)
    else:
        # Defending
        optimal_x = -state.get_global_play_pos().pos_x + ball.pos_x * 0.4
        optimal_y = state.get_global_play_pos().pos_y + ball_delta_y * 0.2

        if state.world_view.team_has_ball(state.team_name, max_data_age=4):
            opt_coord = Coordinate(optimal_x + (10 * side), optimal_y)
            free_pos = state.get_closest_free_position(opt_coord)
            if state.is_test_player():
                debug_msg("Free position:{0}".format(free_pos),
                          "FREE_POSITION")
            return opt_coord if free_pos is None else free_pos

        return Coordinate(optimal_x, optimal_y)
Esempio n. 6
0
    def get_non_offside_forward_team_mates(self,
                                           team,
                                           side,
                                           my_coord: Coordinate,
                                           max_data_age,
                                           min_distance_free,
                                           min_dist_from_me=1):
        free_forward_team_mates: [ObservedPlayer
                                  ] = self.get_free_forward_team_mates(
                                      team, side, my_coord, max_data_age,
                                      min_distance_free, min_dist_from_me)
        opponents: [ObservedPlayer] = self.get_opponents(team, max_data_age)

        # If no opponents are seen, no one is offside
        if len(opponents) < 1:
            debug_msg(
                "free_forward_team_mates={0}".format(free_forward_team_mates),
                "OFFSIDE")
            return free_forward_team_mates

        reverse = True if side == "l" else False
        furthest_behind_opponent: ObservedPlayer = \
            list(sorted(opponents, key=lambda p: p.coord.pos_x, reverse=reverse))[0]
        furthest_opp_x_pos = furthest_behind_opponent.coord.pos_x
        if side == "l":
            non_offside_players = list(
                filter(
                    lambda p: (p.coord.pos_x < furthest_opp_x_pos and p.coord.
                               euclidean_distance_from(my_coord) >
                               min_dist_from_me) or p.coord.pos_x < 0,
                    free_forward_team_mates))
        else:
            non_offside_players = list(
                filter(
                    lambda p: (p.coord.pos_x > furthest_opp_x_pos and p.coord.
                               euclidean_distance_from(my_coord) >
                               min_dist_from_me) or p.coord.pos_x > 0,
                    free_forward_team_mates))
        debug_msg(
            "Further_opp_x_pos={0} | free_forward_team_mates={1} | furthest_behind_opponent={2} | non_offisde_players={3}"
            .format(furthest_opp_x_pos, free_forward_team_mates,
                    furthest_behind_opponent, non_offside_players), "OFFSIDE")
        return non_offside_players
Esempio n. 7
0
    def team_has_ball(self, team, max_data_age, min_possession_distance=3):
        if not self.ball.is_value_known():
            debug_msg("{0} has ball".format("Team2"), "HAS_BALL")
            return False

        all_players: [ObservedPlayer
                      ] = self.get_all_known_players(team, max_data_age)

        # Sort players by distance to ball
        sorted_list: [ObservedPlayer] = list(
            sorted(all_players,
                   key=lambda p: p.coord.euclidean_distance_from(
                       self.ball.get_value().coord),
                   reverse=False))

        if len(sorted_list) < 1:
            return False

        # If closest player to ball team is known and is our team, return True
        closest_player: ObservedPlayer = sorted_list[0]
        if closest_player.team is not None and closest_player.team == team and closest_player.coord.euclidean_distance_from(
                self.ball.get_value().coord) < min_possession_distance:
            debug_msg(
                "{0} has ball | player: {1}".format(team, closest_player),
                "HAS_BALL")
            return True

        debug_msg("{0} has ball".format("Team2"), "HAS_BALL")
        return False
Esempio n. 8
0
 def needs_dribble_or_pass_strat(self):
     if not (self.mode is DRIBBLING_MODE
             or self.ball_incoming()) or self.intercepting or self.now(
             ) - self.last_dribble_pass_strat <= 4:
         if self.is_test_player():
             debug_msg(
                 str(self.now()) +
                 " Not dribbling or recently generated strat",
                 "DRIBBLE_PASS_MODEL")
         return False
     enough_opponents = len(
         self.world_view.get_opponents(self.team_name, 10)) > 0
     enough_teammates = len(
         self.world_view.get_teammates(self.team_name, 10, 5)) > 0
     if not enough_opponents:
         if self.is_test_player():
             debug_msg(
                 str(self.now()) + " Not enough opponents: " +
                 str(self.world_view.other_players), "DRIBBLE_PASS_MODEL")
         return False
     if not enough_teammates:
         if self.is_test_player():
             debug_msg(
                 str(self.now()) + " Not enough teammates: " +
                 str(self.world_view.other_players), "DRIBBLE_PASS_MODEL")
         return False
     return True
Esempio n. 9
0
    def ball_incoming(self):
        if not self.world_view.ball.is_value_known(
                self.action_history.three_see_updates_ago):
            return False

        ball: Ball = self.world_view.ball.get_value()
        dist = ball.distance
        if dist >= 15:
            return False
        if ball.absolute_velocity is not None:
            ball_move_dir = ball.absolute_velocity.world_direction()
            ball_relative_dir = math.degrees(
                calculate_full_origin_angle_radians(ball.coord,
                                                    self.position.get_value()))
            dif = abs(
                smallest_angle_difference((ball_move_dir + 180) % 360,
                                          ball_relative_dir))

            if self.is_test_player():
                debug_msg(
                    str(self.now()) + " Ball movement dir: " +
                    str(ball_move_dir) + " Direction from player: " +
                    str(ball_relative_dir) + " Heading this way : " +
                    str(dif <= 15), "DRIBBLE_PASS_MODEL")
            return dif <= 15

        position, projected_direction, speed = ball.approximate_position_direction_speed(
            2)
        if projected_direction is None or speed < 0.25:
            return False

        ball_angle = math.degrees(
            calculate_full_origin_angle_radians(self.position.get_value(),
                                                ball.coord))
        if abs(ball_angle - projected_direction) < 15 and dist < 40:
            return True

        return False
Esempio n. 10
0
def determine_objective_biptest(state: PlayerState):
    # If lost orientation -> blind orient
    if _lost_orientation(state):
        return Objective(state, lambda: actions.blind_orient(state),
                         lambda: True, 1)

    # If ball unknown -> locate ball
    if _ball_unknown(state):
        return Objective(state, lambda: actions.locate_ball(state),
                         lambda: True, 1)

    if state.position.is_value_known():
        side: int = 1 if state.world_view.side == "l" else -1
        lower_goal: Coordinate = Coordinate(-25 * side, -33)
        upper_goal: Coordinate = Coordinate(-25 * side, 33)
        if not state.is_near(upper_goal, 2):
            debug_msg("Going to left goal", "BIPTEST")
            return Objective(state, lambda: actions.rush_to(state, upper_goal),
                             lambda: state.is_near(upper_goal, 0.5), 1000)
        else:
            debug_msg("Going to right goal", "BIPTEST")
            return Objective(state, lambda: actions.rush_to(state, lower_goal),
                             lambda: state.is_near(lower_goal, 0.5), 1000)
Esempio n. 11
0
    def get_closest_free_position(self,
                                  opt_coord: Coordinate,
                                  max_delta_from_org_coord=5,
                                  min_delta_from_opp=7):
        init_x: int = int(opt_coord.pos_x)
        init_y: int = int(opt_coord.pos_y)

        free_cords: [Coordinate] = []

        for x in range(init_x, init_x + max_delta_from_org_coord):
            for y in range(init_y, init_y + max_delta_from_org_coord):
                c: Coordinate = Coordinate(x, y)
                if self.is_coord_free(c, min_delta_from_opp):
                    free_cords.append(c)

        debug_msg(
            "Opt_coord={0}, free_coords={1}".format(opt_coord, free_cords),
            "FREE_POSITION")
        if len(free_cords) > 0:
            return sorted(free_cords,
                          key=lambda c: c.euclidean_distance_from(opt_coord),
                          reverse=False)[0]

        return None
Esempio n. 12
0
    def perform_action(self):
        if self.player_state.current_objective.should_recalculate(
                self.player_state):
            self.player_state.current_objective = determine_objective(
                self.player_state)

        if self.player_state.is_test_player():  # Debugging
            debug_msg(
                str(self.player_state.now()) + " Mode : " +
                str(self.player_state.mode), "MODE")

        commands = self.player_state.current_objective.get_next_commands(
            self.player_state)

        if self.player_state.is_test_player():  # Debugging
            debug_msg(
                str(self.player_state.now()) + " Sending commands : " +
                str(commands), "SENT_COMMANDS")
            debug_msg(
                str(self.player_state.now()) +
                "Position : {0} | Speed : {1} | BodyDir : {2} | NeckDir : {3} | "
                "TurnInProgress : {4}".format(
                    self.player_state.position.get_value(),
                    self.player_state.body_state.speed,
                    self.player_state.body_angle.get_value(),
                    self.player_state.body_state.neck_angle,
                    self.player_state.action_history.turn_in_progress),
                "STATUS")

        if self.player_state.is_test_player():  # Debugging
            debug_msg(
                "{0} Commands: {1}".format(
                    self.player_state.world_view.sim_time, commands),
                "MESSAGES")

        for command in commands:
            if command is not None:
                self.player_conn.action_queue.put(command)
Esempio n. 13
0
def _extract_actions(strategy: UppaalStrategy, team_members):
    actions = []
    debug_msg("-" * 50, "PASS_CHAIN")
    for r in strategy.regressors:
        if "Passing" in str(
                strategy.index_to_transition[r.get_highest_val_trans()[0]]):
            from_player = _get_ball_possessor(r, strategy.location_to_id,
                                              team_members)
            to_player = _get_pass_target(r, strategy.index_to_transition,
                                         team_members)
            to_player: PlayerViewCoach
            actions.append("(" + str(from_player.num) + " pass " +
                           to_player.coord.marshal() + ")")
            debug_msg(
                str(from_player.num) + " passes to " + str(to_player.num),
                "PASS_CHAIN")
        else:
            from_player = _get_ball_possessor(r, strategy.location_to_id,
                                              team_members)
            actions.append("(" + str(from_player.num) + " dribble" + ")")
            debug_msg(str(from_player.num) + " dribbles ", "PASS_CHAIN")
    debug_msg("-" * 50, "PASS_CHAIN")
    return actions
Esempio n. 14
0
    def ball_interception(self):
        wv = self.world_view
        ball = wv.ball.get_value()
        ball_known = wv.ball.is_value_known(self.now() - 4)
        if (
                not ball_known
        ) or ball.absolute_velocity is None or ball.absolute_velocity.magnitude(
        ) < 0.2:
            return None, None

        if wv.ball.is_value_known(self.now() - 4):
            ball: Ball = wv.ball.get_value()

            tick_offset = self.now() - wv.ball.last_updated_time
            project_positions = ball.project_ball_position(10, tick_offset)
            if project_positions is None:
                return None, None

            all_ticks = range(1, 11)
            positions_and_ticks = list(zip(project_positions, all_ticks))
            printable_list = [(pt[0], pt[1]) for pt in positions_and_ticks]
            # positions_and_ticks = sorted(positions_and_ticks, key=lambda pos_and_t: pos_and_t[0].euclidean_distance_from(self.position.get_value()))
            for (position, tick) in positions_and_ticks:
                if self.can_player_reach(position, tick):
                    debug_msg(
                        str(self.now()) + " | Found reachable position: " +
                        str(ball.absolute_velocity), "INTERCEPTION")
                    return position, tick

            if self.is_test_player():
                debug_msg(
                    str(self.now()) + " | Based on ball velocity : " +
                    str(ball.absolute_velocity), "INTERCEPTION")
                debug_msg(
                    str(self.now()) + " | Predictions : " +
                    str(printable_list), "INTERCEPTION")

        return None, None
def map_reduce(file_path=None):
  from parser import parse
  from lexer import lexer
  from utils import function, debug_msg, insert_in_tbl
  #build hash table from file or scanning the complete source file
  #check for input args
  #global the_tbl
  the_tbl = global_tbl()
  if not file_path:
    file_path = "."
    print "No file_path specified for parsing the source code starting from current directory"
  if os.path.isfile(file_path) and file_path.endswith(".tbl"):
    #read file to create the_tbl
    f = open(file_path)
    entry = None
    func = None
    for line in f:
      if line.startswith("&#?filename:"):
        #acquire the global_etntry_tbl lock and add this entry
        #for this file
        if entry:
          the_tbl.lock.qcquire()
          the_tbl.tbl[entry.get_file_name()] = entry
          the_tbl.lock.release()
        
        filename_start = line.find(':')
        file_name = line[filename_start+1:]
        print "File name is: ", file_name
        entry = global_tbl_entry()
        entry.set_file_name(file_name)
      elif line.startswith("\t&#?func_name:"):
        #	&#?func_name:func&#?func_args:int a&#?macro_name:MSG&#?message:I am Nandan&#?msg_args:
        func = function()
        function_name_start = line.find(':')
        function_name_end = line.index("&#?func_args:")
        func_name = line[function_name_start+1:function_name_end]
        print "Func name: ", func_name
        function_args_start = function_name_end + 13
        func_args_end = line.index("&#?macro_name:")
        func_args = line[function_args_start+1:func_args_end]
        func.set_name(func_name)
        func.set_args(func_args)
        print "Func args: ", func_args
        #message
        dbg_msg = debug_msg()
        dbg_macro_start = line.find("&#?macro_name:") + 14
        dbg_msg_macro_end = line.index("&#?message:")
        macro_name = line[dbg_macro_start:dbg_msg_macro_end]
        print "Macro name: ", macro_name
        dbg_msg.set_macro_name(macro_name)
        dbg_msg_start = dbg_msg_macro_end + 11
        dbg_msg_end = line.index("&#?msg_args:")
        msg = line[dbg_msg_start:dbg_msg_end]
        print "message: ", msg
        dbg_msg.set_message(msg)
        dbg_msg_args_start = dbg_msg_end + 12
        args = line[dbg_msg_args_start:]
        dbg_msg.set_args(args)
        print "msg args: ", args
        insert_in_tbl(entry,dbg_msg, func)
    #insert the last entry
    if entry:
      the_tbl.lock.acquire()
      the_tbl.tbl[entry.get_file_name()] = entry
      the_tbl.lock.release()

    return the_tbl.tbl
  #else scan/parse directory to make the_tbl

  print file_path
  #create table write table
  the_tbl = make_tbl(file_path)
  save_tbl_in_file(the_tbl.tbl)
  return the_tbl
Esempio n. 16
0
def determine_objective_field_default(state: PlayerState):
    state.intercepting = False
    # If lost orientation -> blind orient
    if _lost_orientation(state):
        return Objective(state, lambda: actions.blind_orient(state),
                         lambda: True, 1)

    opponent_side = "r" if state.world_view.side == "l" else "l"
    # If game not started or other team starting -> Idle orientation
    if state.world_view.game_state == 'before_kick_off' or state.world_view.game_state == "kick_off_{0}".format(
            opponent_side) or "goal" in state.world_view.game_state:
        return Objective(state, lambda: actions.idle_orientation(state),
                         lambda: True, 1)

    # If some fault has been made by our team -> position optimally
    if "fault_{0}".format(
            state.world_view.side) in state.world_view.game_state:
        return _position_optimally_objective(state)

    # If we have a free kick, corner_kick, kick_in or kick_off
    #   If closest -> Go to ball and pass, else position optimally
    if state.world_view.game_state == "free_kick_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "corner_kick_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "kick_in_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "kick_off_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "offside_{0}".format(opponent_side):
        if _ball_unknown(state):
            return _locate_ball_objective(state)
        if state.is_near_ball(KICKABLE_MARGIN):
            if state.world_view.sim_time - state.action_history.last_look_for_pass_targets > 2:
                return Objective(state,
                                 lambda: actions.look_for_pass_target(state),
                                 lambda: True, 2)
            if _choose_pass_target(state, must_pass=True) is not None:
                return Objective(
                    state, lambda: actions.pass_to_player(
                        state, _choose_pass_target(state, must_pass=True)),
                    lambda: True, 1)
            else:
                return Objective(state,
                                 lambda: actions.look_for_pass_target(state),
                                 lambda: True, 2)
        elif state.is_nearest_ball(1):
            return _jog_to_ball_objective(state)
        else:
            return _position_optimally_objective(state)

    # If in dribbling mode -> Dribble
    if state.mode is DRIBBLING_MODE:
        return _dribble_objective(state)

    # If in possession mode -> Pass
    if state.mode is POSSESSION_MODE:
        return _pass_objective(state)

    # If position known, but ball not -> Locate ball
    if _ball_unknown(state):
        return _locate_ball_objective(state)

    # If in possession of ball -> dribble!
    if state.is_near_ball() and state.is_nearest_ball(1):
        state.mode = DRIBBLING_MODE
        return _dribble_objective(state)

    required_degree = calculate_required_degree(state)
    if state.is_nearest_ball(required_degree):
        intercept_actions = actions.intercept_2(state)
        state.intercepting = True
        if intercept_actions is not None:
            return Objective(state, lambda: intercept_actions)
        else:
            return _rush_to_ball_objective(state)

    # If ball not incoming -> Position optimally while looking at ball
    if not state.ball_incoming() and not configurations.USING_PASS_CHAIN_STRAT:
        if state.is_test_player():
            debug_msg(str(state.now()) + " Position optimally!", "ACTIONS")
        return _position_optimally_objective(state)

    if state.is_test_player():
        debug_msg(str(state.now()) + " Idle orientation!", "ACTIONS")

    return Objective(state, lambda: actions.idle_orientation(state),
                     lambda: True, 1)
Esempio n. 17
0
def determine_objective_goalie_default(state: PlayerState):
    opponent_side = "r" if state.world_view.side == "l" else "l"
    # If goalie and goal_kick -> Go to ball and pass
    if state.world_view.game_state == "goal_kick_{0}".format(
            state.world_view.side) and state.num == 1:
        debug_msg(
            str(state.now()) + " | goal kick -> got to ball and pass",
            "GOALIE")
        if state.is_near_ball(KICKABLE_MARGIN):
            return _pass_objective(state, must_pass=True)
        else:
            return _jog_to_ball_objective(state)

    # If game not started or other team starting -> Idle orientation
    if state.world_view.game_state == 'before_kick_off' or state.world_view.game_state == "kick_off_{0}".format(
            opponent_side) or ("goal_r" == state.world_view.game_state
                               or "goal_l" == state.world_view.game_state):
        debug_msg(
            str(state.now()) +
            " | If game not started or other team starting -> Idle orientation",
            "GOALIE")
        return Objective(state, lambda: actions.idle_orientation(state),
                         lambda: True, 1)

    # If lost_orientation -> blind orient
    if _lost_orientation(state):
        debug_msg(
            str(state.now()) + " | lost orientation -> blind orient", "GOALIE")
        return Objective(state, lambda: actions.blind_orient(state),
                         lambda: True, 1)

    # If ball unknown -> locate ball
    if _ball_unknown(state):
        debug_msg(
            str(state.now()) + " | ball unknown -> locate ball", "GOALIE")
        return Objective(state, lambda: actions.locate_ball(state),
                         lambda: True, 1)

    # If some fault has been made by our team -> Position optimally
    if "fault_{0}".format(
            state.world_view.side) in state.world_view.game_state:
        debug_msg(
            str(state.now()) + " | Team made fault -> position optimally",
            "GOALIE")
        return _position_optimally_objective_goalie(state)

    # If we have a free kick, corner_kick, kick_in, kick_off or goal_kick
    # If closest -> Go to ball and pass, else position optimally
    if state.world_view.game_state == "free_kick_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "corner_kick_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "kick_in_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "goal_kick_{0}".format(state.world_view.side) \
            or state.world_view.game_state == "offside_{0}".format(opponent_side):
        debug_msg(
            str(state.now()) +
            " | free_kick, corner_kick, kick_in, kick_off, goal_kick, offside -> go to ball or position optimally",
            "GOALIE")
        if _ball_unknown(state):
            return _locate_ball_objective(state)
        if state.is_near_ball(KICKABLE_MARGIN):
            if state.world_view.sim_time - state.action_history.last_look_for_pass_targets > 2:
                return Objective(state,
                                 lambda: actions.look_for_pass_target(state),
                                 lambda: True, 2)
            if _choose_pass_target(state, must_pass=True) is not None:
                return Objective(
                    state, lambda: actions.pass_to_player(
                        state, _choose_pass_target(state, must_pass=True)),
                    lambda: True, 1)
            else:
                return Objective(state,
                                 lambda: actions.look_for_pass_target(state),
                                 lambda: True, 2)
        elif state.is_nearest_ball(1):
            return _jog_to_ball_objective(state)
        else:
            return _position_optimally_objective_goalie(state)

    ball: Ball = state.world_view.ball.get_value()

    # If in possession of the ball -> Pass to team mate
    if state.is_near_ball(KICKABLE_MARGIN):
        pass_target = _choose_pass_target(state)
        if pass_target is not None:
            debug_msg(
                str(state.now()) +
                " | in possession, pass target found -> pass to teammate",
                "GOALIE")
            return Objective(
                state, lambda: actions.pass_to_player(
                    state, _choose_pass_target(state)), lambda: True, 1)
        # No suitable pass target
        debug_msg(
            str(state.now()) +
            " | in possession, pass target not found -> look for pass target",
            "GOALIE")
        return Objective(state, lambda: actions.look_for_pass_target(state),
                         lambda: True, 1)

    # If ball coming to goalie inside box -> Catch ball
    positions = ball.project_ball_position(2, 0)
    if positions is not None and state.is_inside_own_box():
        debug_msg(
            str(state.now()) + " | Ball incoming inside box -> Catch ball",
            "GOALIE")
        ball_pos_1_tick: Coordinate = positions[0]
        if ball_pos_1_tick.euclidean_distance_from(
                state.position.get_value()) < CATCHABLE_MARGIN:
            return Objective(
                state, lambda: actions.catch_ball(state, ball_pos_1_tick),
                lambda: True, 1)

    # If ball coming towards us or ball will hit goal soon -> Intercept
    if (ball.will_hit_goal_within(ticks=5)
            or (state.is_nearest_ball(1) and state.is_ball_inside_own_box())):
        debug_msg(
            str(state.now()) +
            " | ball coming towards us or ball will hit goal soon -> run to ball and catch!",
            "GOALIE")
        intercept_actions = actions.intercept_2(state, "catch")
        if intercept_actions is not None:
            return Objective(state, lambda: intercept_actions)
        else:
            return _rush_to_ball_objective(state)

    # If position not alligned with ball y-position -> Adjust y-position
    if state.position.is_value_known(
    ) and state.world_view.ball.is_value_known(
    ) and not configurations.USING_PASS_CHAIN_STRAT:
        debug_msg(
            str(state.now()) + " | Position not optimal -> adjust position",
            "GOALIE")
        return _position_optimally_objective_goalie(state)

    # If nothing to do -> Face ball
    debug_msg(str(state.now()) + " | Nothing to do -> Face ball", "GOALIE")
    return Objective(state, lambda: actions.face_ball(state), lambda: True, 1)
Esempio n. 18
0
def _choose_pass_target(state: PlayerState, must_pass: bool = False):
    print("choose pass target")
    """
    If uppaal has been generated recently -> Follow strat if applicable
    If free targets forward -> Pass forward
    If no free targets forward, but i am not marked -> dribble forward
    If no free targets forward, but free targets behind, and i am marked -> Pass back
    If no free targets and i am marked -> Try to dribble anyway
    :return: Parse target or None, if dribble
    """

    # For pass chain model, if an existing target is seen by player, pass ball
    if len(state.passchain_targets) > 0:
        print("passchain longer than 0")
        for target in state.passchain_targets:
            target: PrecariousData
            if target.last_updated_time > state.now() - 40:
                print("if target update time is later than 40 seconds ago")
                target = state.find_teammate_closest_to(target.get_value(),
                                                        max_distance_delta=8.0)
                if target is not None:
                    print("TORGET ACQUIRED : ", target)
                    return target

    debug_msg(str(state.now()) + "Choosing pass target", "DRIBBLE_PASS_MODEL")
    # Act according to Possession model
    if state.dribble_or_pass_strat.is_value_known():
        if state.dribble_or_pass_strat.is_value_known(state.now() - 8):
            debug_msg(
                "Following uppaal DribbleOrPass strategy :" +
                str(state.dribble_or_pass_strat.get_value()),
                "DRIBBLE_PASS_MODEL")
            strat = state.dribble_or_pass_strat.get_value()
            state.dribble_or_pass_strat = PrecariousData.unknown()
            if DRIBBLE_INDICATOR in strat:
                if not must_pass:
                    state.statistics.use_possession_strategy()
                    debug_msg(
                        str(state.now()) + " Dribble!", "DRIBBLE_PASS_MODEL")
                    return None

            else:
                match = re.match(r'.*\(([^,]*), ([^)]*)\)', strat)
                x = float(match.group(1))
                y = float(match.group(2))
                target = state.find_teammate_closest_to(Coordinate(x, y),
                                                        max_distance_delta=3.0)
                if target is not None:
                    debug_msg(
                        str(state.now()) +
                        " DRIBBLE_PASS_MODEL : Playing to :" +
                        str(Coordinate(x, y)), "DRIBBLE_PASS_MODEL")

                    # If target is outside the no no square then return target
                    i = -1 if state.world_view.side == "l" else 1
                    is_too_far_back = True if (state.world_view.side == "l" and target.coord.pos_x < -36) \
                                              or (state.world_view.side == "r" and target.coord.pos_x > 36) else False

                    if (not is_too_far_back) and (not is_offside(
                            state, target)) and (target.coord.pos_y > -20
                                                 or target.coord.pos_y > 20):
                        state.statistics.use_possession_strategy()
                        return target
                else:
                    debug_msg(
                        str(state.now()) + "No teammate matched :" +
                        str(Coordinate(x, y)) + " Visible: " +
                        str(state.world_view.get_teammates(
                            state.team_name, 10)), "DRIBBLE_PASS_MODEL")

        # Discard strategy
        state.statistics.discard_possession_strategy()
        state.dribble_or_pass_strat = PrecariousData.unknown()

    side = state.world_view.side
    """ # TODO : TESTING ONLY ----------------------------------------------------------
    teammates = state.world_view.get_teammates(state.team_name, 2)
    if len(teammates) is not 0:
        return choice(teammates)
    # todo -------------------------------------------------------------------------- """

    am_i_marked = state.world_view.is_marked(team=state.team_name,
                                             max_data_age=4,
                                             min_distance=4)

    # If free targets forward -> Pass forward
    forward_team_mates = state.world_view.get_non_offside_forward_team_mates(
        state.team_name,
        side,
        state.position.get_value(),
        max_data_age=4,
        min_distance_free=2,
        min_dist_from_me=2)

    if len(forward_team_mates) > 0:
        # If free team mates sort by closest to opposing teams goal
        opposing_team_goal: Coordinate = Coordinate(
            52.5, 0) if side == "l" else Coordinate(-52.5, 0)
        debug_msg("forward_team_mates: " + str(forward_team_mates),
                  "PASS_TARGET")
        good_target = list(
            sorted(forward_team_mates,
                   key=lambda p: p.coord.euclidean_distance_from(
                       opposing_team_goal),
                   reverse=False))[0]
        return good_target

    # If no free targets forward, but i am not marked -> dribble forward
    if len(forward_team_mates) < 1 and not am_i_marked:
        debug_msg("No free targets forward -> Dribble!", "PASS_TARGET")
        if must_pass:
            tms = state.world_view.get_teammates(state.team_name, 5)
            if len(tms) > 0:
                return random.choice(tms)
        return None

    # If no free targets forward, but free targets behind, and i am marked -> Pass back
    behind_team_mates = state.world_view.get_free_behind_team_mates(
        state.team_name,
        side,
        state.position.get_value(),
        max_data_age=3,
        min_distance_free=3,
        min_dist_from_me=3)
    if len(behind_team_mates) > 0:
        # Get the player furthest forward and free
        opposing_team_goal: Coordinate = Coordinate(
            52.5, 0) if side == "l" else Coordinate(-52.5, 0)
        debug_msg("Behind_team_mates: " + str(behind_team_mates),
                  "PASS_TARGET")
        good_target = list(
            sorted(behind_team_mates,
                   key=lambda p: p.coord.euclidean_distance_from(
                       opposing_team_goal),
                   reverse=False))[0]
        return good_target

    # If no free targets and i am marked -> Try to dribble anyway
    debug_msg("No free targets forward and i am marked -> Dribble anyway!",
              "PASS_TARGET")
    if must_pass:
        tms = state.world_view.get_player_observations(state.team_name, 3)
        if len(tms) > 0:
            return random.choice(tms)
    return None
Esempio n. 19
0
def _update_dribble_or_pass_model(state: PlayerState, model: UppaalModel):
    # This function edits the UPPAAL file to represent the current state of the game

    # Amount of ticks to forecast game state
    # This should be the expected time that it takes to generate the strategy
    FORECAST_TICKS = 6

    team_mates = state.world_view.get_teammates_precarious(state.team_name,
                                                           10,
                                                           min_dist=5)
    opponents = state.world_view.get_opponents_precarious(state.team_name,
                                                          10,
                                                          min_dist=0)

    # Forecast position of the ball possessor
    if state.get_y_north_velocity_vector() is not None:
        possessor_forecasted = (
            state.position.get_value().vector() +
            state.get_y_north_velocity_vector() * FORECAST_TICKS).coord()
    else:
        possessor_forecasted = state.position.get_value()

    # Forecast position of other players
    forecasted_team_positions = list(
        map(
            lambda p: p.get_value().forecasted_position(
                (state.now() - p.last_updated_time) + FORECAST_TICKS),
            team_mates))
    forecasted_opponent_positions = list(
        map(
            lambda p: p.get_value().forecasted_position(
                (state.now() - p.last_updated_time) + FORECAST_TICKS),
            opponents))
    if state.players_close_behind > 0:
        forecasted_opponent_positions.append(
            Coordinate(
                possessor_forecasted.pos_x - 1,
                possessor_forecasted.pos_y,
            ))

    # Convert to textual format understandable by uppaal
    team_pos_value = _to_3d_double_array_coordinate(forecasted_team_positions)
    opponent_pos_value = _to_3d_double_array_coordinate(
        forecasted_opponent_positions)
    possessor_val = _to_2d_double_array_coordinate(possessor_forecasted)

    model.set_global_declaration_value("TEAM_MATES",
                                       len(forecasted_team_positions))
    model.set_global_declaration_value("OPPONENTS",
                                       len(forecasted_opponent_positions))
    model.set_global_declaration_value("team_pos[TEAM_MATES][2]",
                                       team_pos_value)
    model.set_global_declaration_value("opponent_pos[OPPONENTS][2]",
                                       opponent_pos_value)
    model.set_global_declaration_value("possessor[2]", possessor_val)

    if state.is_test_player():  # Debugging
        all_posis = list(
            map(lambda p: p.get_value().coord, state.world_view.other_players))
        debug_msg(
            str(state.now()) + " All positions: " + str(all_posis),
            "DRIBBLE_PASS_MODEL")
        debug_msg(
            str(state.now()) + " Forecasted team positions: " +
            str(team_pos_value), "DRIBBLE_PASS_MODEL")
        debug_msg(
            str(state.now()) + " Forecasted opponent positions: " +
            str(opponent_pos_value), "DRIBBLE_PASS_MODEL")
        debug_msg(
            str(state.now()) + " Forecasted possessor position: " +
            str(possessor_val), "DRIBBLE_PASS_MODEL")

    return forecasted_team_positions
Esempio n. 20
0
  def parse_file(self):
    from lexer import lexer, token
    from parser import parser
    from utils import function, debug_msg
    filename = self.filename
    entry = global_tbl_entry()
    print "parser: Lexing on file:", self.filename
    body = file(self.filename, 'rt').read()
    print 'parser: rORIGINAL:', repr(body)
    print
    print
    print 'parser: -------------TOKENS:------------------'
    lexer = lexer(body)
    parser = parser()
    func_name = None
    curly_brace = 0
    small_brace = 0
    args = ""
    for token in lexer:
      #first find a function name store id and lookahead if brace move to state
      print "parser: parsing token: ", token.get_value()," of type: ", token.get_type()
      if parser.get_state() == "Begin":
        print "parser: parser state Begin"
        if token.get_type() == "Id":
          parser.set_state("FuncName")
          func_name = token.get_value()
      elif parser.get_state() == "FuncName":
        type(token.get_value())
        type(token.get_type())
        if token.get_value() == "(":
          parser.set_state("FuncArgs")
        elif token.get_type() == "Id":
          parser.set_state("FuncName")
          func_name = token.get_value()
        else:
          parser.set_state("Begin")
      elif parser.get_state() == "FuncArgs":
        if token.get_value() == ")":
          parser.set_state("FuncBody")
        elif token.get_value() == ",":
          print "parser: Comma"
        elif token.get_type() == "Id":
          args+=token.get_value()
        else:
          print "parser: found: ", token.get_value()," while parser in state Args"
          #reset parser
          parser.set_state("Begin")
      elif parser.get_state() == "FuncBody":
        if token.get_value() == "{":
          #confirmed function update everything
          parser.set_state("Function")
          aFunction = function()
          aFunction.set_name(func_name)
          aFunction.set_args(args);
          print "parser: ***********Found a function by name : ", func_name, " **************************"
          curly_brace += 1
          #insert function
        elif token.get_type() == "Id":
          parser.set_state("FuncName")
          func_name = token.get_value()
        else:
          parser.set_state("Begin")
      elif parser.get_state() == "Function":
        if token.get_value() == "}":
          curly_brace -= 1
          if curly_brace == 0:
            print "parser: ********* Finished function: ",func_name ,"******************"
            #function ends update everything
            parser.set_state("Begin")
            #close messages for this func
        elif token.get_value() == "{":
          curly_brace += 1
        elif token.get_type() == "Debug":
          parser.set_state("Debug")
          dbg_msg = debug_msg()
          print "MAcro Name ===================================================",token.get_value()
          dbg_msg.set_macro_name(token.get_value())
        elif token.get_type() == "Entry/Exit":
          parser.set_state("DebugEntry/Exit")
          dbg_msg = debug_msg()
          print "MAcro Name ==================================================",token.get_value()
          dbg_msg.set_macro_name(token.get_value())
      elif parser.get_state() == "Debug":
        if token.get_value() == "(":
          if small_brace == 0:
            parser.set_state("DbgMsg")
          small_brace += 1
      elif parser.get_state() == "DbgMsg":
        if token.get_type() == "Quotes":
          dbg_msg.set_message(token.get_value())
        elif token.get_value() == ")":
          small_brace -= 1
          if small_brace == 0:
            print "parser: **** Finished one Debug message***** "
            insert_in_tbl(entry, dbg_msg, aFunction);
            parser.set_state("Function")

        else:
          parser.set_state("DbgMsgArgs")

      elif parser.get_state() == "DbgMsgArgs":
        if token.get_value() == ")":
          small_brace -= 1
          if small_brace == 0:
            print "parser: **** Finished one Debug message***** "
            insert_in_tbl(entry, dbg_msg,aFunction);
            parser.set_state("Function")
        if token.get_value() == "(":
          small_brace += 1
        if token.get_type() in ["Id","Quotes"]:
          dbg_msg.append_args(token.get_value())


      print "parser: ======TESTING: Token value: ",token.get_value()
      print "parser: ======TESTING: Token type: ",token.get_type()

    print "parser: ***********all tables ***********************"
    print
    print "parser: -----------Rest-------------------"
    for val in entry.rest_in_list:
      print "parser: Function: ", val.get_function().get_func_name(), " Message: ", val.get_dbg_msg().get_message()," Debug Args: ", val.get_dbg_msg().get_args()

    print
    print "parser: ----------cmplt_msg_tbl--------------------"
    for hash_key in entry.cmplt_msg_tbl.keys():
      val = entry.cmplt_msg_tbl[hash_key]
      print "parser: Function: ", val.get_function().get_func_name(), " Message: ", val.get_dbg_msg().get_message()," Debug Args: ", val.get_dbg_msg().get_args()

    print
    print "parser: ----------partial_msg_tbl--------------------"
    for hash_key in entry.partial_msg_tbl.keys():
      print hash_key
      val = entry.partial_msg_tbl[hash_key]
      print "parser: Function: ", val.get_function().get_func_name(), " Message: ", val.get_dbg_msg().get_message()," Debug Args: ", val.get_dbg_msg().get_args()
    return entry
Esempio n. 21
0
    def approximate_position_direction_speed(
            self, minimum_data_points_used) -> (Coordinate, int, int):
        if self.projection is not None:
            return self.projection

        if len(self.position_history.list) <= 1:
            return None, None, None  # No information can be deduced about movement of ball
        history = self.position_history.list

        time_1 = history[0][1]
        time_2 = history[1][1]
        c1: Coordinate = history[0][0]
        c2: Coordinate = history[1][0]
        first_coord = c1
        last_coord = c2

        if time_1 == time_2 or c1.euclidean_distance_from(
                c2) < 0.1 or c1.euclidean_distance_from(c2) > 4.2:
            return c1, 0, 0

        final_speed = (c1.euclidean_distance_from(c2) /
                       (time_1 - time_2)) * BALL_DECAY
        final_direction = degrees(calculate_full_origin_angle_radians(c1, c2))
        angles = [final_direction]  # Used for calculating 'average' angle

        max_deviation = 50  # angle deviation
        max_speed_deviation = 0.8
        age = time_1 - time_2
        max_age = 20

        def allowed_angle_deviation(index):
            return 90 if index == 0 else max_deviation

        previous_dist = final_speed
        data_points_used = 2
        for i, pos_and_time in enumerate(islice(history, 2, len(history))):
            c1 = c2
            c2 = pos_and_time[0]
            time_1 = time_2
            time_2 = pos_and_time[1]
            age += time_1 - time_2

            dist = c1.euclidean_distance_from(c2)
            if time_1 == time_2 or dist <= 0.05 or (
                    dist < 0.3 and previous_dist < 0.3) or dist > 4.2:
                break
            previous_dist = dist

            # calculate angle from point observed 2 ticks prior
            direction = degrees(
                calculate_full_origin_angle_radians(history[i][0], c2))
            direction_similar = is_angle_in_range(
                direction,
                (final_direction - allowed_angle_deviation(i)) % 360,
                (final_direction + allowed_angle_deviation(i)) % 360)

            speed = (dist / (time_1 - time_2)) * pow(BALL_DECAY, age)
            speed_similar = (final_speed - max_speed_deviation) <= speed <= (
                final_speed + max_speed_deviation)

            if direction_similar and speed_similar and age < max_age:
                data_points_used += 1
                last_coord = c2
                angles.append(
                    degrees(
                        calculate_full_origin_angle_radians(first_coord, c2)))
                final_speed = (final_speed * age + speed) / (
                    age + 1)  # calculate average with new value
                final_direction = find_mean_angle(angles, 179)
            else:
                debug_msg(
                    "Previous points did not match. Speed : " + str(speed) +
                    "vs." + str(final_speed) + "| Direction :" +
                    str(direction) + "vs." + str(final_direction) + "| age: " +
                    str(age) + str(c1) + str(c2), "POSITIONAL")
                break  # This vector did not fit projection, so no more history is used in the projection

        if data_points_used < minimum_data_points_used:
            return None, None, None

        debug_msg(
            "Prediction based on {0} of these data points: {1}".format(
                data_points_used, self.position_history), "INTERCEPTION")

        direction = degrees(
            calculate_full_origin_angle_radians(first_coord, last_coord))
        self.projection = self.position_history.list[0][
            0], direction, final_speed
        return self.position_history.list[0][0], direction, final_speed