Ejemplo n.º 1
0
 def __init__(self, parent, friendly, rate=RATE, player_id=None):
     multiplier = 1 if friendly else -1
     self.friendly = friendly
     self.player_id = player_id
     if self.friendly:
         from server.engine import Engine
         super().__init__([Point(parent.point.x, parent.point.y), Point(parent.point.x, parent.point.y + 5000 * multiplier)], Engine.CURRENT_SPEED + rate, Lazer.RADIUS)
     else:
         super().__init__(
             [Point(parent.point.x, parent.point.y), Point(parent.point.x, parent.point.y + 5000 * multiplier)],
             rate, Lazer.RADIUS)
Ejemplo n.º 2
0
    def buildVehicle(self, perception):
        self.vehicle.set_position(
            Waypoint(self.car.center[0], self.car.center[1]))
        self.vehicle.set_heading(self.car.pose)
        self.vehicle.set_speed(self.car.speed)
        lanes = perception["lane_center"]

        if len(lanes[0]) > 1:
            # self.vehicle.set_lanes(lanes[0][0], lanes[0][1], lanes[1][0], lanes[1][1])
            # lanes[r/l][n][x/y]
            # self.vehicle.set_lanes(lanes[1][0][0], lanes[1][0][1], lanes[1][1][0], lanes[1][1][1])
            right = Point(lanes[0][0][0], lanes[0][0][1])
            right_ahead = Point(lanes[0][1][0], lanes[0][1][1])
        else:
            right = Point(0, 0)
            right_ahead = Point(0, 0)

        if len(lanes[1]) > 1:
            left = Point(lanes[1][0][0], lanes[1][0][1])
            left_ahead = Point(lanes[1][1][0], lanes[1][1][1])
        else:
            left = Point(0, 0)
            left_ahead = Point(0, 0)

        self.vehicle.set_lanes(Lanes(right, right_ahead, left, left_ahead))

        self.vehicle.set_obstacles([])
        return self.vehicle
Ejemplo n.º 3
0
def convex_hull(
    points: List[Union[Tuple[float, float], List[float],
                       Point]]) -> List[Point]:
    """For given list of points return its convex hull"""
    _at = (tuple, list, Point)  # allowed types
    points = [Point.from_iter(i) for i in points
              if type(i) in _at]  # converts to points

    points.sort(key=lambda p: p.x)  # sort points by x axis
    l_upper = [points[0], points[1]]  # add two leftmost points to L(upper) set

    for i in range(2, len(points)):  # for all other points
        l_upper.append(points[i])  # add the next point to L set

        # test the last three points in L
        while len(l_upper) > 2 and not _is_right_turn(l_upper[-3], l_upper[-2],
                                                      l_upper[-1]):
            # remove the middle of tested three points when they don't make right turn
            l_upper.pop(-2)

    l_lower = [points[-1],
               points[-2]]  # L(lower) begins with the two rightmost points
    # apply the same algorithm for reversed values
    for i in reversed(range(len(points) - 3)):
        l_lower.append(points[i])
        while len(l_lower) > 2 and not _is_right_turn(l_lower[-3], l_lower[-2],
                                                      l_lower[-1]):
            l_lower.pop(-2)

    # remove the first from lower L as it is the same as the last in the upper L
    # append lower to upper L
    return l_upper + l_lower[1:]
Ejemplo n.º 4
0
def find_intersections_slow(line_segments: List[LineSegment]) -> List[Point]:
    result = set()
    for i in range(len(line_segments)):
        for ls in line_segments[i + 1:]:
            intersection = LineSegment.intersection(ls, line_segments[i])
            if intersection:
                result.add((intersection.x, intersection.y))
    return [Point.from_iter(i) for i in result]
    def run(self):
        rospy.init_node('mission_planner')
        rate = rospy.Rate(10)  # 10hz

        mission_msg = MissionMsg()

        start = Point(19.25, 32.50)
        goal = Point(94.500, 61.750)
        self.path_to_goal(start, goal)

        while not rospy.is_shutdown():
            self.vehicle.mission.update(self.vehicle)

            mission_msg.waypoints = self.vehicle.mission.waypoints
            mission_msg.current = self.vehicle.mission.current

            self.mission_pub.publish(mission_msg)

            rate.sleep()
Ejemplo n.º 6
0
 def intersection(l1, l2) -> Optional[Point]:
     p1, p2 = l1.endpoints
     p3, p4 = l2.endpoints
     t = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x)
     if t == 0:
         return None
     x = (p1.x * p2.y - p1.y * p2.x) * (p3.x - p4.x) - (p1.x - p2.x) * (p3.x * p4.y - p3.y * p4.x)
     y = (p1.x * p2.y - p1.y * p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x * p4.y - p3.y * p4.x)
     p = Point(x / t, y / t)
     if p in l1 and p in l2:
         return p
