Ejemplo n.º 1
0
def init_space():
    sp = Space()

    # Cria quadrado
    L = 5
    player = Body(mass=1, moment=100)
    shape = Poly(player, [(-L, -L), (L, -L), (L, L), (-L, L)])
    player.position = (50, 40)
    player.velocity = (-25, 25)
    shape.elasticity = 1.0
    shape.color = pyxel.COLOR_RED

    # Cria margens
    line = Body(body_type=Body.STATIC)
    lines = [
        Segment(line, (-30, -30), (270, -30), 2),
        Segment(line, (-30, 210), (270, 210), 2),
        Segment(line, (-30, -30), (-30, 210), 2),
        Segment(line, (270, -30), (270, 210), 2),
    ]
    for line in lines:
        line.elasticity = 1.0

    # Adiciona elementos ao espaço
    sp.add(player, shape, *lines)
    sp.player = player
    return sp
Ejemplo n.º 2
0
 def add_segment(self, x1, y1, x2, y2, thickness=1, dynamic=True):
     body = Body(body_type=(Body.STATIC, Body.DYNAMIC)[int(dynamic)])
     seg = Segment(body, (x1, y1), (x2, y2), radius=thickness)
     seg.density = Environment.DEFAULT_DENSITY
     self.space.add(body, seg)
     self.bodies.append(body)
     return body
Ejemplo n.º 3
0
def init_space():
    sp = Space()
    sp.gravity = (0, 50)

    chain = make_pivot_chain(sp, (0, 0), (240, 30), 30)
    sp.add(constraint.PivotJoint(chain[0], sp.static_body, chain[0].position))

    # Cria quadrado
    L = 25
    player = Body(mass=1, moment=100)
    shape = Poly(player, [(-L, -L), (L, -L), (L, L), (-L, L)])
    player.position = (90, 60)
    player.velocity = (-25, 25)
    shape.elasticity = 1.0
    shape.color = pyxel.COLOR_RED
    shape.collision_type = 42

    ball = Body(mass=1, moment=200)
    ball_shape = Circle(ball, 20)
    ball.position = (player.position.x, 130)
    ball_shape.elasticity = 1.0
    shape.color = pyxel.COLOR_NAVY
    ball_shape.collision_type = 42

    joint1 = constraint.DampedSpring(player, ball, (0, 0), (20, 0), 20, 3, 0.5)
    joint2 = constraint.PivotJoint(sp.static_body, player, (65, 35))
    joint1.collide_bodies = False
    sp.add(joint1, joint2)

    body2 = Body(1, 100)
    sp.add(body2)
    sp.add(Poly(body2, [(-3, 3), (3, 3), (3, -3), (-3, -3)]))
    body2.position = 220, 50
    sp.add(constraint.DampedRotarySpring(body2, ball, 0, 2, 1))
    sp.body2 = body2

    # Cria margens
    line = Body(body_type=Body.STATIC)
    e = 0
    lines = [
        Segment(line, (-e, -e), (240 + e, -e), 2),
        Segment(line, (-e, 180 + e), (240 + e, 180 + e), 2),
        Segment(line, (-e, -e), (-e, 180 + e), 2),
        Segment(line, (240 + e, -e), (240 + e, 180 + e), 2),
    ]
    for line in lines:
        line.elasticity = 1.0
    lines = []

    # Adiciona elementos ao espaço
    sp.add(player, shape, ball, ball_shape, *lines)
    sp.player = player

    #handler = sp.add_collision_handler(42, 42)
    #handler.begin = lambda *args: False
    return sp
Ejemplo n.º 4
0
 def pymunk_pad(self, space, height):
     """
     Generate a Pymunk segment object which is used to detect
     physics based collision between the spacecraft and the landing pad.
     (collision tracking based on Pymunk physics objects)
     :param space: Pymunk physics space
     :param height: current scene (window) height
     :return: Pymunk segment object
     """
     pm_pad = Segment(
         space.static_body,
         flipy((self.rect.left + 14, self.rect.top + 16), height),
         flipy((self.rect.right - 14, self.rect.top + 16), height), 5)
     pm_pad.collision_type = 4
     return pm_pad
