Beispiel #1
0
    def spawn_creature(self):
        body = pymunk.Body()
        body.position = self.creature_spawn_loc
        # shape = pymunk.Poly.create_box(body, (10, 40))
        trackL = pymunk.Poly(body,
                             [[-15, 20], [-15, -20], [-5, -20], [-5, 20]])
        trackR = pymunk.Poly(body, [[15, 20], [15, -20], [5, -20], [5, 20]])
        trackL.density = 0.000002
        trackR.density = 0.000002
        trackL.color = (75, 75, 75, 255)
        trackR.color = (75, 75, 75, 255)
        trackL.collision_type = self.CREATURE_COLLTYPE
        trackR.collision_type = self.CREATURE_COLLTYPE

        if self.use_sensor:
            # Add sesnor
            sensor = pymunk.Poly(body,
                                 [[0, 0], [self.sensor_a / 2, self.sensor_h],
                                  [-self.sensor_a / 2, self.sensor_h]])
            sensor.sensor = True
            sensor.collision_type = self.SENSOR_COLLTYPE
            sensor.color = (85, 255, 115, 255)
            self.space.add(sensor)

        self.space.add(body, trackL, trackR)
        h = self.space.add_collision_handler(self.SENSOR_COLLTYPE,
                                             self.TARGET_COLLTYPE)
        h.begin = self._sensor_activated
        h.separate = self._sensor_deactivated

        g = self.space.add_collision_handler(self.CREATURE_COLLTYPE,
                                             self.TARGET_COLLTYPE)
        g.begin = self._pick_up_target

        return body, trackL, trackR
Beispiel #2
0
    def createPlayer(self, socket_sid):

        body = pymunk.Body(PLAYER_MASS, 1666)

        front_physical = pymunk.Poly(
            body,
            offsetBox(TRUCK_PLOW_LENGTH / 2 - TRUCK_BODY_SPACING / 2, 0,
                      TRUCK_PLOW_LENGTH, TRUCK_PLOW_WIDTH),
            radius=2.0)
        front_physical.elasticity = 1.5
        front_physical.collision_type = TRUCK_PLOW_TYPE

        back_physical = pymunk.Poly(
            body,
            offsetBox(-TRUCK_BODY_LENGTH / 2 - TRUCK_BODY_SPACING / 2, 0,
                      TRUCK_BODY_LENGTH - TRUCK_BODY_SPACING,
                      TRUCK_BODY_WIDTH),
            radius=2.0)
        back_physical.elasticity = 5.0
        back_physical.collision_type = TRUCK_CORE_TYPE

        body.position = ARENA_WIDTH * random.random(
        ), ARENA_HEIGHT * random.random()
        body.angle = 2 * math.pi * random.random()

        self.space.add(body, front_physical, back_physical)
        player = Player(socket_sid, self, body)
        self.players.append(player)
        body.player = player
Beispiel #3
0
    def __init__(self,
                 name,
                 space,
                 vertices,
                 density=DEFAULT_DENSITY,
                 elasticity=DEFAULT_ELASTICITY,
                 friction=DEFAULT_FRICTION,
                 color=DEFAULT_COLOR):
        PGObject.__init__(self, name, "Poly", space, color, density, friction,
                          elasticity)

        #vertices = map(lambda v: map(float, v), vertices)
        vertices = [[float(vp) for vp in v] for v in vertices]
        loc = centroidForPoly(vertices)
        area = areaForPoly(vertices)
        mass = density * area

        if mass == 0:
            self._cpShape = pm.Poly(space.static_body, vertices)
            self._cpShape.elasticity = elasticity
            self._cpShape.friction = friction
            self._cpShape.collision_type = COLTYPE_SOLID
            self._cpShape.name = name
            space.add(self._cpShape)
        else:
            recenterPoly(vertices)
            imom = pm.moment_for_poly(mass, vertices)
            self._cpBody = pm.Body(mass, imom)
            self._cpShape = pm.Poly(self._cpBody, vertices)
            self._cpShape.elasticity = elasticity
            self._cpShape.friction = friction
            self._cpShape.collision_type = COLTYPE_SOLID
            self._cpShape.name = name
            self._cpBody.position = loc
            space.add(self._cpBody, self._cpShape)