Ejemplo n.º 7
0
 def __init__(self, players=2):
     self.center = Point(Engine.WIDTH / 2, Engine.HEIGHT / 2)
     self.player_ships = [
         PlayerShip(
             x,
             Point(Engine.WIDTH / (players + 1) * (x + 1),
                   PlayerShip.RADIUS * 1.5)) for x in range(players)
     ]
     self.scores = [0 for _ in range(players)]
     self.friendly_objects = []
     self.enemy_objects = []
     Engine.CURRENT_SPEED = Engine.SPEED
     from objects.spawners.enemy_ship_spawner import EnemyShipSpawner
     from objects.spawners.ufo_spawner import UfoSpawner
     from objects.spawners.asteroid_spawner import AsteroidSpawner
     self.spawners = [
         AsteroidSpawner(75, 0, 0.02),
         UfoSpawner(90, 0, 0.02),
         EnemyShipSpawner(100, 0, 0.02)
     ]
Ejemplo n.º 8
0
def generate_rand_data(num_points: int, range_x: float=1, range_y: float=1):
    """
    Generate random `Point` object assets with x and y range

    :param num_points: number of points in dataset
    :param range_x: range of x values
    :param range_y: range of y values
    :return: list of randomly generate Point objects
    """
    point_list = []
    for i in range(num_points):
        point_list.append(Point(random.random() * range_x,
                                random.random() * range_y))
    return point_list
Ejemplo n.º 9
0
def generate_centroids(num_centroids: int, point_list: list, precision: int=3):
    """
    Randomly generate centroids within the bounds of dataset

    :param num_centroids: number of centroids required
    :param point_list: list of Point objects
    :param precision: number of decimal places of precision on location of centroids
    :return: list of randomly generated centroids
    """
    precision = 10 ** precision
    centroid_list = []
    x_vals = [i.x for i in point_list]
    y_vals = [i.y for i in point_list]
    x_max, x_min = max(x_vals), min(x_vals)
    y_max, y_min = max(y_vals), min(y_vals)
    for i in range(num_centroids):
        centroid = Point(random.randrange(int(precision * x_min), int(precision * x_max)) / precision,
                         random.randrange(int(precision * y_min), int(precision * y_max)) / precision)
        centroid.is_centroid = True
        centroid.cluster_id = i
        centroid_list.append(centroid)
        point_list.append(centroid)
    new_centroid_list = check_centroids(centroid_list=centroid_list, point_list=point_list, precision=3)
    return new_centroid_list
Ejemplo n.º 10
0
def generate_data(file_path: str, headers: bool=True):
    """
    Generate `Point` object assets imported from values from 2D csv file

    :param file_path: path of csv file
    :param headers: set to True if csv file has headers
    :return: list of generated Point objects
    """
    point_list = []
    with open(file_path, 'r') as csvfile:
        data = csv.reader(csvfile, delimiter=',')
        if headers:
            next(data, None)
        for row in data:
            point_list.append(Point(float(row[0]), float(row[1])))
    return point_list