Ejemplo n.º 5
0
def init_space():
    sp = Space()

    player = Body(mass=1, moment=1)
    shape = Circle(player, 10)
    player.position = (20, 90)
    player.velocity = (5, 0)
    shape.color = pyxel.COLOR_YELLOW

    line = Body(body_type=Body.STATIC)
    line_shape = Segment(line, (0, 1), (240, 1), 2)
    line_shape.color = pyxel.COLOR_RED

    sp.add(player, shape, line, line_shape)
    sp.player = player
    return sp
    def __createLineShape(self, info: 'Dict[str, Any]',
                          default_elasticity: float = None,
                          default_friction: float = None) -> 'pymunk.Shape':

        points = info.get('Point', ())

        if len(points) != 2:
            raise ValueError('Line must have exactly two points')

        points = tuple((point.get('x', 0), point.get('y', 0))
                       for point in points)

        if points[0] == points[1]:
            raise ValueError('Start and end of the line must be different')

        thickness = info.get('thickness', 1)
        if thickness <= 0:
            raise ValueError('Line thickness must be greater than 0')

        shape = Segment(None, points[0], points[1], info.get('thickness', 1))

        self.__setGeneralProperties(shape, info,
                                    default_elasticity=default_elasticity,
                                    default_friction=default_friction)

        return shape
Ejemplo n.º 7
0
 def __init__(self, space, rect, playfield=None):
     super(Spinner, self).__init__()
     r, cy = rect.width / 2, rect.height / 2
     assert (r == cy)
     body = Body(.1, moment_for_circle(.1, 0, r))
     body.position = rect.center
     top = Circle(body, r)
     top.layers = 2
     rect2 = pygame.Rect((-r, -cy), rect.size)
     cross0 = Segment(body, rect2.midleft, rect2.midright, 1)
     cross1 = Segment(body, rect2.midtop, rect2.midbottom, 1)
     j0 = PivotJoint(playfield, body, body.position)
     j1 = SimpleMotor(playfield, body, 0)
     j1.max_force = 200
     self.shapes = [top, cross0, cross1, j0, j1]
     self.rect = pygame.Rect(rect)
     self._original_image = prepare.GFX['pachinko-spinner']
Ejemplo n.º 8
0
def init_space():
    sp = Space()
    sp.gravity = (0, 50)
    sp.damping = 1.0

    floor = Body(body_type=Body.STATIC)
    stick = Body(mass=100, moment=100 * 50**2)
    L = 20
    shapes = [
        Poly(stick, [(-L, -L), (L, -L), (L, L), (0, L + L / 2), (-L, L)],
             radius=3),
        Segment(floor, (1, 179), (239, 179), 1),
        Segment(floor, (1, 1), (239, 1), 1),
        Segment(floor, (1, 1), (1, 179), 1),
        Segment(floor, (239, 1), (239, 179), 1),
    ]
    stick.position = (120, L)

    bodies = []
    for _ in range(L):
        r = random.uniform(2, 6)
        mass = pi * r**2
        body = Body(mass=mass, moment=mass * r**2 / 2)
        circle = Circle(body, r)

        x = random.uniform(r, 240 - r)
        y = random.uniform(r, 180 - r)
        body.position = (x, y)

        vx = random.uniform(-L, L)
        vy = random.uniform(-L, L)
        body.velocity = (vx, vy)

        bodies.append(body)
        shapes.append(circle)
        circle.color = random.randint(1, 15)

    for shape in shapes:
        shape.elasticity = 1.0

    sp.add(floor, stick, *bodies, *shapes)
    return sp
Ejemplo n.º 9
0
 def __init__(self, space, rect, playfield=None, win=False, returns=False):
     super(Pocket, self).__init__()
     color = (220, 100, 0)
     inside = rect.inflate(-10, -10)
     cover = Poly.create_box(playfield, inside.size, rect.center)
     self.shapes = [cover]
     if win:
         self.shapes.extend(
             (Segment(playfield, rect.topleft, rect.bottomleft, 1),
              Segment(playfield, rect.bottomleft, rect.bottomright, 1),
              Segment(playfield, rect.bottomright, rect.topright, 1)))
     self._original_image = pygame.Surface(rect.size, pygame.SRCALPHA)
     pygame.draw.rect(self._original_image, color, rect)
     self.rect = pygame.Rect(rect)
     if win:
         self.shape.collision_type = pocket_win_type
     elif returns:
         self.shape.collision_type = pocket_return_type
     else:
         self.shape.collision_type = pocket_fail_type
