Пример #1
0
    def __init__(self):
        super().__init__(start_state=DoubleTouchTracker.State.start)

        for state in DoubleTouchTracker.State:
            self.add_state(state)

        # FIXME: is it only restart plays?
        self.add_transition(
            DoubleTouchTracker.State.start,
            DoubleTouchTracker.State.restart_play_began,
            lambda: (main.root_play().play is not None and
                     main.root_play().play.__class__.is_restart() and
                     main.game_state().is_our_restart()),
            'we start running an offensive restart play')

        self.add_transition(
            DoubleTouchTracker.State.restart_play_began,
            DoubleTouchTracker.State.kicking,
            lambda: ((any(self._touching_ball(bot) for bot in main.our_robots())) or
                     main.game_state().is_playing()) and not main.game_state().is_placement(),
            'one of our bots has the ball or the ball was kicked')

        self.add_transition(DoubleTouchTracker.State.kicking,
                            DoubleTouchTracker.State.kicker_forbidden,
                            # The ball is no longer in restart, we have begun playing
                            (lambda: main.game_state().is_playing() or
                             # We aren't in a restart anymore
                             main.root_play().play is None or
                             not main.root_play().play.__class__.is_restart()),
                            'ball has moved and is now in play')

        self.add_transition(DoubleTouchTracker.State.kicker_forbidden,
                            DoubleTouchTracker.State.other_robot_touched,
                            lambda: self.other_robot_touching_ball(),
                            'another robot has touched the ball')
Пример #2
0
    def __init__(self):
        super().__init__(continuous=False)

        for substate in Penalty.State:
            self.add_state(substate, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
            Penalty.State.waiting,
            lambda: True,
            'immediately')

        self.add_transition(Penalty.State.waiting,
            Penalty.State.setup,
            lambda: main.game_state().is_setup_state(),
            'ref says time to setup')

        for state in [Penalty.State.waiting, Penalty.State.setup]:
            self.add_transition(state,
                Penalty.State.ready,
                lambda: main.game_state().is_ready_state(),
                'ref says ready')

        self.add_transition(Penalty.State.ready,
            behavior.Behavior.State.completed,
            lambda: self.subbehavior_with_name('kick').state == behavior.Behavior.State.completed,
            'done kicking')