Ejemplo n.º 11
0
    def update(self):
        Engine.CURRENT_SPEED = (
            (self.center.y // Engine.HEIGHT) + 1) * Engine.SPEED
        self.center = self.center + Point(0, Engine.CURRENT_SPEED)

        self.update_object_set(self.friendly_objects)
        self.update_object_set(self.enemy_objects)

        for ship in self.player_ships:
            ship.update()
            ship.point.x = max(
                self.center.x - Engine.WIDTH / 2,
                min(ship.point.x, self.center.x + Engine.WIDTH / 2))
            ship.point.y = max(
                self.center.y - Engine.HEIGHT / 2,
                min(ship.point.y, self.center.y + Engine.HEIGHT / 2))

        for enemy in self.enemy_objects:
            if enemy.point.y < self.center.y - Engine.HEIGHT:
                enemy.hit()
            if isinstance(
                    enemy, Lazer
            ) and enemy.point.y > self.center.y + Engine.HEIGHT / 2 + enemy.radius:
                enemy.hit()

        for friendly in self.friendly_objects:
            if isinstance(
                    friendly, Lazer
            ) and friendly.point.y > self.center.y + Engine.HEIGHT / 2 + friendly.radius:
                friendly.hit()

        for friendly in self.friendly_objects + self.player_ships:
            for enemy in self.enemy_objects:
                if friendly.died:
                    break
                if enemy.died:
                    continue
                if friendly.intersects(enemy):
                    if isinstance(
                            friendly, PlayerShip
                    ) and friendly.invulnerability_frames_left > 0:
                        continue
                    if isinstance(friendly, Lazer) and isinstance(
                            enemy, Lazer):
                        continue
                    self.check_score_change(friendly, enemy)
                    friendly.hit()
                    result = enemy.hit()
                    if result:
                        if isinstance(result, list):
                            self.enemy_objects += result
                        else:
                            self.enemy_objects.append(result)

        self.friendly_objects = [
            friendly for friendly in self.friendly_objects if not friendly.died
        ]
        self.enemy_objects = [
            enemy for enemy in self.enemy_objects if not enemy.died
        ]

        lives = []
        scores = []
        all_ded = True

        for x in range(len(self.player_ships)):
            if not self.player_ships[x].died:
                self.scores[x] += Engine.SECOND_POINTS
                all_ded = False
            lives.append(self.player_ships[x].lives)
            scores.append(self.scores[x])

        if all_ded:
            print(all_ded, lives, scores)
            return [], [], []

        for spawner in self.spawners:
            result = spawner.update(deepcopy(self.center))
            if result:
                if isinstance(result, list):
                    self.enemy_objects += result
                else:
                    self.enemy_objects.append(result)

        object_list = []
        for entity in self.player_ships + self.friendly_objects + self.enemy_objects:
            obj = [
                int(entity.point.x - entity.radius / 2 -
                    (self.center.x - Engine.WIDTH / 2)),
                Engine.HEIGHT - int(entity.point.y + entity.radius / 2 -
                                    (self.center.y - Engine.HEIGHT / 2))
            ]
            if isinstance(entity, PlayerShip):
                if entity.died:
                    obj.append('')
                elif entity.invulnerability_frames_left > 0 and (
                        entity.invulnerability_frames_left // 3) % 2 == 0:
                    obj.append('')
                else:
                    obj.append('ship')
            elif isinstance(entity, Lazer):
                if entity.friendly:
                    obj.append('redlazer')
                else:
                    obj.append('greenlazer')
            elif isinstance(entity, Asteroid):
                obj.append('bigasteroid')
            elif isinstance(entity, Rock):
                obj.append('smallasteroid')
            elif isinstance(entity, EnemyShip):
                if entity.autofire_rate is None:
                    obj.append('ufo')
                else:
                    obj.append('enemyship')
            else:
                print(str(type(entity)))
                obj.append('')
            object_list.append(obj)
        return object_list, lives, scores
Ejemplo n.º 12
0
 def move(self, xx, yy):
     self.point = self.point + Point(xx, yy)
Ejemplo n.º 13
0
def _rot90ccw(ls: LineSegment) -> LineSegment:
    """Rotate line segment counter clockwise"""
    p1, p2 = ls.endpoints
    return LineSegment([Point(-p1.y, p1.x), Point(-p2.y, p2.x)])
Ejemplo n.º 14
0
def random_point(_r):
    return Point(random() * _r - _r / 2, random() * _r - _r / 2)
Ejemplo n.º 15
0
import random
from copy import deepcopy

from objects.asteroid import Asteroid
from objects.enemy_ship import EnemyShip
from objects.point import Point
from objects.set_path_object import SetPathObject
from server.engine import Engine

eight = [
    Point(-Engine.WIDTH / 2 + 100, Engine.HEIGHT - 100),
    Point(Engine.WIDTH / 2 - 100, Engine.HEIGHT + 100),
    Point(Engine.WIDTH / 2 - 100, Engine.HEIGHT - 100),
    Point(-Engine.WIDTH / 2 + 100, Engine.HEIGHT + 100)
]

reverse_eight = eight[::-1]

vertical_asteroid = Asteroid(
    [Point(0, Engine.HEIGHT),
     Point(0, -Engine.HEIGHT)])
diagonal_asteroid = Asteroid(
    [Point(0, Engine.HEIGHT),
     Point(0, -Engine.HEIGHT)])
ufo_horizontal = EnemyShip([
    Point(-Engine.WIDTH / 2 + 100, Engine.HEIGHT),
    Point(Engine.WIDTH / 2 - 100, Engine.HEIGHT)
])
enemy_ship_eight = EnemyShip(eight, autofire_rate=60)
enemy_ship_reversed_eight = EnemyShip(reverse_eight, autofire_rate=60)
Ejemplo n.º 16
0
    def press(self, widget, event):
        """
        This code is executed when you press the mouse button
        """
        self.emit("focus", gtk.DIR_TAB_FORWARD)

        x = event.x / self.zoom
        y = event.y / self.zoom

        def start_resize(child):
            self.unselect_all()
            child.selected = True
            child.resizing = True
            if child.direction < ANONIMOUS:
                control = child.handler.control[opposite(child.direction)]
                child.pivot.x = self.grid.nearest(control.x)
                child.pivot.y = self.grid.nearest(control.y)
                child.pivot = self.guides.nearest(child.pivot)
                child.handler.pivot.x = control.x
                child.handler.pivot.y = control.y
                child.handler.pivot.active = True

        if self.pick:
            self.unselect_all()
            #x, y = self.get_pointer()
            target = Point()
            child = self.child
            self.add(child)
            child.selected = True
            target.x = self.grid.nearest(x)
            target.y = self.grid.nearest(y)
            target = self.guides.nearest(target)
            child.x = target.x
            child.y = target.y
            child.width = 0
            child.height = 0
            child.direction = SOUTHEAST
            child.handler.control[opposite(child.direction)].y = child.y
            child.handler.control[opposite(child.direction)].x = child.x
            start_resize(child)
            widget.bin_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.BOTTOM_RIGHT_CORNER))
            self.emit("select", child)
            return True

        selection = True

        def start_move(child, x, y):
            child.offset.x = x - child.x
            child.offset.y = y - child.y
            child.press(x, y)

        def select(child):
            if not event.state & gtk.gdk.CONTROL_MASK:
                self.unselect_all()
            child.selected = True

        for child in sorted(self.document.pages[0].children, key=lambda child: child.z):
            if child.selected:
                if child.handler.at_position(x, y):
                    child.direction = child.handler.get_direction(x, y)
                    selection = False
                    start_resize(child)
                elif child.at_position(x, y):
                    #start_move(child, x, y)
                    start_move(child, x, y)
                    selection = False
                else:
                    continue
            elif child.at_position(x, y):
                selection = False
                select(child)
                start_move(child, x, y)
            else:
                continue

        if selection:
            self.selection.x = x
            self.selection.y = y
            self.selection.width = 0
            self.selection.height = 0
            self.selection.active = True
            widget.bin_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.CROSSHAIR))
        else:
            self.stop_cursor_change = True
            #self.updated = False
        self.update() # XXX

        return True