Ejemplo n.º 10
0
    def __init__(self, space, rect, playfield=None):
        super(Spinner, self).__init__()
        r, cy = rect.width / 2., rect.height / 2.
        assert (r == cy)
        body = Body(.1, moment_for_circle(.1, 0.0, r))
        body.position = rect.center
        top = Circle(body, r)
        top.layers = 2
        rect2 = Rect((-r, -cy), rect.size)
        cross0 = Segment(body, rect2.midleft, rect2.midright, 1)
        cross0.layers = 3
        cross1 = Segment(body, rect2.midtop, rect2.midbottom, 1)
        cross1.layers = 4

        j0 = PivotJoint(playfield, body, body.position)
        j1 = SimpleMotor(playfield, body, 0.0)
        j1.max_force = 200
        self.shapes = [top, cross0, cross1, j0, j1]
        self.rect = Rect(rect)
        self._original_image = prepare.GFX['pachinko-spinner']
Ejemplo n.º 11
0
    def line(self, x1, y1, x2, y2, radius=1, **kwargs):
        """
        Creates a line segment from (x1, y1) to (x2, y2).
        """
        xm = (x1 + x2) / 2
        ym = (y1 + y2) / 2
        body = self._make_body(**kwargs)
        shape = Segment(body, (x1 - xm, y1 - ym), (x2 - xm, y2 - ym), radius)
        shape = self._make_shape(shape, **kwargs)

        body.position = (xm, ym)
        self.space.add(body, shape)
        return body
Ejemplo n.º 12
0
    def handle_polyline(data, body=None):
        def get_point(i):
            pt = [i * scale for i in get_xy(i)]
            return pt[0] + ox, (oy + pt[1]) - ooy

        get_xy = itemgetter('x', 'y')
        ox, oy = [i * scale for i in get_xy(data)]
        points = list(data['polyline'])
        prev_pt = get_point(points[0])
        for new_pt in (get_point(pt) for pt in points[1:]):
            segment = Segment(body, prev_pt, new_pt, 1)
            prev_pt = new_pt
            yield segment
Ejemplo n.º 13
0
 def path(self, vertices, *, radius=0, **kwargs):
     """
     Creates path of segments from the given list of vertices.
     """
     body = self._make_body(**kwargs)
     cm = path_center_of_mass(vertices)
     vs = vertices[:-1]
     us = vertices[1:]
     shapes = [
         self._make_shape(Segment(body, a - cm, b - cm, radius), **kwargs)
         for a, b in zip(vs, us)
     ]
     body.position = cm
     self.space.add(body, *shapes)
     return body
Ejemplo n.º 14
0
def init_space():
    sp = Space()

    h = 20 * sqrt(2)
    player = Body(mass=1, moment=400)
    shape = Poly(player, [(-20, -h / 3), (20, -h / 3), (0, 2 / 3 * h)])
    player.position = (90, 90)
    shape.elasticity = 1.0
    shape.color = pyxel.COLOR_YELLOW

    line = Body(body_type=Body.STATIC)
    lines = [
        Segment(line, (0, 1), (240, 1), 2),
        Segment(line, (0, 179), (240, 179), 2),
        Segment(line, (1, 0), (1, 180), 2),
        Segment(line, (239, 0), (239, 180), 2),
    ]
    for line in lines:
        line.elasticity = 1.0
        line.color = pyxel.COLOR_PEACH

    sp.add(player, shape, *lines)
    sp.player = player
    return sp
Ejemplo n.º 15
0
def create_segment(
        p1=(0, 0), p2=(0, 1), thicc=1, x=0, y=0, m=1, scalar=1,
        bt=Body.DYNAMIC):
    '''
    given point_1 (p1), point_2 (p2), thickness (thicc),
          x-position (x), y-position (y), mass (m),
          scalar <to augment the length>, body_type (bt)
    return (body, shape) tuple for a line segment
    '''
    given_bt = bt
    bt = Body.DYNAMIC if given_bt == 'dynamic' else Body.DYNAMIC
    bt = Body.STATIC if given_bt == 'static' else Body.DYNAMIC
    bt = Body.KINEMATIC if given_bt == 'kinematic' else Body.DYNAMIC
    p2 = (p2[0] * scalar, p2[1] * scalar)
    moment = moment_for_segment(mass=m, a=p1, b=p2, radius=thicc)
    body = Body(mass=m, moment=moment, body_type=bt)
    shape = Segment(body=body, a=p1, b=p2, radius=thicc)
    body.position = (x, y)
    return body, shape