Beispiel #4
0
def load_poly_concave(tmxobject, map_height, static_body, defaults):
    """
    Creates several pymunk.Poly objects parsed from a TiledObject instance.
    They share a common pymunk.Body object.

    :param TiledObject tmxobject: A TiledObject instance that represents a \
    concave polygon with multiple vertices.
    :param int map_height: The height of the TiledMap that the TiledObject \
    was loaded from in pixels.

    """

    poly_defaults = defaults["pymunktmx_poly"]
    shape_attrs = get_shape_attrs(tmxobject, poly_defaults)
    body_attrs = get_body_attrs(tmxobject, poly_defaults)
    offset = body_attrs[u"offset"]
    radius = shape_attrs[u"radius"]

    # break concave shape into triangles
    points = list(tmxobject.points)

    # pymunk.util.triangulate expects the list to be in anti-clockwise order
    if pymunk.util.is_clockwise(points):
        points.reverse()

    # the pymunk.util.convexise doesn't create shapes that match originals
    # so we will just use the triangles
    triangles = pymunk.util.triangulate(points)

    shapes = []
    if body_attrs[u"static"]:
        for vertices in triangles:
            vertices = [(p[0], map_height - p[1]) for p in vertices]
            shape = pymunk.Poly(static_body, vertices, offset, radius)
            shapes.append(shape)

    else:
        x = float(tmxobject.x)
        y = float(float(map_height) - tmxobject.y)
        mass = body_attrs[u"mass"]
        verts = [(p[0] - x, -(p[1] - y)) for p in tmxobject.points]
        moment = pymunk.moment_for_poly(mass, verts, offset)
        body = pymunk.Body(mass, moment)
        body.position = (x, y)

        set_attrs(body_attrs,
                  body,
                  skip_keys=[u"position", u"mass", u"static"])

        for vertices in triangles:
            vertices = [(p[0] - x, -(p[1] - y)) for p in vertices]
            shape = pymunk.Poly(body, vertices, offset, radius)
            shapes.append(shape)

        shapes.append(body)

    for shape in shapes:
        set_attrs(shape_attrs, shape, skip_keys=[u"radius"])

    return shapes
Beispiel #5
0
def add_hourglass(space):
    global bodyradius
    global bodyheight

    bodylefttriangle = pymunk.Body(body_type=pymunk.Body.STATIC)
    # change body1 and body2 x position to change the opening size
    bodylefttriangle.position = (245 - bodyradius, 150 + bodyheight)
    shape = pymunk.Poly(bodylefttriangle, [(0, 0), (0, 100), (50, 50)])
    space.add(shape)

    bodyrighttriangle = pymunk.Body(body_type=pymunk.Body.STATIC)
    # change body1 and body2 x position to change the opening size
    bodyrighttriangle.position = (355 + bodyradius, 150 + bodyheight)
    shape2 = pymunk.Poly(bodyrighttriangle, [(0, 0), (0, 100), (-50, 50)])
    space.add(shape2)

    bodybottom = pymunk.Body(body_type=pymunk.Body.STATIC)
    bodybottom.position = (200, 50)
    bb1 = pymunk.Segment(bodybottom, (-200, 0), (500, 0), 10)
    # change these 2 to change the opening
    bb2 = pymunk.Segment(bodybottom, (45 - bodyradius, 0),
                         (45 - bodyradius, 350 + bodyheight), 10)
    bb3 = pymunk.Segment(bodybottom, (155 + bodyradius, 0),
                         (155 + bodyradius, 350 + bodyheight), 10)
    space.add(bb1)
    space.add(bb2)
    space.add(bb3)

    bodytop = pymunk.Body(body_type=pymunk.Body.STATIC)
    bodytop.position = (200, 500)
    bt1 = pymunk.Segment(bodytop, (-200, -100 + bodyheight),
                         (500, -100 + bodyheight), 10)
    space.add(bt1)

    return shape, shape2, bb1, bb2, bb3, bt1