Ejemplo n.º 17
0
    def motion(self, widget, event):
        """
        This code is executed when move the mouse pointer
        """
        self.statics.motion += 1
        #self.consume(Gdk.MOTION_NOTIFY, event.get_state())
        self.disconnect(self.motion_id)
        if self.horizontal_ruler:
            self.horizontal_ruler.motion(self.horizontal_ruler, event, True)
        if self.vertical_ruler:
            self.vertical_ruler.motion(self.vertical_ruler, event, True)
        x = event.x / self.zoom
        y = event.y / self.zoom

        if not self.stop_cursor_change:
            def get_direction_for_child_at_position(x, y, children):
                for child in children:
                    if child.selected and child.handler.at_position(x, y):
                        direction = child.handler.get_direction(x, y)
                        #widget.bin_window.set_cursor(child.get_cursor(direction))
                        widget.get_window().set_cursor(child.get_cursor(direction))
                        return direction
                return NONE

            direction = get_direction_for_child_at_position(x, y, self.document.pages[0].children)

            if direction == NONE:
                if self.pick:
                    #widget.bin_window.set_cursor(Gdk.Cursor.new(Gdk.PENCIL))
                    widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.PENCIL))
                else:
                    #widget.bin_window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.ARROW))
                    widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.ARROW))

        if self.selection.active:
            self.selection.width = x - self.selection.x
            self.selection.height = y - self.selection.y
            self.updated = False
            self.update() # XXX
        elif event.get_state() & Gdk.ModifierType.BUTTON1_MASK:
            for child in self.document.pages[0].children: # TODO
                if child.selected:
                    target = Point()
                    if child.resizing:
                        target.x = self.grid.nearest(x)
                        target.y = self.grid.nearest(y)
                        target = self.guides.nearest(target)
                        if child.direction < ANONIMOUS:
                            child.resize(target.x, target.y)
                        else:
                            child.transform(target.x, target.y)
                    else:
                        #widget.bin_window.set_cursor(Gdk.Cursor.new(Gdk.FLEUR))
                        widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.FLEUR))
                        target.x = self.grid.nearest(x - child.offset.x)
                        target.y = self.grid.nearest(y - child.offset.y)
                        target = self.guides.nearest(target)
                        # XXX-TEST
                        if self.is_testing:
                            def magnetize(target, children):
                                for child in children:
                                    if not child.selected and child.magnetos.is_magnetized(target):
                                        return child.magnetos.get_magnetized(target)
                                return target

                            target = magnetize(target, self.document.pages[0].children)
                        # XXX-TEST
                        child.move(target.x, target.y)
                    self.emit("edit-child", child)
                    self.update()
        self.motion_id = self.connect("motion-notify-event", self.motion)
        return True