Ejemplo n.º 16
0
def make_pivot_chain(space, a, b, n, mass=1):
    a, b = map(Vec2d, (a, b))
    delta = (b - a) / n
    L = delta.length
    pos = a

    objs = []
    prev_body = None
    for _ in range(n):
        final = pos + delta
        body = Body(mass=mass / n, moment=(mass / n) * L**2 / 2)
        shape = Segment(body, -delta / 2, delta / 2, 2)
        body.position = pos + delta / 2
        objs.append(body)

        if prev_body is not None:
            joint = constraint.PivotJoint(body, prev_body, pos)
            joint.collide_bodies = False
            space.add(joint)
        space.add(body, shape)
        pos = final
        prev_body = body

    return objs
Ejemplo n.º 17
0
    def __init__(self, kind, puck_shape, immobile=False):
        self.immobile = immobile
        # self.mass = 0.1  # 0.1 kg

        # Create a massless body with 0 moment of inertia.  Pymunk will figure
        # out the mass and moment of inertia based on the density (set below)
        # when the body and shape are both added to the space.
        if not immobile:
            self.body = Body(0, 0)
        else:
            self.body = Body(0, 0, Body.STATIC)

        if puck_shape == "CIRCLE":
            # Hockey puck radius = 23mm = 0.023
            #self.radius = 2.3 * CM_TO_PIXELS

            # Double hockey puck radius
            self.radius = 4.6 * CM_TO_PIXELS

            # Arbitrary radius
            #self.radius = 0.07 * M_TO_PIXELS

            # Plate puck radius = 12.8cm = 0.128
            #self.radius = 0.128 * M_TO_PIXELS

            # Objects from Gauci et al paper: 0.05 meter radius, converted to
            # pixels for display
            # self.radius = 12 * CM_TO_PIXELS

            self.shape = Circle(self.body, self.radius)

        elif puck_shape == "RANDOM_CIRCLES":
            self.radius = randint(1, 5) * CM_TO_PIXELS
            self.shape = Circle(self.body, self.radius)

        elif puck_shape == "RECTANGLE":
            length = 100
            thickness = 5
            a = Vec2d(0, 0)
            b = Vec2d(length, 0)
            self.shape = Segment(self.body, a, b, thickness)
            self.radius = length / 2

        elif puck_shape == "RANDOM_RECTANGLES":
            length = randint(10, 150)
            thickness = randint(4, 10)
            a = Vec2d(0, 0)
            b = Vec2d(length, 0)
            self.shape = Segment(self.body, a, b, thickness)
            self.radius = length / 2

        radiusForDensity = 2.3 * CM_TO_PIXELS  # hockey puck radius
        self.shape.density = 0.1 / (pi * radiusForDensity**2)

        self.body.position = 0, 0
        self.body.angle = uniform(-pi, pi)
        self.body.velocity = 0, 0
        self.body.angular_velocity = 0

        self.kind = kind
        if kind == 0:
            self.shape.color = 200, 100, 100
            self.shape.filter = ShapeFilter(categories=RED_PUCK_MASK)
        elif kind == 1:
            self.shape.color = 100, 200, 100
            self.shape.filter = ShapeFilter(categories=GREEN_PUCK_MASK)
        elif kind == 2:
            self.shape.color = 100, 100, 200
            self.shape.filter = ShapeFilter(categories=BLUE_PUCK_MASK)
        else:
            sys.exit("Unknown puck kind: " + kind)

        if immobile:
            self.shape.color = self.shape.color[0] / 3, self.shape.color[
                1] / 3, self.shape.color[2] / 3