Пример #3
0
    def __init__(self):
        super().__init__(continuous=True)

        for substate in Goalie.State:
            self.add_state(substate, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start, Goalie.State.chill,
                            lambda: True, "immediately")

        self.add_transition(Goalie.State.chill, Goalie.State.defend,
                            lambda: main.ball().valid, "ball is valid")

        non_chill_states = [s for s in Goalie.State if s != Goalie.State.chill]

        # if ball is invalid, chill
        for state in non_chill_states:
            self.add_transition(state, Goalie.State.chill,
                                lambda: not main.ball().valid,
                                "ball is invalid")

        for state in non_chill_states:
            self.add_transition(
                state, Goalie.State.setup_penalty,
                lambda: main.game_state().is_their_penalty() and main.game_state().is_setup_state(),
                "setting up for opponent penalty")

        for state in [s2
                      for s2 in non_chill_states
                      if s2 != Goalie.State.intercept]:
            self.add_transition(
                state, Goalie.State.intercept,
                lambda: evaluation.ball.is_moving_towards_our_goal() and not self.robot_is_facing_our_goal(evaluation.ball.opponent_with_ball()),
                "ball coming towards our goal")

        for state in [s2 for s2 in non_chill_states
                      if s2 != Goalie.State.clear]:
            self.add_transition(
                state, Goalie.State.clear,
                lambda: evaluation.ball.is_in_our_goalie_zone() and not main.game_state().is_their_penalty() and not evaluation.ball.is_moving_towards_our_goal() and evaluation.ball.opponent_with_ball() is None,
                "ball in our goalie box, but not headed toward goal")

        for state in [s2 for s2 in non_chill_states
                      if s2 != Goalie.State.defend]:
            self.add_transition(
                state, Goalie.State.defend,
                lambda: not evaluation.ball.is_in_our_goalie_zone() and not evaluation.ball.is_moving_towards_our_goal() and not main.game_state().is_their_penalty() and not self.robot_is_facing_our_goal(evaluation.ball.opponent_with_ball()),
                'not much going on')

        for state in [s2 for s2 in non_chill_states
                      if s2 != Goalie.State.block]:
            self.add_transition(
                state, Goalie.State.block,
                lambda: not evaluation.ball.is_in_our_goalie_zone() and not evaluation.ball.is_moving_towards_our_goal() and self.robot_is_facing_our_goal(evaluation.ball.opponent_with_ball()),
                "opponents have possession")
    def execute_marking(self):
        move = self.subbehavior_with_name('move')
        move.pos = self.move_target

        left_seg = robocup.Segment(
            robocup.Point(-constants.Field.PenaltyLongDist / 2, 0),
            robocup.Point(-constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))
        right_seg = robocup.Segment(
            robocup.Point(constants.Field.PenaltyLongDist / 2, 0),
            robocup.Point(constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))
        top_seg = robocup.Segment(
            robocup.Point(-constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist),
            robocup.Point(constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))

        if move.pos is not None:
            main.system_state().draw_circle(move.pos, 0.02,
                                            constants.Colors.Green, "Mark")
            main.system_state().draw_segment(left_seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_segment(top_seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_segment(right_seg, constants.Colors.Green,
                                             "Mark")

        # make the defender face the threat it's defending against
        if (self.robot is not None and self.block_line is not None):
            self.robot.face(self.block_line.get_pt(0))

        if self.robot.has_ball() and not main.game_state().is_stopped():
            self.robot.kick(0.75)
Пример #5
0
 def score(cls):
     gs = main.game_state()
     if gs.is_ready_state() and gs.is_our_direct() and main.ball().pos.y > (
             constants.Field.Length - 1.0):
         return 1
     else:
         return float("inf")
Пример #6
0
    def __init__(self):
        super().__init__(continuous=True)

        for state in Placement.State:
            self.add_state(state, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            Placement.State.placing, lambda: True,
                            'immediately')
        self.add_transition(Placement.State.placing, Placement.State.reset,
                            lambda: self.check_update(), 'command changed')
        self.add_transition(Placement.State.reset, Placement.State.placing,
                            lambda: True, 'immediately')

        self._pos = main.game_state().get_ball_placement_point()
        self._our_restart = main.game_state().is_our_restart()
Пример #7
0
    def __init__(self):
        super().__init__(start_state=DoubleTouchTracker.State.start)

        for state in DoubleTouchTracker.State:
            self.add_state(state)

        # FIXME: is it only restart plays?
        self.add_transition(
            DoubleTouchTracker.State.start,
            DoubleTouchTracker.State.restart_play_began, lambda:
            (main.root_play().play != None and main.root_play().play.__class__.
             is_restart() and main.game_state().is_our_restart()),
            'we start running an offensive restart play')

        self.add_transition(
            DoubleTouchTracker.State.restart_play_began,
            DoubleTouchTracker.State.kicking,
            lambda: any(bot.has_ball() for bot in main.our_robots()),
            'one of our bots has the ball')

        self.add_transition(DoubleTouchTracker.State.kicking,
                            DoubleTouchTracker.State.kicker_forbidden,
                            lambda: not self.kicker_has_possession(),
                            'kicker kicks or fumbles ball')

        self.add_transition(DoubleTouchTracker.State.kicker_forbidden,
                            DoubleTouchTracker.State.other_robot_touched,
                            lambda: self.other_robot_touching_ball(),
                            'another robot has touched the ball')
Пример #8
0
    def __init__(self):
        super().__init__(continuous=True)

        for state in TheirShootOut.State:
            self.add_state(state, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            TheirShootOut.State.starting, lambda: True,
                            'immediately')

        self.add_transition(TheirShootOut.State.starting,
                            TheirShootOut.State.block,
                            lambda: main.game_state().is_playing(), 'block')

        #go intercept if enemy robot doesn't have the ball or is within chip range
        self.add_transition(TheirShootOut.State.block,
                            TheirShootOut.State.intercept,
                            lambda: not self.has_ball(), 'intercept')

        #go back to blocking if the robot reclaims control of the ball and is outside chip range.
        self.add_transition(
            TheirShootOut.State.intercept, TheirShootOut.State.block,
            lambda: self.has_ball() and not self.in_chip_distance(), 'reblock')

        self.add_transition(
            TheirShootOut.State.block, TheirShootOut.State.capture,
            lambda: self.in_chip_distance() and self.has_ball(), 'capture')

        self.add_transition(
            TheirShootOut.State.intercept, TheirShootOut.State.capture,
            lambda: self.in_chip_distance() and self.has_ball(), 'capture')

        self.block_percentage = .50
        self.chip_distance = 3.0
        self.ball_lost_distance = 0.5
    def execute_marking(self):
        move = self.subbehavior_with_name('move')
        move.pos = self.move_target

        left_seg = robocup.Segment(
            robocup.Point(-constants.Field.PenaltyLongDist / 2, 0),
            robocup.Point(-constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))
        right_seg = robocup.Segment(
            robocup.Point(constants.Field.PenaltyLongDist / 2, 0),
            robocup.Point(constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))
        top_seg = robocup.Segment(
            robocup.Point(-constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist),
            robocup.Point(constants.Field.PenaltyLongDist / 2,
                          constants.Field.PenaltyShortDist))

        if move.pos is not None:
            main.system_state().draw_circle(move.pos, 0.02,
                                            constants.Colors.Green, "Mark")
            main.system_state().draw_segment(left_seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_segment(top_seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_segment(right_seg, constants.Colors.Green,
                                             "Mark")

        # make the defender face the threat it's defending against
        if (self.robot is not None and self.block_line is not None):
            self.robot.face(self.block_line.get_pt(0))

        if self.robot.has_ball() and not main.game_state().is_stopped() and not self._self_goal(self.robot):
            self.robot.kick(0.75)
 def score(cls):
     gs = main.game_state()
     if gs.is_ready_state() and gs.is_our_direct() and main.ball().pos.y > (
             constants.Field.Length - 1.0):
         return 1
     else:
         return float("inf")
Пример #11
0
    def __init__(self):
        super().__init__(continuous=True)

        for state in Placement.State:
            self.add_state(state, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            Placement.State.placing, lambda: True,
                            'immediately')
        self.add_transition(Placement.State.placing, Placement.State.reset,
                            lambda: self.check_update(), 'command changed')
        self.add_transition(Placement.State.reset, Placement.State.placing,
                            lambda: True, 'immediately')

        self._pos = main.game_state().get_ball_placement_point()
        self._our_restart = main.game_state().is_our_restart()
Пример #12
0
    def __init__(self):
        super().__init__(continuous=False)

        self.pause_time = 0

        for substate in OurPlacement.State:
            self.add_state(substate, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            OurPlacement.State.dribble, lambda: True,
                            'immediately')

        #place the ball in the target area
        self.add_transition(
            OurPlacement.State.dribble, OurPlacement.State.pause,
            lambda: self.subbehavior_with_name('dribble').state == behavior.Behavior.State.completed,
            'finished dribbling')

        self.add_transition(OurPlacement.State.pause, OurPlacement.State.avoid,
                            lambda: time.time() - self.pause_time >= 1,
                            'pause for 1 seconds')

        #if the ball comes out of the target area, put it back
        self.add_transition(
            OurPlacement.State.avoid, OurPlacement.State.dribble,
            lambda: (main.ball().pos - main.game_state().get_ball_placement_point()).mag() > 0.1,
            'ball moved out of target area')
Пример #13
0
    def __init__(self):
        super().__init__(start_state=DoubleTouchTracker.State.start)

        for state in DoubleTouchTracker.State:
            self.add_state(state)

        # FIXME: is it only restart plays?
        self.add_transition(DoubleTouchTracker.State.start,
            DoubleTouchTracker.State.restart_play_began,
            lambda: (main.root_play().play != None
                and main.root_play().play.__class__.is_restart()
                and main.game_state().is_our_restart()),
            'we start running an offensive restart play')

        self.add_transition(DoubleTouchTracker.State.restart_play_began,
            DoubleTouchTracker.State.kicking,
            lambda: any(bot.has_ball() for bot in main.our_robots()),
            'one of our bots has the ball')

        self.add_transition(DoubleTouchTracker.State.kicking,
            DoubleTouchTracker.State.kicker_forbidden,
            lambda: not self.kicker_has_possession(),
            'kicker kicks or fumbles ball')

        self.add_transition(DoubleTouchTracker.State.kicker_forbidden,
            DoubleTouchTracker.State.other_robot_touched,
            lambda: self.other_robot_touching_ball(),
            'another robot has touched the ball')
Пример #14
0
    def __init__(self):
        super().__init__(continuous=False)

        self._kicker_shell_id = None

        for state in OurKickoff.State:
            self.add_state(state, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            OurKickoff.State.setup, lambda: True,
                            'immediately')

        self.add_transition(OurKickoff.State.setup, OurKickoff.State.kick,
                            lambda: not main.game_state().is_setup_state(),
                            "referee leaves setup")

        self.add_transition(
            OurKickoff.State.kick, behavior.Behavior.State.completed,
            lambda: self.has_subbehavior_with_name('kicker') and self.subbehavior_with_name('kicker').is_done_running(),
            "kicker finished")

        # TODO: verify that these values are right - I'm fuzzy on my matrix multiplication...
        idle_positions = [
            robocup.Point(0.7, constants.Field.Length / 2.0 - 0.2),
            robocup.Point(-0.7, constants.Field.Length / 2.0 - 0.2)
        ]
        self.centers = []
        for i, pos_i in enumerate(idle_positions):
            center_i = skills.move.Move(pos_i)
            self.add_subbehavior(center_i,
                                 'center' + str(i),
                                 required=False,
                                 priority=4 - i)
            self.centers.append(center_i)
Пример #15
0
    def should_clear_ball(self):

        if main.game_state().is_stopped():
            return False

        #Returns true if our robot can reach the ball sooner than the closest opponent
        safe_to_clear = False
        if main.ball().pos.mag() < constants.Field.ArcRadius * 2 and main.ball(
        ).vel.mag() < .75 and not evaluation.ball.is_in_our_goalie_zone():

            defender1 = self.subbehavior_with_name('defender1')
            defender2 = self.subbehavior_with_name('defender2')
            if (defender1.robot != None and defender2.robot != None):
                max_vel = robocup.MotionConstraints.MaxRobotSpeed.value
                max_accel = robocup.MotionConstraints.MaxRobotAccel.value

                for robot in main.system_state().their_robots:
                    their_dist_to_ball = robot.pos.dist_to(main.ball().pos)
                    #if their robot is moving faster than ours, assume it is at its maximum speed, otherwise assume its max speed is the same as ours
                    their_max_vel = max(max_vel, robot.vel.mag())

                #calculate time for the closest opponent to reach ball based on current /vel/pos data * .9 for safety
                their_time_to_ball = (
                    their_dist_to_ball /
                    their_max_vel) * defender1.safety_multiplier

                if their_time_to_ball > evaluation.ball.time_to_ball(
                        defender1.robot
                ) or their_time_to_ball > evaluation.ball.time_to_ball(
                        defender2.robot):
                    safe_to_clear = True

        return safe_to_clear
Пример #16
0
 def score(cls):
     gs = main.game_state()
     if len(main.our_robots()) < 5:
         return float("inf")
     if (gs.is_ready_state() and gs.is_our_free_kick() and
             main.ball().pos.y > (constants.Field.Length - 1.2) and
             abs(main.ball().pos.x) > .6):
         return 0
     else:
         return 10000
    def setupStates(self):
        self.gameState = main.game_state()
        self.systemState = main.system_state()
        self.context = main.context()
        for g in self.systemState.our_robots:
            self.robotList.append(g)
        for g in self.systemState.their_robots:
            self.robotList.append(g)

        self.updateRobotList()
Пример #18
0
    def __init__(self, indirect=None):
        super().__init__(continuous=True)

        # If we are indirect we don't want to shoot directly into the goal
        gs = main.game_state()

        if indirect != None:
            self.indirect = indirect
        elif main.ball().pos.y > constants.Field.Length / 2.0:
            self.indirect = gs.is_indirect()
        else:
            self.indirect = False

        self.add_transition(behavior.Behavior.State.start,
                            behavior.Behavior.State.running, lambda: True,
                            'immediately')

        # FIXME: this could also be a PivotKick
        kicker = skills.line_kick.LineKick()
        # kicker.use_chipper = True
        kicker.min_chip_range = 0.3
        kicker.max_chip_range = 3.0
        # This will be reset to something else if indirect on the first iteration
        kicker.target = constants.Field.TheirGoalSegment

        # add two 'centers' that just move to fixed points
        center1 = skills.move.Move(robocup.Point(0, 1.5))
        self.add_subbehavior(center1, 'center1', required=False, priority=4)
        center2 = skills.move.Move(robocup.Point(0, 1.5))
        self.add_subbehavior(center2, 'center2', required=False, priority=3)

        if self.indirect:
            receive_pt, target_point, probability = evaluation.touchpass_positioning.eval_best_receive_point(
                main.ball().pos)
            pass_behavior = tactics.coordinated_pass.CoordinatedPass(
                receive_pt,
                None,
                (kicker, lambda x: True),
                receiver_required=False,
                kicker_required=False,
                prekick_timeout=9)
            # We don't need to manage this anymore
            self.add_subbehavior(pass_behavior, 'kicker')

            kicker.target = receive_pt
        else:
            kicker = skills.line_kick.LineKick()
            kicker.target = constants.Field.TheirGoalSegment
            self.add_subbehavior(kicker, 'kicker', required=False, priority=5)

        self.add_transition(
            behavior.Behavior.State.running, behavior.Behavior.State.completed,
            lambda: self.subbehavior_with_name('kicker').is_done_running() and self.subbehavior_with_name('kicker').state != tactics.coordinated_pass.CoordinatedPass.State.timeout,
            'kicker completes')
Пример #19
0
    def __init__(self, indirect=None):
        super().__init__(continuous=True)

        # If we are indirect we don't want to shoot directly into the goal
        gs = main.game_state()

        if indirect is not None:
            self.indirect = indirect
        elif main.ball().pos.y > constants.Field.Length / 2.0:
            self.indirect = gs.is_indirect()
        else:
            self.indirect = False

        self.add_transition(behavior.Behavior.State.start,
                            behavior.Behavior.State.running, lambda: True,
                            'immediately')

        # FIXME: this could also be a PivotKick
        kicker = skills.line_kick.LineKick()
        # kicker.use_chipper = True
        kicker.min_chip_range = 0.3
        kicker.max_chip_range = 3.0
        # This will be reset to something else if indirect on the first iteration
        kicker.target = constants.Field.TheirGoalSegment

        # add two 'centers' that just move to fixed points
        center1 = skills.move.Move(robocup.Point(0, 1.5))
        self.add_subbehavior(center1, 'center1', required=False, priority=4)
        center2 = skills.move.Move(robocup.Point(0, 1.5))
        self.add_subbehavior(center2, 'center2', required=False, priority=3)

        if self.indirect:
            receive_pt, target_point, probability = evaluation.touchpass_positioning.eval_best_receive_point(
                main.ball().pos)
            pass_behavior = tactics.coordinated_pass.CoordinatedPass(
                receive_pt,
                None,
                (kicker, lambda x: True),
                receiver_required=False,
                kicker_required=False,
                prekick_timeout=9)
            # We don't need to manage this anymore
            self.add_subbehavior(pass_behavior, 'kicker')

            kicker.target = receive_pt
        else:
            kicker = skills.line_kick.LineKick()
            kicker.target = constants.Field.TheirGoalSegment
            self.add_subbehavior(kicker, 'kicker', required=False, priority=5)

        self.add_transition(
            behavior.Behavior.State.running, behavior.Behavior.State.completed,
            lambda: self.subbehavior_with_name('kicker').is_done_running() and self.subbehavior_with_name('kicker').state != tactics.coordinated_pass.CoordinatedPass.State.timeout,
            'kicker completes')
Пример #20
0
    def score(cls):
        gs = main.game_state()

        # enter play when doing a corner kick or stay in it even if we manipulate the ball
        if OurIndirectPivot.Running or (gs.is_ready_state() and
                                        (gs.is_our_direct()
                                         or gs.is_our_indirect())
                                        and main.ball().pos.y <
                                        (constants.Field.Length - 1.2)):
            OurIndirectPivot.Running = True
            return 0
        else:
            return float("inf")
Пример #21
0
def minimax(board, depth=4, sense=1, alpha=float("-inf"), beta=float("inf")):
    """
    Minimax algorithm looking multiple moves ahead to determine optimal moves.
    Uses alpha-beta pruning.
    :param board: current board state
    :param depth: number of turns ahead to look
    :param sense: determines whether player is minimizing or maximizing score
    :param alpha: lower bound for maximum score
    :param beta: upper bound for minimum score
    :return: optimal move
    """
    if game_state(board) == "draw":
        return [[], 0]
    elif game_state(board) == turn(board):
        return [[], (1000 + depth) * sense]
    elif game_state(board) == opp(board):
        return [[], (-1000 + depth) * sense]
    elif depth == 0:
        score = 0
        if two(board, turn(board)):
            score += 100 * sense
        if two(board, opp(board)):
            score -= 100 * sense
        return [[], score]
    best_move = []
    result = float('inf') * -sense
    for move in find_moves(board):
        b = board.copy_board()
        Player().make_move(b, move)
        curr = minimax(b, depth - 1, -sense, alpha, beta)[1]
        if curr > result and sense == 1 or curr < result and sense == -1:
            best_move, result = move, curr
        if sense == 1:
            alpha = max(alpha, curr)
        else:
            beta = min(beta, curr)
        if alpha >= beta:
            break
    return [best_move, result]
Пример #22
0
    def __init__(self):
        super().__init__(continuous=False)

        for substate in Penalty.State:
            self.add_state(substate, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            Penalty.State.waiting, lambda: True, 'immediately')

        self.add_transition(Penalty.State.waiting, Penalty.State.setup,
                            lambda: main.game_state().is_setup_state(),
                            'ref says time to setup')

        for state in [Penalty.State.waiting, Penalty.State.setup]:
            self.add_transition(state, Penalty.State.ready,
                                lambda: main.game_state().is_ready_state(),
                                'ref says ready')

        self.add_transition(
            Penalty.State.ready, behavior.Behavior.State.completed,
            lambda: self.subbehavior_with_name('kick').state == behavior.
            Behavior.State.completed, 'done kicking')
Пример #23
0
    def __init__(self):
        super().__init__(start_state=DoubleTouchTracker.State.start)

        for state in DoubleTouchTracker.State:
            self.add_state(state)

        # FIXME: is it only restart plays?
        self.add_transition(
            DoubleTouchTracker.State.start,
            DoubleTouchTracker.State.restart_play_began, lambda:
            (main.root_play().play is not None and main.root_play().play.
             __class__.is_restart() and main.game_state().is_our_restart()),
            'we start running an offensive restart play')

        self.add_transition(
            DoubleTouchTracker.State.restart_play_began,
            DoubleTouchTracker.State.kicking, lambda: (
                (any(self._touching_ball(bot)
                     for bot in main.our_robots())) or main.game_state(
                     ).is_playing()) and not main.game_state().is_placement(),
            'one of our bots has the ball or the ball was kicked')

        self.add_transition(
            DoubleTouchTracker.State.kicking,
            DoubleTouchTracker.State.kicker_forbidden,
            # The ball is no longer in restart, we have begun playing
            (
                lambda: main.game_state().is_playing() or
                # We aren't in a restart anymore
                main.root_play().play is None or not main.root_play().play.
                __class__.is_restart()),
            'ball has moved and is now in play')

        self.add_transition(DoubleTouchTracker.State.kicker_forbidden,
                            DoubleTouchTracker.State.other_robot_touched,
                            lambda: self.other_robot_touching_ball(),
                            'another robot has touched the ball')
Пример #24
0
    def __init__(self):
        super().__init__(continuous=True)

        for s in OurShootoutKick.State:
            self.add_state(s, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            OurShootoutKick.State.starting, lambda: True,
                            'immediately')

        # begin to kick as soon as given the ready signal
        self.add_transition(OurShootoutKick.State.starting,
                            OurShootoutKick.State.shooting,
                            lambda: main.game_state().is_ready_state(),
                            'shoot when given the ready signal')
Пример #25
0
    def __init__(self):
        super().__init__(continuous=True)

        #initalize states
        for s in OurShootoutChip.State:
            self.add_state(s, behavior.Behavior.State.running)

        # add transition to lead into the first state (starting/setup state)
        self.add_transition(behavior.Behavior.State.start,
                            OurShootoutChip.State.starting, lambda: True,
                            'immediately')

        # one the ball is able to be hit begin dribbling a meter up
        self.add_transition(OurShootoutChip.State.starting,
                            OurShootoutChip.State.dribbling,
                            lambda: main.game_state().is_ready_state(),
                            'begin')

        # if the goalie gets too close chip over him
        self.add_transition(OurShootoutChip.State.dribbling,
                            OurShootoutChip.State.chipping,
                            lambda: self.is_goalie_close(), 'goalie in range')

        # if the goalie is not too close and we reach a "must shoot time" (since we only have 10s)
        # just kick the ball into goal
        self.add_transition(
            OurShootoutChip.State.dribbling, OurShootoutChip.State.shooting,
            lambda: not self.is_goalie_close() and self.must_shoot_time(),
            'must shoot')

        # if the ball fails to go in after a chip try to capture
        self.add_transition(
            OurShootoutChip.State.chipping, OurShootoutChip.State.capture,
            lambda: self.has_subbehavior_with_name(
                'chipping') and self.subbehavior_with_name('chipping').state ==
            behavior.Behavior.State.completed, 'recapture')

        # after you capture shoot the ball with a kick
        self.add_transition(
            OurShootoutChip.State.capture, OurShootoutChip.State.shooting,
            lambda: self.subbehavior_with_name('capture').state == behavior.
            Behavior.State.completed, 'reshoot')

        self.total_time = 10.0
        self.shoot_time = 6.0
        self.start_time = time.time()
        self.chip_distance = 1.5
        self.goalie_range = 2
Пример #26
0
    def should_clear_ball(self):
        if main.game_state().is_stopped():
            return False

        safe_to_clear = False
        if (abs(main.ball().pos.x) < constants.Field.PenaltyLongDist
                and main.ball().pos.y < constants.Field.PenaltyShortDist * 2
                and main.ball().vel.mag() < .75
                and not evaluation.ball.is_in_our_goalie_zone()):
            defender1 = self.subbehavior_with_name('defender1')
            defender2 = self.subbehavior_with_name('defender2')
            if (defender1.robot != None and defender2.robot != None):

                defenders = [defender1.robot, defender2.robot]

                # See if we can reach the ball before them
                safe_to_clear, bot_to_clear = evaluation.path.can_collect_ball_before_opponent(
                    our_robots_to_check=defenders)

        return safe_to_clear
Пример #27
0
    def should_clear_ball(self):
        if main.game_state().is_stopped():
            return False

        safe_to_clear = False
        if (abs(main.ball().pos.x) < constants.Field.PenaltyLongDist and 
            main.ball().pos.y < constants.Field.PenaltyShortDist * 2 and 
            main.ball().vel.mag() < .75 and 
            not evaluation.ball.is_in_our_goalie_zone()):
            defender1 = self.subbehavior_with_name('defender1')
            defender2 = self.subbehavior_with_name('defender2')
            if (defender1.robot != None and defender2.robot != None):

                defenders = [defender1.robot, defender2.robot]

                # See if we can reach the ball before them
                safe_to_clear, bot_to_clear = evaluation.path.can_collect_ball_before_opponent(
                    our_robots_to_check=defenders)

        return safe_to_clear
Пример #28
0
    def __init__(self):
        super().__init__(continuous=False)

        self._kicker_shell_id = None

        for state in OurKickoff.State:
            self.add_state(state, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start,
                            OurKickoff.State.setup, lambda: True,
                            'immediately')

        self.add_transition(OurKickoff.State.setup, OurKickoff.State.kick,
                            lambda: not main.game_state().is_setup_state(),
                            "referee leaves setup")

        self.add_transition(
            OurKickoff.State.kick, behavior.Behavior.State.completed,
            lambda: self.has_subbehavior_with_name('kicker') and self.
            subbehavior_with_name('kicker').is_done_running(),
            "kicker finished")

        # TODO: verify that these values are right - I'm fuzzy on my matrix multiplication...
        idle_positions = [
            robocup.Point(0.7, constants.Field.Length / 2.0 - 0.2),
            robocup.Point(-0.7, constants.Field.Length / 2.0 - 0.2)
        ]
        self.centers = []
        for i, pos_i in enumerate(idle_positions):
            center_i = skills.move.Move(pos_i)
            self.add_subbehavior(center_i,
                                 'center' + str(i),
                                 required=False,
                                 priority=4 - i)
            self.centers.append(center_i)

        self.add_subbehavior(tactics.defense.Defense(),
                             'defense',
                             required=False)
Пример #29
0
    def __init__(self):
        super().__init__(continuous=True)

        self.debug = False

        self.add_transition(behavior.Behavior.State.start,
                            behavior.Behavior.State.running, lambda: True,
                            'immediately')

        self.marks = []

        if (main.game_state().is_their_direct()):
            self.intercept = (constants.Field.OurGoalSegment.center() -
                              main.ball().pos) * 0.25 + main.ball().pos
            self.add_subbehavior(skills.move.Move(self.intercept),
                                 'intercept direct',
                                 required=False,
                                 priority=5)

        for i in range(3):
            mark_i = skills.mark.Mark()
            mark_i.ratio = 0.7
            self.add_subbehavior(mark_i,
                                 'mark' + str(i),
                                 required=False,
                                 priority=3 - i)
            self.marks.append(mark_i)

        self.kick_eval = robocup.KickEvaluator(main.system_state())
        self.kick_eval.debug = True
        for i, robot in enumerate(main.our_robots()):
            self.kick_eval.add_excluded_robot(robot)

        for i, robot in enumerate(main.their_robots()):
            self.kick_eval.add_excluded_robot(robot)

        their_kicker = min(main.their_robots(),
                           key=lambda opp: opp.pos.dist_to(main.ball().pos))
        self.kick_eval.add_excluded_robot(their_kicker)
    def execute_marking(self):
        move = self.subbehavior_with_name('move')
        move.pos = self.move_target

        arc_left = robocup.Arc(
            robocup.Point(-constants.Field.GoalFlat / 2, 0),
            constants.Field.ArcRadius + constants.Robot.Radius * 2,
            math.pi / 2, math.pi)
        arc_right = robocup.Arc(
            robocup.Point(constants.Field.GoalFlat / 2, 0),
            constants.Field.ArcRadius + constants.Robot.Radius * 2, 0,
            math.pi / 2)
        seg = robocup.Segment(
            robocup.Point(
                -constants.Field.GoalFlat / 2,
                constants.Field.ArcRadius + constants.Robot.Radius * 2),
            robocup.Point(
                constants.Field.GoalFlat / 2,
                constants.Field.ArcRadius + constants.Robot.Radius * 2))

        if move.pos is not None:
            main.system_state().draw_circle(move.pos, 0.02,
                                            constants.Colors.Green, "Mark")
            main.system_state().draw_segment(seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_arc(arc_left, constants.Colors.Green,
                                         "Mark")
            main.system_state().draw_arc(arc_right, constants.Colors.Green,
                                         "Mark")

        # make the defender face the threat it's defending against
        if (self.robot is not None and self.block_line is not None):
            self.robot.face(self.block_line.get_pt(0))

        if self.robot.has_ball() and not main.game_state().is_stopped():
            self.robot.kick(0.75)
    def execute_marking(self):
        move = self.subbehavior_with_name('move')
        move.pos = self.move_target

        arc_left = robocup.Arc(
            robocup.Point(-constants.Field.GoalFlat / 2, 0),
            constants.Field.ArcRadius + constants.Robot.Radius * 2,
            math.pi / 2, math.pi)
        arc_right = robocup.Arc(
            robocup.Point(constants.Field.GoalFlat / 2, 0),
            constants.Field.ArcRadius + constants.Robot.Radius * 2, 0,
            math.pi / 2)
        seg = robocup.Segment(
            robocup.Point(
                -constants.Field.GoalFlat / 2,
                constants.Field.ArcRadius + constants.Robot.Radius * 2),
            robocup.Point(
                constants.Field.GoalFlat / 2,
                constants.Field.ArcRadius + constants.Robot.Radius * 2))

        if move.pos is not None:
            main.system_state().draw_circle(move.pos, 0.02,
                                            constants.Colors.Green, "Mark")
            main.system_state().draw_segment(seg, constants.Colors.Green,
                                             "Mark")
            main.system_state().draw_arc(arc_left, constants.Colors.Green,
                                         "Mark")
            main.system_state().draw_arc(arc_right, constants.Colors.Green,
                                         "Mark")

        # make the defender face the threat it's defending against
        if (self.robot is not None and self.block_line is not None):
            self.robot.face(self.block_line.get_pt(0))

        if self.robot.has_ball() and not main.game_state().is_stopped():
            self.robot.kick(0.75)
Пример #32
0
    def execute_running(self):
        # update double touch tracker
        evaluation.double_touch.tracker().spin()

        # cache and calculate the score() function for each play class
        main.play_registry().recalculate_scores()

        # Play Selection
        ################################################################################

        if main.game_state().is_stopped():
            if not isinstance(self.play, plays.stopped.Stopped):
                logging.info("Running 'Stopped' play due to game state change")
                self.play = plays.stopped.Stopped()
                self._currently_restarting = True
        elif main.game_state().is_halted():
            self.play = None
        else:
            # (play_class, score value) tuples
            enabled_plays_and_scores = [p for p in main.play_registry().get_enabled_plays_and_scores()]

            # only let restart play run once
            enabled_plays_and_scores = [p for p in enabled_plays_and_scores if not p[0].is_restart() or ( p[0].is_restart() and self._currently_restarting)]

            # handle temporary blacklisting
            # we remove the blacklisted play class from selection for this iteration, then unblacklist it
            enabled_plays_and_scores = [p for p in enabled_plays_and_scores if p[0] != self.temporarily_blacklisted_play_class]
            self.temporarily_blacklisted_play_class = None

            # see if we need to kill current play or if it's done running
            if self.play != None:
                if self.play.__class__ not in map(lambda tup: tup[0], enabled_plays_and_scores):
                    logging.info("Current play '" + self.play.__class__.__name__ + "' no longer enabled, aborting")
                    self.play.terminate()
                    self.play = None
                elif self.play.is_done_running():
                    logging.info("Current play '" + self.play.__class__.__name__ + "' finished running")
                    if self.play.is_restart:
                        self._currently_restarting = False
                    self.play = None
                elif self.play.__class__.score() == float("inf"):
                    logging.info("Current play '" + self.play.__class__.__name__ + "' no longer applicable, ending")
                    self.play.terminate()
                    self.play = None

            if self.play == None:
                # reset the double-touch tracker
                evaluation.double_touch.tracker().restart()

                try:
                    if len(enabled_plays_and_scores) > 0:
                        # select the play with the smallest value for score()
                        play_class_and_score = min(enabled_plays_and_scores, key=lambda tup: tup[1])

                        # run the play with the lowest score, as long as it isn't inf
                        if play_class_and_score[1] != float("inf"):
                            play_class = play_class_and_score[0]
                            self.play = play_class() # instantiate it
                    else:
                        # there's no available plays to run
                        pass
                except Exception as e:
                    logging.error("Exception occurred during play selection: " + str(e))
                    traceback.print_exc()
                if self.play != None:
                    logging.info("Chose new play: '" + self.play.__class__.__name__ + "'")


        # Role Assignment
        ################################################################################
        try:
            assignments = role_assignment.assign_roles(self.robots, self.role_requirements())
        except role_assignment.ImpossibleAssignmentError as e:
            logging.error("Unable to satisfy role assignment constraints.  Dropping and temp. blacklisting current play...")
            self.drop_current_play(temporarily_blacklist=True)
        else:
            self.assign_roles(assignments)
 def score(cls):
     if main.game_state().is_playing():
         return 9
     return float("inf")
Пример #34
0
 def score(cls):
     return 0 if main.game_state().is_stopped() else float("inf")
Пример #35
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_ready_state() and (
         gs.is_their_free_kick() or gs.is_their_indirect()
         or gs.is_their_direct()) else float("inf")
Пример #36
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_our_placement() else float("inf")
Пример #37
0
    def __init__(self):
        super().__init__(continuous=True)

        for substate in Goalie.State:
            self.add_state(substate, behavior.Behavior.State.running)

        self.add_transition(behavior.Behavior.State.start, Goalie.State.chill,
                            lambda: True, "immediately")

        self.add_transition(Goalie.State.chill, Goalie.State.defend,
                            lambda: main.ball().valid, "ball is valid")

        non_chill_states = [s for s in Goalie.State if s != Goalie.State.chill]

        # if ball is invalid, chill
        for state in non_chill_states:
            self.add_transition(state, Goalie.State.chill,
                                lambda: not main.ball().valid,
                                "ball is invalid")

        for state in non_chill_states:
            self.add_transition(
                state, Goalie.State.setup_penalty, lambda: main.game_state(
                ).is_their_penalty() and main.game_state().is_setup_state(),
                "setting up for opponent penalty")

        for state in [
                s2 for s2 in non_chill_states if s2 != Goalie.State.intercept
        ]:
            self.add_transition(
                state, Goalie.State.intercept,
                lambda: evaluation.ball.is_moving_towards_our_goal(
                ) and not self.robot_is_facing_our_goal(evaluation.ball.
                                                        opponent_with_ball()),
                "ball coming towards our goal")

        for state in [
                s2 for s2 in non_chill_states if s2 != Goalie.State.clear
        ]:
            self.add_transition(
                state, Goalie.State.clear,
                lambda: evaluation.ball.is_in_our_goalie_zone(
                ) and not main.game_state().is_their_penalty(
                ) and not evaluation.ball.is_moving_towards_our_goal(
                ) and evaluation.ball.opponent_with_ball() is None,
                "ball in our goalie box, but not headed toward goal")

        for state in [
                s2 for s2 in non_chill_states if s2 != Goalie.State.defend
        ]:
            self.add_transition(
                state, Goalie.State.defend,
                lambda: not evaluation.ball.is_in_our_goalie_zone(
                ) and not evaluation.ball.is_moving_towards_our_goal(
                ) and not main.game_state().is_their_penalty() and not self.
                robot_is_facing_our_goal(evaluation.ball.opponent_with_ball()),
                'not much going on')

        for state in [
                s2 for s2 in non_chill_states if s2 != Goalie.State.block
        ]:
            self.add_transition(
                state, Goalie.State.block,
                lambda: not evaluation.ball.is_in_our_goalie_zone() and
                not evaluation.ball.is_moving_towards_our_goal() and self.
                robot_is_facing_our_goal(evaluation.ball.opponent_with_ball()),
                "opponents have possession")
Пример #38
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_our_kickoff() else float("inf")
Пример #39
0
 def on_enter_dribble(self):
     dribble = skills.dribble.Dribble(
         main.game_state().get_ball_placement_point())
     self.add_subbehavior(dribble, 'dribble', required=True, priority=100)
Пример #40
0
 def score(cls):
     gs = main.game_state()
     return 0 if (gs.is_ready_state() and gs.is_our_direct() and
                  main.ball().pos.y < 1.0) else float("inf")
Пример #41
0
 def score(cls):
     gs = main.game_state()
     return 0 if (gs.is_ready_state() and gs.is_our_direct() and main.ball().pos.y < 1.0) else float("inf")
Пример #42
0
 def score(cls):
     gs = main.game_state()
     if ((gs.is_setup_state() or not main.game_state().is_playing()) and
             gs.is_their_kickoff()):
         return 0
     return float("inf")
Пример #43
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_ready_state() and ( gs.is_their_free_kick() or gs.is_their_indirect() or gs.is_their_direct()) else float("inf")
Пример #44
0
 def score(cls):
     if (not main.game_state().is_playing()):
         return float("inf")
     if len(main.our_robots()) < 5:
         return float("inf")
     return 10
Пример #45
0
 def score(cls):
     gs = main.game_state()
     #This play does not work well against functional opponent robots, maybe add
     #"and len(main.system_state().their_robots)==0" or some kind of check for nonmoving opponents?
     return 1 if gs.is_playing() else float("inf")
Пример #46
0
 def score(cls):
     gs = main.game_state()
     return 0 if behavior.Behavior.State.running or (
         gs.is_ready_state()
         and gs.is_our_indirect_kick()) else float("inf")
Пример #47
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_their_penalty() and gs.is_setup_state() else float(
         "inf")
Пример #48
0
 def on_enter_reset(self):
     self._pos = main.game_state().get_ball_placement_point()
     self._our_restart = main.game_state().is_our_restart()
Пример #49
0
    def execute_running(self):
        # update double touch tracker
        evaluation.double_touch.tracker().spin()

        # cache and calculate the score() function for each play class
        main.play_registry().recalculate_scores()

        # Play Selection
        ################################################################################

        if main.game_state().is_stopped():
            evaluation.double_touch.tracker().restart()
            if main.game_state().is_placement():
                if not isinstance(self.play,
                                  plays.restarts.placement.Placement):
                    logging.info("Placing Ball")
                    self.play = plays.restarts.placement.Placement()
                    self._currently_restarting = True
            else:
                if self.play is None or not self.play.run_during_stopped():
                    logging.info(
                        "Running 'Stopped' play due to game state change")
                    self.play = plays.stopped.Stopped()
                    self._currently_restarting = True
        elif main.game_state().is_halted():
            evaluation.double_touch.tracker().restart()
            self.play = None
        else:
            # (play_class, score value) tuples
            enabled_plays_and_scores = [
                p for p in main.play_registry().get_enabled_plays_and_scores()
            ]

            # only let restart play run once
            enabled_plays_and_scores = [
                p for p in enabled_plays_and_scores
                if not p[0].is_restart() or (
                    p[0].is_restart() and self._currently_restarting)
            ]

            # handle temporary blacklisting
            # we remove the blacklisted play class from selection for this iteration, then unblacklist it
            enabled_plays_and_scores = [
                p for p in enabled_plays_and_scores
                if p[0] != self.temporarily_blacklisted_play_class
            ]
            self.temporarily_blacklisted_play_class = None

            # see if we need to kill current play or if it's done running
            if self.play is not None:
                if self.play.__class__ not in map(lambda tup: tup[0],
                                                  enabled_plays_and_scores):
                    logging.info("Current play '" +
                                 self.play.__class__.__name__ +
                                 "' no longer enabled, aborting")
                    self.play.terminate()
                    self.play = None
                elif self.play.is_done_running():
                    logging.info("Current play '" +
                                 self.play.__class__.__name__ +
                                 "' finished running")
                    if self.play.is_restart:
                        self._currently_restarting = False
                    self.play = None
                elif self.play.__class__.score() == float("inf"):
                    logging.info("Current play '" +
                                 self.play.__class__.__name__ +
                                 "' no longer applicable, ending")
                    self.play.terminate()
                    self.play = None

            if self.play is None:
                try:
                    if len(enabled_plays_and_scores) > 0:
                        # select the play with the smallest value for score()
                        play_class_and_score = min(enabled_plays_and_scores,
                                                   key=lambda tup: tup[1])

                        # run the play with the lowest score, as long as it isn't inf
                        if play_class_and_score[1] != float("inf"):
                            play_class = play_class_and_score[0]
                            self.play = play_class()  # instantiate it
                    else:
                        # there's no available plays to run
                        pass
                except Exception as e:
                    logging.error(
                        "Exception occurred during play selection: " + str(e))
                    traceback.print_exc()
                if self.play is not None:
                    logging.info("Chose new play: '" +
                                 self.play.__class__.__name__ + "'")

        # Role Assignment
        ################################################################################
        try:
            assignments = role_assignment.assign_roles(
                self.robots, self.role_requirements())
        except role_assignment.ImpossibleAssignmentError as e:
            logging.error(
                "Unable to satisfy role assignment constraints.  Dropping and temp. blacklisting current play..."
            )
            self.drop_current_play(temporarily_blacklist=True)
        else:
            self.assign_roles(assignments)
Пример #50
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_our_placement() else float("inf")
Пример #51
0
 def score(cls):
     return 10 if main.game_state().is_playing() else float("inf")
Пример #52
0
 def score(cls):
     gs = main.game_state()
     return 0 if gs.is_ready_state() and gs.is_our_free_kick() else float(
         "inf")