Ejemplo n.º 18
0
 def __contains__(self, point: Point):
     return point.is_between(*self.endpoints)
Ejemplo n.º 19
0
    def setinput(self):
        pressed = pygame.key.get_pressed()

        view = self.perception.look()
        self.vehicle = self.buildVehicle(view)

        # Mission
        # if not self.vehicle.mission.exists():
        #     self.setVehicleMission()
        #     mission_msg = MissionMsg()
        #     for wayp in self.vehicle.mission.waypoints:
        #         wpm = WaypointMsg()
        #         wpm.x = wayp.x
        #         wpm.y = wayp.y
        #         wpm.type = wayp.type
        #         wpm.speed_limit = wayp.speed_limit
        #         mission_msg.waypoints.append(wpm)
        #     self.pub_mission.publish(mission_msg)

        # Pose
        pose_msg = PoseMsg()
        pose_msg.x = self.vehicle.pose.x
        pose_msg.y = self.map.transform_y_back(self.vehicle.pose.y)
        pose_msg.heading = -self.vehicle.pose.heading
        pose_msg.speed = self.vehicle.pose.speed
        self.pub_pose.publish(pose_msg)

        # Lanes
        lanes_msg = LanesMsg()
        right = Point()
        right_ahead = Point()
        left = Point()
        left_ahead = Point()

        if self.vehicle.lanes.are_visible():
            right.x = self.vehicle.lanes.right.x
            right.y = self.map.transform_y_back(self.vehicle.lanes.right.y)
            left.x = self.vehicle.lanes.left.x
            left.y = self.map.transform_y_back(self.vehicle.lanes.left.y)

            right_ahead.x = self.vehicle.lanes.right_ahead.x
            right_ahead.y = self.map.transform_y_back(
                self.vehicle.lanes.right_ahead.y)
            left_ahead.x = self.vehicle.lanes.left_ahead.x
            left_ahead.y = self.map.transform_y_back(
                self.vehicle.lanes.left_ahead.y)

        lanes_msg.right = right
        lanes_msg.left = left
        lanes_msg.right_ahead = right_ahead
        lanes_msg.left_ahead = left_ahead

        lanes_msg.right.z = 0
        lanes_msg.left.z = 0
        lanes_msg.right_ahead.z = 0
        lanes_msg.left_ahead.z = 0

        self.pub_lanes.publish(lanes_msg)

        if not pressed[K_q]:
            # autonomous player
            # build modified target (for path tracker)
            target = Target()
            target.speed_limit = self.vehicle.target.speed_limit
            target.start.x = self.vehicle.target.start.x
            target.start.y = self.map.transform_y_back(
                self.vehicle.target.start.y)
            target.start.heading = self.vehicle.target.start.heading
            target.start.speed = self.vehicle.target.start.speed
            target.end.x = self.vehicle.target.end.x
            target.end.y = self.map.transform_y_back(self.vehicle.target.end.y)
            target.end.heading = self.vehicle.target.end.heading
            target.end.speed = self.vehicle.target.end.speed

            # set local reference frame for trajectory
            # all angles constrained in [-pi/pi]
            wp_traversed = self.has_changed(target)

            if not self.frame or wp_traversed:
                # Harrit has y as car longitudinal axis
                car_heading = math.atan2(math.sin(self.car.pose + math.pi / 2),
                                         math.cos(self.car.pose + math.pi / 2))
                self.frame = Frame(target.start.x, target.start.y, car_heading)
                print "new frame:", target.start.x, target.start.y, target.end.x, target.end.y, self.car.center[
                    0], self.car.center[1], car_heading * 180 / math.pi

            # convert to local frame
            current_wp_x, current_wp_y = self.frame.global2local(
                target.start.x, target.start.y)
            next_wp_x, next_wp_y = self.frame.global2local(
                target.end.x, target.end.y)
            car_x, car_y = self.frame.global2local(self.car.center[0],
                                                   self.car.center[1])

            if (current_wp_x, current_wp_y) != (
                    next_wp_x,
                    next_wp_y) and target.start.x and target.start.y:
                target_heading = -target.end.heading - self.frame.angle  # Compensate for clockwise angle
                target_heading = math.atan2(
                    math.sin(target_heading),
                    math.cos(target_heading))  # Between [-pi, pi]
                target_heading = target_heading if target_heading > 0 else 2 * pi - target_heading  # Between [0, 2*pi]
                inst_heading = -self.car.pose - self.frame.angle  # Compensate for clockwise angle
                inst_heading = math.atan2(
                    math.sin(inst_heading),
                    math.cos(inst_heading))  # Between [-pi, pi]
                inst_heading = inst_heading if inst_heading > 0 else 2 * pi - inst_heading  # Between [0, 2*pi]

                print "cwx: ", current_wp_x, "cwy:", current_wp_y, "nwx:", next_wp_x, "nwy:", next_wp_y, 5, 5, \
                    "cx:", car_x, "cy:", car_y, "s:", self.car.speed, "th: {0:.2f}".format(
                    target_heading*180/math.pi), "ih: {0:.2f}".format(
                    inst_heading*180/math.pi), "trv:", wp_traversed

                trajectory = self.planner.trajectory_planner(
                    current_wp_x=current_wp_x,
                    current_wp_y=current_wp_y,
                    next_wp_x=next_wp_x,
                    next_wp_y=next_wp_y,
                    current_wp_v=target.start.speed,
                    next_wp_v=target.end.speed,
                    # current_wp_v=5, next_wp_v=5,
                    current_x=car_x,
                    current_y=car_y,
                    inst_v=self.car.speed,
                    heading=target_heading,
                    inst_heading=inst_heading,
                    wp_traversed=wp_traversed)
                print trajectory
                # Trajectory is empty, should recompute
                if len(trajectory[0]) < 2:
                    print "Empty trajectory, mission failed!"
                    self.tracker.setTarget(target)
                    return

                global_traj = [[0 for x in range(len(trajectory[0]))]
                               for y in range(2)]
                for i in xrange(0, len(trajectory[0])):
                    (tx, ty) = self.frame.local2global(trajectory[0][i],
                                                       trajectory[1][i])
                    global_traj[0][i] = tx
                    global_traj[1][i] = ty

                # if len(global_traj[0]) > 0:
                #     idx = int(min(len(global_traj[0]) - 1, max(10 * self.car.speed, 20)))
                #     target.end.x = global_traj[0][idx]
                #     target.end.y = global_traj[1][idx]

                input = self.tracker.getInput(target, global_traj)
                self.car.acc = input['acc']
                self.car.steer = input['steer']

                # Lateral error too large, should recompute
                if input['error']:
                    print "Lateral error too large, mission failed!"
                    return
        else:
            # human player
            if pressed[K_LEFT]:
                self.car.steer += -radians(4)
            elif pressed[K_RIGHT]:
                self.car.steer += radians(4)
            else:
                self.car.steer = 0

            if pressed[K_UP]:
                self.car.acc += 1
            elif pressed[K_DOWN]:
                self.car.acc += -1
            else:
                self.car.acc = 0