Beispiel #6
0
def create_hill(space, sprite_list, start_x, y, count):
    """ Create a hill """
    # Left edge
    sprite = PymunkSprite("./images/tiles/grassHill_right.png", start_x - constants.SPRITE_SIZE, y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
    t = pymunk.Transform(tx=-60, ty=-96)
    sprite.shape = pymunk.Poly(sprite.body, [(80, 120), (80, 60), (20, 60)], transform=t)
    sprite.shape.friction = constants.DEFAULT_FRICTION / 4
    sprite_list.append(sprite)
    space.add(sprite.body, sprite.shape)
    # Add dirt under
    dirt_y = 0
    sprite = PymunkSprite("./images/tiles/grassCorner_right.png", start_x - constants.SPRITE_SIZE, dirt_y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
    sprite_list.append(sprite)

    # Middle
    for x in range(start_x, start_x + count * constants.SPRITE_SIZE + 1, constants.SPRITE_SIZE):
        sprite = PymunkSprite("./images/tiles/grassMid.png", x, y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
        sprite_list.append(sprite)
        space.add(sprite.body, sprite.shape)
        # Add dirt under
        dirt_y = 0
        sprite = PymunkSprite("./images/tiles/grassCenter.png", x, dirt_y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
        sprite_list.append(sprite)

    # Right edge
    sprite = PymunkSprite("./images/tiles/grassHill_left.png", start_x + constants.SPRITE_SIZE * count + constants.SPRITE_SIZE, y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
    sprite.shape.friction = constants.DEFAULT_FRICTION / 4
    t = pymunk.Transform(tx=-60, ty=-96)
    sprite.shape = pymunk.Poly(sprite.body, [(20, 120), (20, 60), (80, 60)], transform=t)
    sprite_list.append(sprite)
    space.add(sprite.body, sprite.shape)
    # Add dirt under
    dirt_y = 0
    sprite = PymunkSprite("./images/tiles/grassCorner_left.png", start_x + constants.SPRITE_SIZE * count + constants.SPRITE_SIZE, dirt_y, scale=constants.SPRITE_SCALING, body_type=pymunk.Body.STATIC)
    sprite_list.append(sprite)
    def create_world(self):
        self.space = pymunk.Space()
        self.space.gravity = Vec2d(0., -900.)

        static_body = pymunk.Body()
        static_lines = [  #pymunk.Segment(static_body, Vec2d(50,100), Vec2d(550,100), 1),
            #pymunk.Segment(static_body, Vec2d(450,100), Vec2d(450,300), 1)
        ]

        static_blocks = [
            pymunk.Poly(static_body, [(50, 100), (550, 100), (550, 99),
                                      (50, 99)])
        ]
        for l in static_blocks:
            l.friction = 0.3
        self.space.add(static_blocks)

        for x in range(5):
            for y in range(12):
                size = 5
                points = [(-size, -size), (-size, size), (size, size),
                          (size, -size)]
                mass = 10.0
                moment = pymunk.moment_for_poly(mass, points, (0, 0))
                body = pymunk.Body(mass, moment)
                body.position = Vec2d(200 + x * 50, 105 + y * 11)
                shape = pymunk.Poly(body, points, (0, 0))
                shape.friction = 0.3
                self.space.add(body, shape)
Beispiel #8
0
    def create_world(self):
        fp = [(self.tray_width / 2, -self.tray_height / 2),
              (-self.tray_width / 2, self.tray_height / 2),
              (self.tray_width / 2, self.tray_height / 2),
              (-self.tray_width / 2, -self.tray_height / 2),
              (-self.tray_width / 2, -self.tray_height / 2)]

        mass = 100
        moment = pymunk.moment_for_poly(mass, fp[0:2])

        self.trayBody = pymunk.Body(mass, moment)
        self.trayBody.position = self.tray_x_pos, self.tray_y_pos
        self.trayBody.angle = self.tray_angle
        trayShape = pymunk.Poly(self.trayBody, fp)
        if self.tray_has_ends:
            side1 = [(self.tray_width / 2, self.tray_height / 2),
                     (self.tray_width / 2, self.tray_height * 4),
                     (self.tray_width / 2 - 1, self.tray_height * 4),
                     (self.tray_width / 2 - 1, self.tray_height / 2)]
            side2 = [(-self.tray_width / 2, self.tray_height / 2),
                     (-self.tray_width / 2, self.tray_height * 4),
                     (-self.tray_width / 2 + 1, self.tray_height * 4),
                     (-self.tray_width / 2 + 1, -self.tray_height / 2)]
            self.side1_shape = pymunk.Poly(self.trayBody, side1)
            self.side2_shape = pymunk.Poly(self.trayBody, side2)
            self.space.add(self.side1_shape, self.side2_shape)
        self.space.add(self.trayBody, trayShape)

        trayJointBody = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        trayJointBody.position = self.trayBody.position
        j = pymunk.PinJoint(self.trayBody, trayJointBody, (0, 0), (0, 0))
        self.space.add(j)

        self.__add_ball()
def main():
    pygame.init()
    screen = pygame.display.set_mode((600, 600))
    pygame.display.set_caption("Joints. Just wait and the L will tip over")
    clock = pygame.time.Clock()

    space = pymunk.Space(threaded=True)
    space.gravity = (0.0, -900.0)
    balls = []
    ###
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = 0, 200
    shape = pymunk.Poly(body, ([0, 0], [0, 10], [600, 10], [600, 0]))
    shape.filter = pymunk.ShapeFilter(categories=0x1)
    space.add(body, shape)

    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = 0, 180
    shape = pymunk.Poly(body, ([0, 0], [0, 10], [600, 10], [600, 0]))
    shape.filter = pymunk.ShapeFilter(categories=0x2)
    space.add(body, shape)

    ###
    draw_options = pymunk.pygame_util.DrawOptions(screen)
    ticks_to_next_ball = 10
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                sys.exit(0)
            elif event.type == KEYDOWN and event.key == K_SPACE:
                for line in lines:
                    space.remove(line)
                lines = []

        ticks_to_next_ball -= 1
        if ticks_to_next_ball <= 0:
            ticks_to_next_ball = 25
            ball_shape = add_ball(space)
            balls.append(ball_shape)

        screen.fill((255, 255, 255))

        balls_to_remove = []
        for ball in balls:
            if ball.body.position.y < 150:
                balls_to_remove.append(ball)

        for ball in balls_to_remove:
            space.remove(ball, ball.body)
            balls.remove(ball)

        space.debug_draw(draw_options)

        space.step(1 / 50.0)
        pygame.display.flip()
        clock.tick(50)
    def __init__(self, _space, _robotgrafik):

        self._id = _robotgrafik._id
        # For updateing the robot position
        self.robotgrafik = _robotgrafik
        # pymunk space
        self.space = _space
        # radius of the robot in cm
        self.radius = 10
        # mass of the robot in kg
        self.mass = 2000
        # maximum velocity in m/ms
        self.vmax = gc.ROBOTS[self._id - 1]["vmax"]
        # maximum torque for all wheels combined in Nm
        self.fmax = gc.ROBOTS[self._id - 1]["fmax"]
        # motor speed array
        self.motor = np.array([0, 0, 0, 0])
        # indicator if the robot is "defekt"
        self.defekt = False

        # configure the Body of the Robot
        self.body = pymunk.Body(
            self.mass,
            pymunk.moment_for_circle(self.mass, 0, self.radius, (0, 0)))
        self.body.position = ((self.robotgrafik._x_position,
                               self.robotgrafik._y_position))
        self.body.angle = np.radians(self.robotgrafik._orientation)
        self.body.name = "robot" + str(self._id)
        self.startAngle = self.body.angle

        # generate the special shape of the robot.
        # because the ballcapture zone is not concave two polygons are needed
        polygonlist1 = [[3, 5], [5, 3], [3, 1], [3, -1], [-5, -1], [-5, 3],
                        [-3, 5]]
        polygonlist2 = [[3, 1], [5, -3], [3, -5], [-3, -5], [-5, -3], [-5, 1]]

        # scale polygon to correct size
        scale = 10 / 5.83  #scaling 10/5.83 = 10/sqrt(3¹+5¹)
        newpolygon1 = []
        for p in polygonlist1:
            newpolygon1.append([p[0] * scale, p[1] * scale])
        newpolygon2 = []
        for p in polygonlist2:
            newpolygon2.append([p[0] * scale, p[1] * scale])

        # generate Robot shapes
        self.shape1 = pymunk.Poly(self.body, newpolygon1)
        self.shape1.elasticity = 0
        self.shape1.friction = 0.9
        self.shape1.collision_type = collision_types["robot"]
        self.shape2 = pymunk.Poly(self.body, newpolygon2)
        self.shape2.elasticity = 0
        self.shape2.friction = 0.9
        self.shape2.collision_type = collision_types["robot"]

        # add shapes to Body
        self.space.add(self.body, self.shape1, self.shape2)
Beispiel #11
0
    def __init__(self,
                 vertices,
                 x,
                 y,
                 app,
                 size=5,
                 resistance=1,
                 color=9,
                 damage=10):
        self.x = x
        self.y = y

        self.forceX = 0
        self.forceY = 0

        self.damage = damage

        self.app = app
        self.space = app.space
        self.px = app.px

        self.health = 100
        self.resistance = 0.1  # 0 is infinite resistance
        self.maxHealth = 100

        self.size = size

        # drifer's shape is a pentagon
        self.vertices = vertices * size

        self.hitboxVertices = vertices * (size + 2)

        # will probably want to improve this in the future
        self.body = pymunk.Body(2 * size, pymunk.inf)
        self.body.velocity_func = noGravity
        self.body.angular_velocity = np.random.uniform(-0.5, 0.5)

        self.hitbox = pymunk.Poly(self.body, self.hitboxVertices, radius=1)
        self.hitbox.filter = pymunk.ShapeFilter(
            categories=constants.MASK_ENEMY)
        self.hitbox.sensor = True

        self.shape = pymunk.Poly(self.body, self.vertices, radius=1)
        self.shape.filter = pymunk.ShapeFilter(categories=constants.MASK_ENEMY)

        self.body.position = x, y
        self.color = color

        self.state = {
            "seePlayer": False,
            "memory": 0,
            "lookAt": None,
            "lookAtNorm": None,
            "collisions": {},
            "dead": False,
            "ticks": 0
        }
def add_hourglass(space):
    global bodyradius
    global bodyheight
    global angle

    bodylefttriangle = pymunk.Body(body_type=pymunk.Body.STATIC)
    # change body1 and body2 x position to change the opening size
    bodylefttriangle.position = (245 - bodyradius, 150 + bodyheight)
    shape = pymunk.Poly(bodylefttriangle, [(0, 0), (0, 50 + angle), (50, 50)])
    shape.elasticity = 0.0
    shape.friction = 0
    space.add(shape)

    bodyrighttriangle = pymunk.Body(body_type=pymunk.Body.STATIC)
    # change body1 and body2 x position to change the opening size
    bodyrighttriangle.position = (355 + bodyradius, 150 + bodyheight)
    shape2 = pymunk.Poly(bodyrighttriangle, [(0, 0), (0, 50 + angle),
                                             (-50, 50)])
    shape2.elasticity = 0.0
    shape2.friction = 0
    space.add(shape2)

    bodybottom = pymunk.Body(body_type=pymunk.Body.STATIC)
    bodybottom.position = (200, 50)
    bb1 = pymunk.Segment(bodybottom, (-200, 0), (500, 0), 10)
    # change these 2 to change the opening
    bb2 = pymunk.Segment(bodybottom, (45 - bodyradius, 0),
                         (45 - bodyradius, 350 + bodyheight), 10)
    bb3 = pymunk.Segment(bodybottom, (155 + bodyradius, 0),
                         (155 + bodyradius, 350 + bodyheight), 10)

    bb1.elasticity = 0.0
    bb2.elasticity = 0.0
    bb3.elasticity = 0.0
    bb1.friction = 10
    bb2.friction = 10
    bb3.friction = 10
    space.add(bb1)
    space.add(bb2)
    space.add(bb3)

    bodytop = pymunk.Body(body_type=pymunk.Body.STATIC)
    bodytop.position = (200, 500)
    bt1 = pymunk.Segment(bodytop, (-200, -100 + bodyheight),
                         (500, -100 + bodyheight), 10)

    bt1.elasticity = 0.0
    bt1.friction = 100
    space.add(bt1)

    bodystop = pymunk.Body(body_type=pymunk.Body.STATIC)
    bodystop.position = (250 - bodyradius, 200 + bodyheight)
    bstopper = pymunk.Segment(bodystop, (0, 0), (100 + bodyradius, 0), 5)
    space.add(bstopper)

    return shape, shape2, bb1, bb2, bb3, bt1, bstopper
Beispiel #13
0
    def testVertices(self):
        vs = [(-10,10), (0,0),(20,0),(10,10)]
        c = p.Poly(None, vs, None, 0)

        self.assertEqual(c.get_vertices(), vs)
        
        c = p.Poly(None, vs, p.Transform(1,2,3,4,5,6), 0)
        
        vs2 = [(5.0, 6.0), (25.0, 26.0), (45.0, 66.0), (25.0, 46.0)]
        self.assertEqual(c.get_vertices(), vs2)
def add_robot(space, seat):
    #define robot upper body and upper leg
    ubt = Vec2d(3.5, 0)
    robot_u_points = [
        Vec2d(-4, 31.64) + ubt,
        Vec2d(-4, 0) + ubt,
        Vec2d(4, 0) + ubt,
        Vec2d(4, 31.64) + ubt
    ]

    robot_body = pymunk.Body()
    robot_body.position = seat.position + (0, 3)
    robot_u = pymunk.Poly(robot_body, robot_u_points)
    robot_u.mass = 3.311
    robot_u.color = THECOLORS["red"]
    robot_u.filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS ^ 1)

    robot_u_leg = pymunk.Poly(seat, [(1, 3), (-10.5, 3), (-10.5, 8), (1, 8)])
    robot_u_leg.color = THECOLORS["red"]
    robot_u_leg.mass = 0.603
    #robot_u_leg_extra = pymunk.Circle(seat,2,(5,0))
    #robot_u_leg_extra.mass = 2

    #define robot lower leg
    robot_leg = pymunk.Body()
    robot_leg.position = seat.position
    robot_l_leg = pymunk.Poly(robot_leg, [(-10.5, 5), (-10.5, -11.8),
                                          (-4.0, -11.8), (-4.0, 5)])
    robot_l_leg.mass = 1.214
    robot_l_leg.color = THECOLORS["red"]
    space.add(robot_body, robot_u, robot_u_leg, robot_leg, robot_l_leg)

    #motor and pivot for hip
    #uses measured values of angles rather than given in program
    seat_motor = pymunk.SimpleMotor(seat, robot_body, 0)
    seat_motor.max_force = 1e6
    seat_pivot = pymunk.PivotJoint(seat, robot_body, robot_body.position + ubt)
    seat_pivot._set_collide_bodies(False)
    seat_pivot_lim = pymunk.RotaryLimitJoint(robot_body, seat, 0, 0.575959)
    space.add(seat_motor, seat_pivot, seat_pivot_lim)

    #motor and pivot for knee
    max_knee_ang = 5

    max_knee_ang = np.deg2rad(max_knee_ang)
    knee_motor = pymunk.SimpleMotor(seat, robot_leg, 0)
    knee_motor.max_force = 1e5
    knee_pivot = pymunk.PivotJoint(seat, robot_leg, seat.position + (-8, 7))
    knee_pivot._set_collide_bodies(False)
    knee_pivot_lim = pymunk.RotaryLimitJoint(seat, robot_leg,
                                             max_knee_ang - np.deg2rad(69),
                                             max_knee_ang)
    space.add(knee_motor, knee_pivot, knee_pivot_lim)

    return seat_motor, knee_motor, robot_body, robot_leg, robot_u_leg
Beispiel #15
0
    def __init__(self, starting_slot, first_hit_wins):
        self.time = 0
        self.winner = None
        self.curr_hit = None
        self.first_hit_wins = first_hit_wins

        self.space = pymunk.Space()
        self.space.gravity = 0, GRAVITY if starting_slot == 0 else -GRAVITY

        self.wall_body = pymunk.Body(body_type=pymunk.Body.STATIC)

        left_points = [
            Vec2d(-0.5, -1),
            Vec2d(-1, -1),
            Vec2d(-1, 1),
            Vec2d(-0.5, 1)
        ]
        right_points = [
            Vec2d(0.5, -1),
            Vec2d(1, -1),
            Vec2d(1, 1),
            Vec2d(0.5, 1)
        ]

        self.left_wall_shape = pymunk.Poly(self.wall_body, left_points)
        self.left_wall_shape.friction = 1
        self.left_wall_shape.elasticity = 0.65

        self.right_wall_shape = pymunk.Poly(self.wall_body, right_points)
        self.right_wall_shape.friction = self.left_wall_shape.friction
        self.right_wall_shape.elasticity = self.left_wall_shape.elasticity

        self.space.add(self.wall_body, self.left_wall_shape,
                       self.right_wall_shape)

        self.ball = Ball(self)
        self.ball.body.position = Vec2d(0.75 * (random.random() - 0.5), 0)
        self.ball.body.velocity = Vec2d(0.2 * (random.random() - 0.5), 0)

        self.paddles = [Paddle(self, 0), Paddle(self, 1)]

        for slot in [0, 1]:
            paddle = self.paddles[slot]
            joint = pymunk.GrooveJoint(
                self.wall_body,
                paddle.mounting_body,
                groove_a=Vec2d(-0.5, paddle.slot_multiplier * SLIDER_Y),
                groove_b=Vec2d(0.5, paddle.slot_multiplier * SLIDER_Y),
                anchor_b=Vec2d(0, 0))
            self.space.add(joint)

        self.handler = self.space.add_default_collision_handler()
        self.handler.post_solve = self._post_solve
def create_sides():
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (25, 400)
    w, h = 1, 800
    vs = [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h)]
    shape = pymunk.Poly(body, vs)
    space.add(body, shape)

    body1 = pymunk.Body(body_type=pymunk.Body.STATIC)
    body1.position = (775, 400)
    shape = pymunk.Poly(body1, vs)
    space.add(body1, shape)
def create_align():
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (300, 25)
    w, h = 1, 50
    vs = [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h)]
    shape = pymunk.Poly(body, vs)
    shape.color = (255, 0, 0, 255)
    space.add(body, shape)

    body1 = pymunk.Body(body_type=pymunk.Body.STATIC)
    body1.position = (500, 25)
    shape = pymunk.Poly(body1, vs)
    space.add(body1, shape)
Beispiel #18
0
    def __init__(self,
                 application,
                 func,
                 collider,
                 space,
                 solid=False,
                 filter=None,
                 args=()):
        self.application = application
        while True:
            id = random.randint(1000, 100000)
            if id not in self.application.trigger_ids:
                self.application.trigger_ids.append(id)
                self.id = id
                break

        self.space = space
        self.solid = solid
        self.filter = filter

        self.func = func
        self.args = args

        if collider["type"] == "rect":
            self.collider = pymunk.Poly(
                body=self.space.static_body,
                vertices=[(collider["x"], collider["y"]),
                          (collider["x"] + collider["width"], collider["y"]),
                          (collider["x"] + collider["width"],
                           collider["y"] + collider["height"]),
                          (collider["x"], collider["y"] + collider["height"])],
                radius=collider["radius"])
        elif collider["type"] == "circle":
            self.collider = pymunk.Circle(body=self.space.static_body,
                                          radius=collider["radius"],
                                          offset=collider["offset"])
        elif collider["type"] == "poly":
            self.collider = pymunk.Poly(body=self.space.static_body,
                                        vertices=collider["vertices"],
                                        radius=collider["radius"])
        self.space.add(self.collider)

        if self.filter is None:
            self.handler = self.space.add_wildcard_collision_handler(self.id)
        else:
            self.handler = self.space.add_collision_handler(
                self.id, self.filter)
        self.handler.begin = self.begin
Beispiel #19
0
    def testBB(self):
        c = p.Poly(None, [(2,2),(4,3),(3,5)])
        bb = c.update(p.Transform.identity())
        self.assertEqual(bb, c.bb)
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))

        b = p.Body(1,2)
        c = p.Poly(b, [(2,2),(4,3),(3,5)])
        c.cache_bb()
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))

        s = p.Space()
        b = p.Body(1,2)
        c = p.Poly(b, [(2,2),(4,3),(3,5)])
        s.add(b,c)
        self.assertEqual(c.bb, p.BB(2, 2, 4, 5))