Ejemplo n.º 18
0
    def __init__(self, pos, team, id):

        # Foot positions
        a = (-self.length, self.length)
        b = (self.length, self.length)
        c = (-self.length, -self.length)
        d = (self.length, -self.length)

        angle = 0 if team > 0 else math.pi
        headAngle = 0  #(random.random()-0.5) * self.headMaxAngle * 2

        # Setup left foot
        inertia = moment_for_segment(self.mass, a, b, self.radius)
        body = Body(self.mass, inertia, Body.DYNAMIC)
        body.position = pos
        body.angle = angle
        body.velocity_func = friction_robot
        self.leftFoot = Segment(body, a, b, self.radius)
        self.leftFoot.color = (255, int(127 * (1 - team)),
                               int(127 * (1 + team)), 0)
        self.leftFoot.elasticity = 0.3
        self.leftFoot.friction = 2.5
        self.leftFoot.collision_type = CollisionType.Robot

        # Setup right foot
        inertia = moment_for_segment(self.mass, c, d, self.radius)
        body = Body(self.mass, inertia, Body.DYNAMIC)
        body.position = pos
        body.angle = angle
        body.velocity_func = friction_robot
        self.rightFoot = Segment(body, c, d, self.radius)
        self.rightFoot.color = (255, int(127 * (1 - team)),
                                int(127 * (1 + team)), 0)
        self.rightFoot.elasticity = 0.3
        self.rightFoot.friction = 2.5
        self.rightFoot.collision_type = CollisionType.Robot

        # setup joint
        self.joint = PivotJoint(self.leftFoot.body, self.rightFoot.body,
                                (pos[0], pos[1]))
        self.joint.error_bias = 0.1
        self.rotJoint = RotaryLimitJoint(self.leftFoot.body,
                                         self.rightFoot.body, 0, 0)
        self.jointRemoved = False

        # Basic properties
        self.team = team
        self.id = id
        self.headAngle = headAngle

        # Previous position
        self.prevPos = self.getPos()

        # Penalty and pushing parametes
        self.penalized = False
        self.penalTime = 0
        self.touching = False
        self.touchCntr = 0
        self.mightPush = False
        self.fallen = False
        self.fallCntr = 0
        self.fallTime = 0

        # Movement parameters
        self.moveTime = 0
        self.headMoving = 0

        # Kick parameters
        self.kicking = False
        self.initPos = None
        self.foot = None