Ejemplo n.º 20
0
def random_point(_r):
    return Point(random() * _r - _r / 2, random() * _r - _r / 2)


def randint_point(_r):
    return Point(randint(-_r, _r), randint(-_r, _r))


legend = True
plot_process = True
r = 4  # range from -r to r
n = 20  # number of random segments

# test line segments
line_segments = [
    LineSegment([Point(1, 5), Point(2, 3)]),
    LineSegment([Point(3, 4), Point(2, 2)]),
    LineSegment([Point(2, 4), Point(3, 2)]),
    LineSegment([Point(3, 6), Point(3, 4)]),
    LineSegment([Point(2, 4), Point(1, 1)])
]

# failed tests
# line_segments = [
#     LineSegment([Point(-0.479532, 0.479277), Point(0.0329766, -0.320124)]),
#     LineSegment([Point(-0.419874, 0.323043), Point(-0.0474568, 0.0768236)]),
#     LineSegment([Point(-0.14408, 0.165792), Point(-0.0238416, -0.40193)]),
#     LineSegment([Point(-0.0428549, 0.144741), Point(0.329162, 0.0863071)]),
#     LineSegment([Point(0.444422, 0.119511), Point(-0.215631, -0.0739168)]),
#     LineSegment([Point(0.0722771, 0.0903832), Point(0.319375, -0.308218)]),
# ]
Ejemplo n.º 21
0
def randint_point(_r):
    return Point(randint(-_r, _r), randint(-_r, _r))