Beispiel #20
0
    def _create_pm_shape(self, is_interactive=False):

        if is_interactive:
            radius = self.interaction_radius
            width = self.interaction_width
            length = self.interaction_length
        else:
            radius = self.radius
            width = self.width
            length = self.length

        if self.physical_shape == 'circle':
            pm_shape = pymunk.Circle(self.pm_body, radius)

        elif self.physical_shape in [
                'triangle', 'square', 'pentagon', 'hexagon'
        ]:
            vertices = self._compute_vertices(is_interactive=is_interactive)
            pm_shape = pymunk.Poly(self.pm_body, vertices)

        elif self.physical_shape == 'rectangle':
            pm_shape = pymunk.Poly.create_box(self.pm_body, (width, length))

        else:
            raise ValueError

        if is_interactive:
            pm_shape.sensor = True
        else:
            pm_shape.friction = FRICTION_ENTITY
            pm_shape.elasticity = ELASTICITY_ENTITY

        return pm_shape
Beispiel #21
0
    def __init__(self, img, x=400, y=70):
        playerImageTile = pyglet.resource.image(img)
        self.playerRight = playerImageTile.get_region(0, 0, 64, 64)
        self.playerLeft = playerImageTile.get_region(64, 0, 64, 64)

        self.sprite = pyglet.sprite.Sprite(self.playerLeft, x=x, y=y)

        self.height = self.playerRight.height
        self.width = self.playerRight.width
        mass = 10

        self.maxSpeed = 300
        self.maxJumpSpeed = 200

        self.body = pymunk.Body(mass, float('inf'))  #infinity!
        self.body.position = (x, y)

        #self.body.velocity = (10, 0)

        self.box = pymunk.Poly(self.body,
                               ((0, 0), (0, self.height),
                                (self.width, self.height), (self.width, 0)))
        self.box.friction = 0.2
        self.box.elasticity = 0.4

        self.touchingObject = False

        self._dx = 0
        self._v_step = 10