Ejemplo n.º 19
0
    def __init__(self,
                 width=600,
                 height=600,
                 obstacle_num=5,
                 obstacle_radius=30,
                 feed_num=0,
                 feed_radius=5):
        import pyglet
        from pymunk import Space, Segment, Body, Circle, moment_for_circle, pyglet_util
        super(VehicleSimulator, self).__init__()
        self.__left_sensor_val = 0
        self.__right_sensor_val = 0
        self.__feed_sensor_val = False
        self.__feed_touch_counter = {}
        self.__feed_bodies = []
        self.__feed_radius = feed_radius

        self.__window = pyglet.window.Window(
            self.ARENA_SIZE + self.DISPLAY_MARGIN * 2,
            self.ARENA_SIZE + self.DISPLAY_MARGIN * 2,
            vsync=False)
        self.__draw_options = pyglet_util.DrawOptions()
        self.__closed = False

        @self.__window.event
        def on_draw():
            pyglet.gl.glClearColor(255, 255, 255, 255)
            self.__window.clear()
            self.__simulation_space.debug_draw(self.__draw_options)

        @self.__window.event
        def on_close():
            pyglet.app.EventLoop().exit()
            self.__closed = True

        self.__simulation_space = Space()
        self.__simulation_space.gravity = 0, 0

        # arena
        walls = [
            Segment(
                self.__simulation_space.static_body,
                (self.DISPLAY_MARGIN, self.DISPLAY_MARGIN),
                (self.ARENA_SIZE + self.DISPLAY_MARGIN, self.DISPLAY_MARGIN),
                0),
            Segment(
                self.__simulation_space.static_body,
                (self.ARENA_SIZE + self.DISPLAY_MARGIN, self.DISPLAY_MARGIN),
                (self.ARENA_SIZE + self.DISPLAY_MARGIN,
                 self.ARENA_SIZE + self.DISPLAY_MARGIN), 0),
            Segment(
                self.__simulation_space.static_body,
                (self.ARENA_SIZE + self.DISPLAY_MARGIN,
                 self.ARENA_SIZE + self.DISPLAY_MARGIN),
                (self.DISPLAY_MARGIN, self.ARENA_SIZE + self.DISPLAY_MARGIN),
                0),
            Segment(
                self.__simulation_space.static_body,
                (self.DISPLAY_MARGIN, self.ARENA_SIZE + self.DISPLAY_MARGIN),
                (self.DISPLAY_MARGIN, self.DISPLAY_MARGIN), 0)
        ]
        for w in walls:
            w.collision_type = self.COLLISION_TYPE.OBJECT
            w.friction = 0.2
        self.__simulation_space.add(walls)

        # vehicle
        mass = 1
        self.__vehicle_body = Body(
            mass, moment_for_circle(mass, 0, self.VEHICLE_RADIUS))
        self.__vehicle_shape = Circle(self.__vehicle_body, self.VEHICLE_RADIUS)
        self.__vehicle_shape.friction = 0.2
        self.__vehicle_shape.collision_type = self.COLLISION_TYPE.VEHICLE
        self.__simulation_space.add(self.__vehicle_body, self.__vehicle_shape)

        # left sensor
        sensor_l_s = Segment(self.__vehicle_body, (0, 0),
                             (self.SENSOR_RANGE * np.cos(self.SENSOR_ANGLE),
                              self.SENSOR_RANGE * np.sin(self.SENSOR_ANGLE)),
                             0)
        sensor_l_s.sensor = True
        sensor_l_s.collision_type = self.COLLISION_TYPE.LEFT_SENSOR
        handler_l = self.__simulation_space.add_collision_handler(
            self.COLLISION_TYPE.LEFT_SENSOR, self.COLLISION_TYPE.OBJECT)
        handler_l.pre_solve = self.__left_sensr_handler
        handler_l.separate = self.__left_sensr_separate_handler
        self.__simulation_space.add(sensor_l_s)

        # right sensor
        sensor_r_s = Segment(self.__vehicle_body, (0, 0),
                             (self.SENSOR_RANGE * np.cos(-self.SENSOR_ANGLE),
                              self.SENSOR_RANGE * np.sin(-self.SENSOR_ANGLE)),
                             0)
        sensor_r_s.sensor = True
        sensor_r_s.collision_type = self.COLLISION_TYPE.RIGHT_SENSOR
        handler_r = self.__simulation_space.add_collision_handler(
            self.COLLISION_TYPE.RIGHT_SENSOR, self.COLLISION_TYPE.OBJECT)
        handler_r.pre_solve = self.__right_sensr_handler
        handler_r.separate = self.__right_sensr_separate_handler
        self.__simulation_space.add(sensor_r_s)

        # obstacles
        for a in (np.linspace(0, np.pi * 2, obstacle_num, endpoint=False) +
                  np.pi / 2):
            body = Body(body_type=Body.STATIC)
            body.position = (self.DISPLAY_MARGIN + self.ARENA_SIZE / 2 +
                             self.ARENA_SIZE * 0.3 * np.cos(a),
                             self.DISPLAY_MARGIN + self.ARENA_SIZE / 2 +
                             self.ARENA_SIZE * 0.3 * np.sin(a))
            shape = Circle(body, obstacle_radius)
            shape.friction = 0.2
            shape.collision_type = self.COLLISION_TYPE.OBJECT
            self.__simulation_space.add(shape)

        for i in range(feed_num):
            body = Body(1, 1)
            self.__feed_bodies.append(body)
            shape = Circle(body, self.__feed_radius)
            shape.sensor = True
            shape.color = self.FEED_COLOR
            shape.collision_type = self.COLLISION_TYPE.FEED
            handler = self.__simulation_space.add_collision_handler(
                self.COLLISION_TYPE.VEHICLE, self.COLLISION_TYPE.FEED)
            handler.pre_solve = self.__feed_touch_handler
            handler.separate = self.__feed_separate_handler
            self.__simulation_space.add(body, shape)
            self.__feed_touch_counter[shape] = 0

        self.reset()
Ejemplo n.º 20
0
def _add_wall_to(space, body, vert1, vert2, material):
    wall = Segment(body, vert1, vert2, 0.1)
    wall.friction = material.friction
    wall.elasticity = material.elasticity
    space.add_static(wall)