Ejemplo n.º 22
0
 def __init__(self, endpoints: List[Point] = None, start: Point = Point(), end: Point = Point()):
     if endpoints:  # two points given in a list
         self.endpoints = sorted(endpoints[:2])
     else:  # given start and end point
         self.endpoints = sorted([start, end])
Ejemplo n.º 23
0
    def read(self, fptr):
        '''
        Difficulty 3

        Some function that reads in a file, and generates the internal board.

        **Parameters**

            fptr: *str*
                The file name of the input board to solve.

        **Returns**

            None
        '''

        #open and read lines of file
        file_read=open(fptr,"r") 
        lines=file_read.readlines()

        #edit the read text so as to get rid of blank lines and lines with a #
        while '\n' in lines:
            lines.remove('\n')
        for line in list(lines):
            if line[0] == '#':
                lines.remove(line)

        #find the start and end indeces for the board grid
        start=lines.index("GRID START\n")+1
        end=lines.index("GRID STOP\n")
        board_int=lines[start:end] #the board grid from the txt file

        #create a modified board grid, without any spaces
        new=[]
        for i in range(0, len(board_int)):
            current_line=board_int[i].split()
            new.append(current_line)

        #find size of board
        x=len(new[0]) #columns
        y=len(new) #rows

        #update size to include spaces for box boundaries
        width=2*x+1
        length=2*y+1

        #create the empty board (w/ "None")
        board_int_upd=[ [ None for col in range( width ) ] for row in range( length ) ]

        #add the actual blocks to the new empty board matrix. keep "None" at the block boundaries. 
        for i in range(0, y):
            for j in range(0,x):
                board_int_upd[2*i+1][j*2+1]=new[i][j]

        #parse thorugh the lines to find the beginning of the blocks paragraph, the lasers, and the points. 
        p=0 #initialize p and l to be zero to show that we have not yet found the point and laser lines. 
        l=0
        b=0
        line_numb=0 #initialize the line number

        for line in lines:
            if line[0]==('A') or  line[0]=='B' or line[0]=='C' and b is 0: #a line that shows blocks
                    blocks_start=line_numb-1
                    blocks_end=blocks_start
                    b=1 #marks the first occurence
            if line[0] is "L" and l is 0: #the line that shows laser
                laser_start=line_numb
                l=1 #marks the first occurence
            if line[0] is "P" and p is 0:
                point_start=line_numb
                p=1 #marks the first occurence
            line_numb+=1

        #BLOCKS PARAGRAPH
        #organize the blocks into a list of letters, whose qty = the # of that type of block
        blocks_end=laser_start-1 #blocks info ends where laser info begins
        blocks_values=[] 
        for j in range(blocks_start+1, blocks_end+1):
            blocks_values.append(lines[j][0])
            blocks_values.append(lines[j][2])
        blocks_list=[]
        #print(blocks_values)
        for index in range(1, len(blocks_values), 2):
            f=int(blocks_values[index])
            for index2 in range(1, f+1):
                blocks_list.append(blocks_values[index-1])

        #LASER
        #organize laser into list of objects
        laser_end=point_start-1 #laser ends where points info starts
        lsr=[]
        for i in range(laser_start, laser_end+1):
            line=lines[i].split()
            position=(int(line[1]), int(line[2]))
            #print(position)
            direction=(int(line[3]), int(line[4]))
            lsr.append(Laser(position, direction))

        #POINTS
        #organize pts into list of objects
        pts=[]
        for i in range(point_start, len(lines)):
            line1=lines[i].split()
            if line1[0]=='P':
                position=(int(line1[1]), int(line1[2]))
                #print(position)
            pts.append(Point(position, 0))

        #close the file
        file_read.close()

        #assign the important objects/lists to the game object 
        self.blocks=blocks_list
        self.emptyboard=board_int_upd
        self.points=pts
        self.lasers=lsr

        pass
Ejemplo n.º 24
0
 def length(self) -> float:
     return Point.distance(*self.endpoints)
Ejemplo n.º 25
0
def sweep_line(x1, x2, y):
    return LineSegment([Point(x1, y), Point(x2, y)])