Beispiel #22
0
    def __init__(self, pos, verts, space, rng):
        self.num_cols = math.ceil(const.SCREEN_WIDTH / const.TILE_SIZE)
        self.num_rows = math.ceil(const.WATER_HEIGHT / const.TILE_SIZE)

        self.top_tile = utils.load_image(["river_to_sand_tile.png"])
        self.tile = utils.load_image(["river_tile.png"])

        self.debris_tile = utils.load_image(["debris", "seaweed_water.png"])
        tile_size = self.tile.get_size()

        self.rects = []
        for row in range(self.num_rows):
            new_row = []
            for col in range(self.num_cols):
                rect = pg.Rect(
                    col * const.TILE_SIZE, pos[1] + (row * const.TILE_SIZE), *tile_size
                )
                new_row.append(rect)
            self.rects.append(new_row)

        self.body = pm.Body(body_type=pm.Body.STATIC)

        # Transform pygame vertices to fit Pymunk body
        invert_verts = utils.invert_y(verts)
        self.shape = pm.Poly(self.body, invert_verts)
        self.shape.collision_type = CollisionTypes.WATER

        self.body.position = utils.flipy(pos)
        self.space = space
        self.space.add(self.shape)
Beispiel #23
0
 def __init__(self, vertexlist, color, elast, stb, pmsp = None):
     self.poly = pm.Poly(stb, vertexlist)
     self.poly.elasticity = elast
     self.poly.collision_type = COLLTYPE_WALL
     self.col = color
     self.shapetype = SHAPE_POLY
     self.sp = ref(pmsp)