Ejemplo n.º 26
0
    def press(self, widget, event):
        """
        This code is executed when you press the mouse button
        """
        self.emit("focus", Gtk.DirectionType.TAB_FORWARD)

        x = event.x / self.zoom
        y = event.y / self.zoom

        def start_resize(child):
            self.unselect_all()
            child.selected = True
            child.resizing = True
            if child.direction < ANONIMOUS:
                control = child.handler.control[opposite(child.direction)]
                child.pivot.x = self.grid.nearest(control.x)
                child.pivot.y = self.grid.nearest(control.y)
                child.pivot = self.guides.nearest(child.pivot)
                child.handler.pivot.x = control.x
                child.handler.pivot.y = control.y
                child.handler.pivot.active = True

        if self.pick:
            self.unselect_all()
            #x, y = self.get_pointer()
            target = Point()
            #child = self.get_child()
            child = self.child
            self.add(child)
            child.selected = True
            target.x = self.grid.nearest(x)
            target.y = self.grid.nearest(y)
            target = self.guides.nearest(target)
            child.x = target.x
            child.y = target.y
            child.width = 0
            child.height = 0
            child.direction = SOUTHEAST
            child.handler.control[opposite(child.direction)].y = child.y
            child.handler.control[opposite(child.direction)].x = child.x
            start_resize(child)
            #widget.bin_window.set_cursor(Gdk.Cursor.new(Gdk.BOTTOM_RIGHT_CORNER))
            widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.BOTTOM_RIGHT_CORNER))
            self.emit("select", child)
            return True

        selection = True

        def start_move(child, x, y):
            child.offset.x = x - child.x
            child.offset.y = y - child.y
            child.press(x, y)

        def select(child):
            if not event.get_state() & Gdk.ModifierType.CONTROL_MASK:
                self.unselect_all()
            child.selected = True

        for child in sorted(self.document.pages[0].children, key=lambda child: child.z):
            if child.selected:
                if child.handler.at_position(x, y):
                    child.direction = child.handler.get_direction(x, y)
                    selection = False
                    start_resize(child)
                elif child.at_position(x, y):
                    #start_move(child, x, y)
                    start_move(child, x, y)
                    selection = False
                else:
                    continue
            elif child.at_position(x, y):
                selection = False
                select(child)
                start_move(child, x, y)
            else:
                continue

        if selection:
            self.selection.x = x
            self.selection.y = y
            self.selection.width = 0
            self.selection.height = 0
            self.selection.active = True
            #widget.bin_window.set_cursor(Gdk.Cursor.new(Gdk.CursorType.CROSSHAIR))
            widget.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.CROSSHAIR))
        else:
            self.stop_cursor_change = True
            #self.updated = False
        self.update() # XXX

        return True
Ejemplo n.º 27
0
    def motion(self, widget, event):
        """
        This code is executed when move the mouse pointer
        """
        self.statics.motion += 1
        #self.consume(gtk.gdk.MOTION_NOTIFY, event.state)
        self.disconnect(self.motion_id)
        if self.horizontal_ruler:
            self.horizontal_ruler.motion(self.horizontal_ruler, event, True)
        if self.vertical_ruler:
            self.vertical_ruler.motion(self.vertical_ruler, event, True)
        x = event.x / self.zoom
        y = event.y / self.zoom

        if not self.stop_cursor_change:
            def get_direction_for_child_at_position(x, y, children):
                for child in children:
                    if child.selected and child.handler.at_position(x, y):
                        direction = child.handler.get_direction(x, y)
                        widget.bin_window.set_cursor(child.get_cursor(direction))
                        return direction
                return NONE

            direction = get_direction_for_child_at_position(x, y, self.document.pages[0].children)

            if direction == NONE:
                if self.pick:
                    widget.bin_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.PENCIL))
                else:
                    widget.bin_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.ARROW))

        if self.selection.active:
            self.selection.width = x - self.selection.x
            self.selection.height = y - self.selection.y
            self.updated = False
            self.update() # XXX
        elif event.state & gtk.gdk.BUTTON1_MASK:
            for child in self.document.pages[0].children: # TODO
                if child.selected:
                    target = Point()
                    if child.resizing:
                        target.x = self.grid.nearest(x)
                        target.y = self.grid.nearest(y)
                        target = self.guides.nearest(target)
                        if child.direction < ANONIMOUS:
                            child.resize(target.x, target.y)
                        else:
                            child.transform(target.x, target.y)
                    else:
                        widget.bin_window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR))
                        target.x = self.grid.nearest(x - child.offset.x)
                        target.y = self.grid.nearest(y - child.offset.y)
                        target = self.guides.nearest(target)
                        # XXX-TEST
                        if self.is_testing:
                            def magnetize(target, children):
                                for child in children:
                                    if not child.selected and child.magnetos.is_magnetized(target):
                                        return child.magnetos.get_magnetized(target)
                                return target

                            target = magnetize(target, self.document.pages[0].children)
                        # XXX-TEST
                        child.move(target.x, target.y)
                    self.emit("edit-child", child)
                    self.update()
        self.motion_id = self.connect("motion-notify-event", self.motion)
        return True