Beispiel #24
0
    def __init__(self, num, col, striped):
        self.frictionCounter = 0
        self.radius = 23 / 2
        self.mass = 1.000000 + (num * 0.00000001)
        self.num = num
        self.col = col
        self.striped = striped

        self.moment = pymunk.moment_for_circle(self.mass, 0, self.radius,
                                               (0, 0))
        self.moment = math.inf
        self.body = pymunk.Body(self.mass, self.moment)
        self.body.body_type = 0

        self.shapeID = pymunk.Circle(self.body, num, (0, 0))
        self.shape3 = pymunk.Circle(self.body, 1, (0, 0))

        if self.striped:
            self.shape = pymunk.Circle(self.body, self.radius, (0, 0))
            self.shape2 = pymunk.Poly(self.body,
                                      ((-self.radius, 3), (self.radius, 3),
                                       (self.radius, -3), (-self.radius, -3)))
            self.shape.color = (255, 255, 255, 255)

            self.shape2.color = (col)
            self.shape2.filter = pymunk.ShapeFilter(categories=1)
        else:
            self.shape = pymunk.Circle(self.body, self.radius, (0, 0))
            self.shape.color = (col)

        self.shape.elasticity = 1
        self.shape.friction = 0.0
        self.shape.filter = pymunk.ShapeFilter(categories=1)
        self.shape3.filter = pymunk.ShapeFilter(categories=4, mask=4)
        self.shape3.collision_type = 10
Beispiel #25
0
def create_bananas(space):
    mass = 10
    size = 50
    points = [(-size, -size), (-size, size), (size,size), (size, -size)]
    moment = pymunk.moment_for_poly(mass, points, (0,0))
    body = pymunk.Body(mass, moment)
    x = random.randint(0, 500)
    body.position = Vec2d(x,x)
    banana = pymunk.Poly(body, points, (0,0))
    #banana.friction = 2
    banana.elasticity = 0.95
    space.add(body, banana)

    """
    Circular Banana

    radius = 10
    inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
    body = pymunk.Body(mass, inertia)
    x = random.randint(0, 500)
    body.position = x, x
    banana = pymunk.Circle(body, radius, (0, 0))
    banana.elasticity = 0.95
    space.add(body, banana)
    """
    return banana
Beispiel #26
0
		def make_logo(self):

			#"""
			for letter in range(len(self.logo_polys)):
				self.letters.append([])

				mass = 100
				body = pm.Body(mass, 30000)

				cps = [p.get_centerpoint() for p in self.logo_polys[letter]]
				cp_x = sum((p.x for p in cps)) / len(self.logo_polys[letter])
				cp_y = sum((p.y for p in cps)) / len(self.logo_polys[letter])

				body.position = cp_x, cp_y

				self.space.add(body)

				for poly in self.logo_polys[letter]:

					pt = Polygon.from_tuples([(v.x - cp_x, v.y - cp_y) for v in poly])
					verts = [(v.x, v.y) for v in pt]

					shape = pm.Poly(body, verts)
					shape.elasticity = 0.1

					self.letters[letter].append( (pt, body) )
					self.space.add(shape)

			"""
    def get_shape(self, boundary):
        '''
        shape documentation at: https://pymunk-tutorial.readthedocs.io/en/latest/shape/shape.html
        '''

        if self.agent_shape == 'segment':
            width = boundary['width']
            length = boundary['length']

            half_width = width / 2
            half_length = length / 2 - half_width
            shape = pymunk.Segment(None, (-half_length, 0), (half_length, 0),
                                   radius=half_width)

        elif self.agent_shape == 'circle':
            length = boundary['length']
            half_length = length / 2
            shape = pymunk.Circle(None, radius=half_length, offset=(0, 0))

        elif self.agent_shape == 'rectangle':
            width = boundary['width']
            length = boundary['length']
            half_length = length / 2
            half_width = width / 2
            shape = pymunk.Poly(
                None, ((-half_length, -half_width), (half_length, -half_width),
                       (half_length, half_width), (-half_length, half_width)))

        return shape
Beispiel #28
0
    def __init__(self,
                 img,
                 x=0,
                 y=0,
                 mass=10,
                 friction=0.1,
                 elasticity=0.5,
                 canRotate=True):

        super(PhysicalObject, self, img, x=x, y=y).__init__()

        if canRotate:
            moment = pymunk.moment_for_box(mass, self.width, self.height)
        else:
            moment = float('inf')

        self.body = pymunk.Body(mass, moment)

        self.box = pymunk.Poly(self.body,
                               ((-self.width / 2, -self.height / 2),
                                (-self.width / 2, +self.height / 2),
                                (+self.width / 2, +self.height / 2),
                                (+self.width / 2, -self.height / 2)))

        self.box.friction = friction
        self.box.elasticity = elasticity
Beispiel #29
0
 def __init__(self, space, id, sides, vertices, radius, color, obstacle_type):
     self.error_details = ''
     try:
         self.id = id
         self.created = False
         self.space = space
         self._parse_input(sides, vertices, radius, color, obstacle_type) #convert string inputs to appropriate data types
         valid_input = self._check_input(self.sides, self.vertices, self.radius, self.color, self.obstacle_type) #ensure inputs are in the required data types
         if valid_input:
             if self.obstacle_type == 'D':
                 self.body = pymunk.Body(body_type = pymunk.Body.DYNAMIC)
             if self.obstacle_type == 'F':
                 self.body = pymunk.Body(body_type = pymunk.Body.STATIC)
             self.color = self.color + [255]
             if self.sides == 1:
                 self.body.position = self.vertices
                 self.shape = pymunk.Circle(self.body, self.radius)
             elif self.sides == 2:
                 self.shape = pymunk.Segment(self.body, self.vertices[0:2], self.vertices[2:], self.radius)
             else:
                 self.shape = pymunk.Poly(self.body, self._group_vertices(self.vertices), None, self.radius)
             self.shape.friction = 1
             self.shape.mass = 10
             self.shape.color = self.color
             self.space.add(self.body, self.shape)
             self.vertices = self._group_vertices(self.vertices)
             self.created = True
         else:
             raise Exception
     except:
         self.error_mssg = 'Invalid input for ' + self.id + '\nPlease ensure all values are in the appropriate format. Refer to documentation for more help.'
         if self.error_details != '':
             self.error_mssg += '\n\nError Details:\n' + self.error_details
         error(self.error_mssg)
Beispiel #30
0
    def __init__(self,
                 space,
                 init_pos=(0, 0),
                 image_shape=None,
                 is_player=True,
                 is_geosynch=False,
                 moon_center=(0, 0),
                 boost_sound=None):
        super().__init__()
        self.game_over = False
        self.rocket_boost_sound = boost_sound
        self.is_geosynch = is_geosynch
        self.is_player = is_player
        self.image = pygame.image.load(resource_path("images/catstronaut.png"))
        self.moon_center = moon_center
        if image_shape:
            self.image = pygame.transform.scale(self.image, image_shape)
            self.image = pygame.transform.flip(self.image, True, True)
        self.rect = self.image.get_bounding_rect()
        width = self.rect.width
        height = self.rect.height
        self.space = space
        self.pos = pygame.Vector2(init_pos)

        vs = [(-width / 2, -height / 2), (width / 2, -height / 2),
              (width / 2, height / 2), (-width / 2, height / 2)]
        mass = 5
        moment = pymunk.moment_for_poly(mass, vs)
        self.body = pymunk.Body(mass, moment)
        self.body.force = (0, -250)
        self.body.position = self.pos.x, -self.pos.y + 500
        self.shape = pymunk.Poly(self.body, vs)
        self.shape.friction = 0.5
        self.space.add(self.body, self.shape)
        self.can_jump = True