Esempio n. 1
0
File: sim.py Progetto: mfekadu/jeans
def get_pymunk_space(gravity=(0, -9.807)):
    '''returns a `space` where the physics happens'''
    space = Space()
    # gravity is represented by a tuple
    # 0 acceleration in x-axis and -9.807 in y-axis
    space.gravity = gravity
    return space
Esempio n. 2
0
    def __addBoundaries(space: pymunk.Space):
        global floor1_1, floor1_2
        floor1_1 = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        floor1_1.velocity = (-groundSpeed, 0)
        floor1_1.position = (windowSize[0] / 2, windowSize[1])
        shape1_1 = pymunk.Segment(floor1_1, (-500, 0), (500, 0), 10)
        shape1_1.color = (0, 0, 255, 255)
        shape1_1.friction = 0.69

        floor1_2 = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        floor1_2.velocity = (-groundSpeed, 0)
        floor1_2.position = (windowSize[0] + 500, windowSize[1])
        shape1_2 = pymunk.Segment(floor1_2, (-500, 0), (500, 0), 10)
        shape1_2.friction = 0.69

        floor2 = pymunk.Body(body_type=pymunk.Body.STATIC)
        shape2 = pymunk.Segment(floor2, (0, 0), (windowSize[0], 0), 10)
        shape2.friction = 1.00

        floor3 = pymunk.Body(body_type=pymunk.Body.STATIC)
        shape3 = pymunk.Segment(floor3, (0, 0), (0, windowSize[1]), 10)
        shape3.friction = 1.00
        shape3.color = (255, 0, 0, 255)
        shape3._set_collision_type(1)

        floor4 = pymunk.Body(body_type=pymunk.Body.STATIC)
        shape4 = pymunk.Segment(floor4, (windowSize[0], 0),
                                (windowSize[0], windowSize[1]), 10)
        shape4.friction = 1.00
        space.add(floor1_1, shape1_1, floor1_2, shape1_2, floor2, shape2,
                  floor3, shape3, floor4, shape4)
    def build_grid(self, space: pymunk.Space, collision_type_for_brick,
                   collision_type_for_ball, aspect_ratio):
        grid_position = aspect_ratio.scale(90, 500)

        brick_size = aspect_ratio.scale(100, 16)
        brick_width = brick_size.x
        brick_height = brick_size.y

        space_between_brick = aspect_ratio.scale(10, 14)
        x_space_between_brick = space_between_brick.x
        brick_step_x = brick_width + x_space_between_brick

        y_space_between_brick = space_between_brick.y
        brick_step_y = brick_height + y_space_between_brick

        for x in range(10):
            pos_x = grid_position.x + x * brick_step_x
            for y in range(10):
                pos_y = grid_position.y + y * brick_step_y
                # http://www.pymunk.org/en/latest/pymunk.html#pymunk.Body.__init__
                body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
                # position
                body.position = pos_x, pos_y
                # shape
                shape = pymunk.Segment(body, (0, 0),
                                       aspect_ratio.scale(100, 0), 8)
                shape.elasticity = 0.98
                shape.collision_type = collision_type_for_brick
                space.add(body, shape)

        handler = space.add_collision_handler(collision_type_for_brick,
                                              collision_type_for_ball)
        # http://www.pymunk.org/en/latest/pymunk.html#pymunk.CollisionHandler.separate
        handler.separate = self._cb_remove_brick
Esempio n. 4
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
Esempio n. 5
0
 def __init__(self):
     self.items = []
     self.words = []
     self.springs = []
     init_pymunk()
     self.space = Space()
     self.space.resize_static_hash()
     self.space.resize_active_hash()
def mark_startingpoint(space: pymunk.Space, sp: SegmentPart) -> None:
    """Draw Car Simulation Starting point and indicate Starting Direction."""
    start_body = pymunk.Body(body_type=pymunk.Body.STATIC)

    starting_dot = pymunk.Circle(start_body, 6, offset=to_pygame(sp.start))
    starting_dot.collision_type = COLLISION_TYPES['start']

    space.add(starting_dot)
Esempio n. 7
0
def static_circ(x: int, y: int, r: int, col: int, space: pymunk.Space,
                **kwargs):
    pyxel.circ(x, y, r, col)
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (x, y)
    s = pymunk.Circle(body, radius=r)
    for k, v in kwargs.items():
        setattr(s, k, v)
    space.add(s)
Esempio n. 8
0
 def __init__(self):
     self.items = []
     init_pymunk()
     self.space = Space()
     self.space.gravity = (0, -0.5)
     self.space.resize_static_hash()
     self.space.resize_active_hash()
     self.leaves = []
     self.end_game = False
def create_segment(space: pymunk.Space, segment: Segment) -> None:
    """Create walls in space."""
    seg_body = pymunk.Body(body_type=pymunk.Body.STATIC)

    for seg_part in segment:
        seg_shape = pymunk.Segment(seg_body, to_pygame(seg_part.start),
                                   to_pygame(seg_part.end), 3)
        seg_shape.elasticity = 0
        seg_shape.collision_type = COLLISION_TYPES['wall']
        space.add(seg_shape)
Esempio n. 10
0
    def step(space: pymunk.Space, dt: float) -> None:
        """Step the space using a fixed timestep, even when ``dt`` varies.

        :param space: The space to step forward
        :param dt: A variable amount of time to move forward
        """
        nonlocal unused_dt
        steps, unused_dt = divmod(dt + unused_dt, fixed_timestep)
        for _ in range(int(steps)):
            space.step(fixed_timestep)
Esempio n. 11
0
    def __init__(
        self,
        space: pymunk.Space,
        paddle_position: Vec2d,
        collision_type: CollisionType,
        aspect_ratio: AspectRatio,
        mass: float = 1,
        paddle: Paddle = None,
    ):
        """

        :param space:
        :param paddle_position:
        :param collision_type:
        :param aspect_ratio:
        :param mass:
        :param paddle:
        """
        super().__init__(mass=mass, moment=pymunk.inf)

        self.aspect_ratio = aspect_ratio

        self.radius = 16

        paddle_height = 16
        paddle_half_height = paddle_height

        ball_position = Vec2d(
            paddle_position.x, paddle_position.y +
            aspect_ratio.scale_s(paddle_half_height + self.radius))
        self.position = ball_position

        shape = pymunk.Circle(self, radius=aspect_ratio.scale_s(self.radius))
        shape.elasticity = 0.98
        shape.collision_type = collision_type
        shape.filter = pymunk.ShapeFilter(categories=2 << collision_type)

        self.spc = space
        self.on_paddle = True

        self.velocity_func = self.constant_velocity

        self.joint = pymunk.GrooveJoint(
            space.static_body,
            self,
            Vec2d(paddle.groove_joint.groove_a.x, ball_position.y),
            Vec2d(paddle.groove_joint.groove_b.x, ball_position.y),
            Vec2d(0, 0),
        )
        space.add(self, shape, self.joint)

        self.ball_speed = 500

        self.segments_q = []
        self.points_on_ball = []
    def __init__(self, config):
        self.sprite_list = _arcade.SpriteList()
        self.obstacles = []
        self.static_obstacles = []
        self.falling_obstacles = []
        self.color_obstacles = []

        self.robots = []
        self.space = Space()
        self.space.damping = 0.1

        self.board_width = config['board_width']
        self.board_height = config['board_height']
        board_color = tuple(config['board_color'])

        board = Board(self.board_width / 2, self.board_height / 2, self.board_width, self.board_height, board_color)
        self.static_obstacles.append(board)

        for robot_conf in config['robots']:
            self.robots.append(RobotState(robot_conf))

        edge = Edge(self.board_width, self.board_height)
        self.static_obstacles.append(edge)
        self.falling_obstacles.append(edge)

        for obstacle in config['obstacles']:
            if obstacle['type'] == 'lake':
                lake = Lake.from_config(obstacle)
                self.static_obstacles.append(lake)
                if lake.hole is not None:
                    self.falling_obstacles.append(lake.hole)
                self.color_obstacles.append(lake)
            elif obstacle['type'] == 'rock':
                rock = Rock.from_config(obstacle)
                self.obstacles.append(rock)
            elif obstacle['type'] == 'border':
                border = Border.from_config(self.board_width, self.board_height, obstacle)
                self.static_obstacles.append(border)
                self.color_obstacles.append(border)
            elif obstacle['type'] == 'bottle':
                bottle = Bottle.from_config(obstacle)
                self.obstacles.append(bottle)
            elif obstacle['type'] == 'tile':
                tile = Tile.from_config(obstacle)
                self.static_obstacles.append(tile)
                self.color_obstacles.append(tile)
            else:
                print("unknown obstacle type")

        self.falling_obstacles.append(board)
        self.color_obstacles.append(board)

        self.selected_object = None
    def __init__(self,
                 space: pymunk.Space,
                 collision_type: CollisionType,
                 aspect_ratio,
                 mass=10):
        """

        :param space:
        :param collision_type:
        :param aspect_ratio:
        :param mass:
        """
        super().__init__(mass=mass, moment=pymunk.inf)

        wall_left = 50
        wall_right = 1230
        wall_bottom = 50

        paddle_width = 100
        paddle_height = 16
        paddle_half_width = paddle_width // 2
        paddle_half_height = paddle_height // 2

        paddle_position = Vec2d(640, wall_bottom + paddle_height * 3)
        self.position = aspect_ratio.scale_V2d(paddle_position)

        shape = pymunk.Segment(self, aspect_ratio.scale(-paddle_half_width, 0),
                               aspect_ratio.scale(+paddle_half_width, 0),
                               aspect_ratio.scale_s(paddle_half_height))
        # Don't work with custom pre_solve collision handler (this solver suppose a segment and not
        # a polygonal shape). Need to fix that !
        # shape = pymunk.Poly.create_box(self, (paddle_width, paddle_height))

        shape.elasticity = 1.00
        shape.collision_type = collision_type
        shape.filter = pymunk.ShapeFilter(categories=2 << collision_type)

        self.groove_joint = GroovJoint(
            aspect_ratio.scale(wall_left + paddle_half_width * 1.50,
                               paddle_position.y),
            aspect_ratio.scale(wall_right - paddle_half_width * 1.50,
                               paddle_position.y),
        )

        self.joint = pymunk.GrooveJoint(
            space.static_body,
            self,
            self.groove_joint.groove_a,
            self.groove_joint.groove_b,
            self.groove_joint.anchor,
        )

        space.add(self, shape, self.joint)
    def _cb_remove_brick(self, arbiter: pymunk.Arbiter, space: pymunk.Space,
                         data):
        """
        callback function

        :param arbiter:
        :param space:
        :param data:
        :return:
        """
        brick_shape = arbiter.shapes[0]
        space.remove(brick_shape, brick_shape.body)
Esempio n. 15
0
    def __init__(self, game):
        super().__init__(game)
        self.player = None
        self.active = True

        self.geometry = list()
        self.space = Space()
        self.space.gravity = (0, 1000)
        self.sprites = LayeredUpdates()
        self.event_handler = event_handling.EventQueueHandler()
        self.background = resources.gfx("background.png", convert=True)
        self.load()
        pygame.mixer.music.load(resources.music_path("zirkus.ogg"))
        pygame.mixer.music.play(-1)
Esempio n. 16
0
def static_rect(x: int, y: int, w: int, h: int, col: int, space: pymunk.Space,
                **kwargs):
    """
    Draws a static rectb with collisions.
    :return:
    :param kwargs: addition keyword args for Poly. Check pymonk.Poly docs for that. Exmaple: friction
    """
    pyxel.rect(x, y, w, h, col)
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    body.position = (x + w // 2, y + h // 2)  # pymunk uses gravity center
    # No extra body because it's  static without any properties
    s = pymunk.Poly.create_box(body, size=(w, h))
    for k, v in kwargs.items():
        setattr(s, k, v)
    space.add(s)
Esempio n. 17
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
Esempio n. 18
0
def find_nearby_paths(
    space: pymunk.Space,
    position: Vec2d,
    radius: float,
    # group_id=None,
    sequence=None,
    previous_path=None,
) -> List[Tuple[pymunk.PointQueryInfo, Path]]:
    """
    Finds nearby paths to the search position, within the search radius.
    :param space: the pymunk space to search in
    :param position: search position
    :param radius: search radius
    :param sequence: if not None, will only return paths with this sequence
    :param current_path: if not None, will exclude this path
    :return: a list of (PointQueryInfo, Path) tuples of the nearby paths
    """

    shape_filter: pymunk.ShapeFilter = pymunk.ShapeFilter(
        categories=EntityCategory.hint_sensor)

    return [
        (clean_pqi(pqi, position), pqi.shape.body.entity)
        for pqi in space.point_query(position, radius, shape_filter)
        if pqi.shape is not None and pqi.shape.body is not None
        and pqi.shape.body.entity is not None and pqi.shape.body.entity.type_
        == EntityType.path and pqi.shape.body.entity is not previous_path and (
            sequence is None or pqi.shape.body.entity.sequence is sequence)
    ]
Esempio n. 19
0
    def scan(self,
             position: Vec2d,
             start_angle: float,
             space: pymunk.Space,
             result_filter=lambda rsr: True):
        contacts: [(Vec2d, RayScanResult)] = []

        # alpha_correction_factor = self.beam_radius / self.distance

        for i in range(self.resolution):
            scan_angle = start_angle + self.scan_step_angle * i
            scan_endpoint = position + Vec2d(self.distance,
                                             0).rotated(scan_angle)
            # self.scan_endpoints.append(scan_endpoint)
            segment_query_infos: [pymunk.SegmentQueryInfo] = \
                space.segment_query(position, scan_endpoint, self.beam_radius, self.shape_filter)

            segment_contacts: [RayScanResult] = []
            for segment_query_info in segment_query_infos:
                shape = segment_query_info.shape
                if shape is None or shape.sensor:
                    continue

                # corrected_alpha = min(1.0, segment_query_info.alpha + alpha_correction_factor)

                entity = shape.body.entity
                rsr = RayScanResult(segment_query_info.alpha, entity.type_,
                                    entity.id, segment_query_info.point,
                                    segment_query_info.normal, shape, entity)

                if result_filter(rsr):
                    segment_contacts.append(rsr)
            contacts.append((scan_endpoint, segment_contacts))
        return contacts
Esempio n. 20
0
 def __init__(self):
     self.items = []
     self.words = []
     self.springs = []
     init_pymunk()
     self.space = Space()
     self.space.resize_static_hash()
     self.space.resize_active_hash()
    def build_dynamic_grid(self, space: pymunk.Space, collision_type_for_brick,
                           collision_type_for_ball, aspect_ratio):

        wall_left = 50
        wall_right = 1230

        grid_left_corner = aspect_ratio.scale(wall_left + 40, 500)
        grid_right_corner = aspect_ratio.scale(wall_right - 40,
                                               500 + (16 + 14) * 10 - 40)

        nb_bricks = Vec2d(12, 8)

        spaces_between_brick = aspect_ratio.scale_V2d(Vec2d(10, 14))

        grid_size = grid_right_corner - grid_left_corner

        brick_size = (
            grid_size -
            (nb_bricks - Vec2d(1, 1)) * spaces_between_brick) / nb_bricks

        brick_steps = brick_size + spaces_between_brick

        for x in range(nb_bricks.x):
            pos_x = grid_left_corner.x + x * brick_steps.x
            for y in range(nb_bricks.y):
                pos_y = grid_left_corner.y + y * brick_steps.y

                # https://github.com/viblo/pymunk/blob/master/examples/breakout.py
                # http://www.pymunk.org/en/latest/pymunk.html#pymunk.Body.__init__
                brick_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
                # position
                brick_body.position = Vec2d(pos_x, pos_y) + brick_size * 0.5

                brick_shape = pymunk.Poly.create_box(brick_body, brick_size)

                brick_shape.elasticity = 0.98
                brick_shape.collision_type = collision_type_for_brick
                brick_shape.filter = pymunk.ShapeFilter(
                    categories=2 << collision_type_for_brick)
                space.add(brick_body, brick_shape)

        handler = space.add_collision_handler(collision_type_for_brick,
                                              collision_type_for_ball)
        # http://www.pymunk.org/en/latest/pymunk.html#pymunk.CollisionHandler.separate
        handler.separate = self._cb_remove_brick
Esempio n. 22
0
    def test_add_to_body(self):
        disc = Disc(gold, 5, (1, 2))
        body = Body(0, 0)
        space = Space()
        space.add(body)

        disc.add_to_body(space, body)

        self.assertNotNone(disc.shape, "didnt create shape")
        self.assertEquals(disc.shape.body, body, "didnt add shape to body")
        self.assertEquals(disc.shape.radius, 5.0, "bad radius")
        self.assertEquals(disc.shape.center, Vec2d(1.0, 2.0), "bad center")
        self.assertAlmostEquals(disc.shape.friction, gold.friction,
            msg="bad friction")
        self.assertAlmostEquals(disc.shape.elasticity, gold.elasticity,
            msg="bad elasticity")
        self.assertEquals(space.shapes, [disc.shape],
            "didn't add shape to space")
Esempio n. 23
0
 def __init__(self):
     self.items = []
     init_pymunk()
     self.space = Space()
     self.space.gravity = (0, -0.5)
     self.space.resize_static_hash()
     self.space.resize_active_hash()
     self.leaves = []
     self.end_game = False
    def create_car(self, space: pymunk.Space, sp: SegmentPart, mass=20):
        """Create a car body and add to Space."""
        vertices = [(0, 0), (CAR_SIZE[0], 0), (CAR_SIZE[0], CAR_SIZE[1]),
                    (0, CAR_SIZE[1])]
        inertia = pymunk.moment_for_poly(mass, vertices)
        angle = calc_radians_between(sp.start, sp.end)

        body = pymunk.Body(mass, inertia)
        body.angle = angle
        body.position = to_pygame(sp.start)
        body.velocity = calc_heading_vector(angle) * 0

        shape = pymunk.Poly(body, vertices)
        shape.elasticity = 0
        shape.collision_type = COLLISION_TYPES['car']

        space.add(body, shape)

        return shape
Esempio n. 25
0
    def __init__(self, space: pymunk.Space, collision_type_for_ball,
                 collision_type_for_bottom, cb_loose_ball, aspect_ratio):
        """

        :param space:
        :param collision_type_for_ball:
        :param collision_type_for_bottom:
        :param cb_loose_ball: call back function to reset game
        """

        left = pymunk.Segment(space.static_body, aspect_ratio.scale(50, 50),
                              aspect_ratio.scale(50, 800), 2)
        top = pymunk.Segment(space.static_body, aspect_ratio.scale(50, 800),
                             aspect_ratio.scale(1230, 800), 2)
        right = pymunk.Segment(space.static_body, aspect_ratio.scale(1230, 50),
                               aspect_ratio.scale(1230, 800), 2)

        left.elasticity = 1.0
        right.elasticity = 1.0
        top.elasticity = 1.0

        bottom = pymunk.Segment(space.static_body, aspect_ratio.scale(50, 50),
                                aspect_ratio.scale(1230, 50), 2)
        bottom.sensor = True
        bottom.collision_type = collision_type_for_bottom

        left.filter = pymunk.ShapeFilter(
            categories=2 << collision_type_for_bottom)
        right.filter = pymunk.ShapeFilter(
            categories=2 << collision_type_for_bottom)
        top.filter = pymunk.ShapeFilter(
            categories=2 << collision_type_for_bottom)
        bottom.filter = pymunk.ShapeFilter(
            categories=2 << collision_type_for_bottom)

        # http://www.pymunk.org/en/latest/pymunk.html#pymunk.CollisionHandler
        handler = space.add_collision_handler(collision_type_for_ball,
                                              collision_type_for_bottom)
        handler.begin = self.reset_game
        self.cb_loose_ball = cb_loose_ball

        space.add(left, top, right, bottom)
    def __init__(self, do_render, sparse, max_motor_force):
        self.do_render = do_render
        self.sparse = sparse
        self.max_motor_force = max_motor_force

        if self.do_render:
            pygame.init()
            self.screen = pygame.display.set_mode((ENV_SIZE, ENV_SIZE))
            self.draw_options = pygame_util.DrawOptions(self.screen)
            self.clock = pygame.time.Clock()
        self.motors = []
        self.segment_bodies = []

        self.space = Space()
        self.space.iterations = 20

        no_collision = self.space.add_collision_handler(NO_COLLISION_TYPE, NO_COLLISION_TYPE)
        no_collision.begin = lambda a, b, c: False
        ghost_collision = self.space.add_wildcard_collision_handler(GHOST_TYPE)
        ghost_collision.begin = lambda a, b, c: False
Esempio n. 27
0
    def __init__(self):
        super().__init__()
        self.space = Space(threaded=True)
        self.space.collision_slop = 0.7
        self.iter = 0
        self.time = 0.0
        self.on_reset = []
        self.P, self.I, self.D = 4.25347222, 0.0001041666, -4.67881944
        self.I = 0.0

        y = 0
        L = 500
        self.ground = self.line(-L,
                                y,
                                L,
                                y,
                                static=True,
                                friction=0.75,
                                radius=5)
        handler = self.space.add_wildcard_collision_handler(1)
        handler.begin = self.on_collision
Esempio n. 28
0
def init_game():
    sp = Space()
    # sp.gravity = (0,90)
    # sp.damping = 0.8

    # Add Cat to Space
    generate_cat(sp)

    # Add pickle to Space
    generate_pickles(sp)

    # Add star to Space
    generate_stars(sp)

    # Add floor to Space
    floor = Body(body_type=Body.STATIC)
    floor_shape = Floor(floor, (0, SCREEN_H - 1), (SCREEN_W, SCREEN_H - 1), 1)
    floor_shape.elasticity = 0.7
    sp.add(floor, floor_shape)

    return sp
Esempio n. 29
0
class World(object):


    def __init__(self, debug_draw=None):
        self.space = Space()
        self.debug_draw = debug_draw


    def step(self, elapsed):
        if self.debug_draw:
            self.debug_draw.pre_world_step()
        self.space.step(elapsed)

        if self.debug_draw:
            for shape in self.space.shapes:
                if isinstance(shape, Poly):
                    self.debug_draw.DrawPolygon(shape)

        for body in self.space.bodies:
            body.reset_forces()

            

    def add(self, body_or_joint, shape=None):
        if shape is not None:
            self.space.add(body_or_joint, shape)
        else:
            self.space.add(body_or_joint)


    def render(self):
        if self.debug_draw:
            self.debug_draw.render()
Esempio n. 30
0
 def create(self, space: pymunk.Space):
     Creature.__create(self.limbs, space, True)
     space.add(self.body, self.shape)
     Creature.__create(self.limbs, space, False)
     for pivot in self.pivots:
         space.add(pivot)
     for muscle in self.muscles:
         space.add(muscle)
Esempio n. 31
0
def add_rects_to_space(space: pymunk.Space, rects: list) -> list:
    """This function should executed ONCE"""
    for rect in rects:

        def zero_gravity(body, gravity, damping, dt):
            pymunk.Body.update_velocity(body, (0, 0), damping, dt)

        _w, _h = rect[0].width, rect[0].height

        rect_b = pymunk.Body(1, 2, body_type=pymunk.Body.STATIC)
        rect_b.position = rect[0].x + _w / 2, rect[0].y + _h / 2
        rect_b.gameden = {"tile_id": rect[1]}
        rect_poly = pymunk.Poly(rect_b, [(-_w / 2, -_h / 2), (_w / 2, -_h / 2),
                                         (_w / 2, _h / 2), (-_w / 2, _h / 2)])
        rect_poly.friction = 0.8
        rect_poly.gameden = {"tile_id": rect[1]}
        space.add(rect_b, rect_poly)
        rect_b.velocity_func = zero_gravity

        rect.append(rect_b)
        rect.append(rect_poly)

    return rects
    def draw_sensor(self,
                    space: pymunk.Space,
                    sensor_size: int = 10) -> pymunk.Shape:
        """Create Cross for Car Sensors."""
        cross_body = pymunk.Body(body_type=pymunk.Body.DYNAMIC)

        line_one = pymunk.Segment(cross_body,
                                  self.position + Coordinate(0, sensor_size),
                                  self.position + Coordinate(sensor_size, 0),
                                  2)
        line_two = pymunk.Segment(
            cross_body, self.position,
            self.position + Coordinate(sensor_size, sensor_size), 2)

        line_one.color, line_two.color = pygame.color.THECOLORS[
            'green'], pygame.color.THECOLORS['green']
        line_one.collision_type, line_two.collision_type = COLLISION_TYPES[
            'sensor'], COLLISION_TYPES['sensor']
        line_one.sensor, line_two.sensor = True, True

        space.add([line_one, line_two])

        return line_one, line_two
Esempio n. 33
0
def createSpace(engine_):
  global engine
  engine = engine_

  space = Space()
  space.gravity = Vec2d(0.0, 0.0)
  PhysicsEntity.body = space.static_body

  # attach collision handlers (defined at the end of the file)
  space.add_collision_handler(
    Blob.collisionType,
    Blob.collisionType,
    # begin = handler_blob
    # separate = handler_blob
    pre_solve = handler_blob
  )
  # space.add_collision_handler(
  #   Blob.collisionType,
  #   Wall.collisionType,
  #   pre_solve = handler_wall,
  # )

  return space
Esempio n. 34
0
    def __init__(self):
        # pylint: disable-msg=W0212
        #   Access to a protected member '_space': ack
        init_pymunk()
        self.space = Space()
        self.space.gravity = (0, 0)
        self.space._space.contents.elasticIterations = 10
        self.static_body = Body(inf, inf)

        self.rooms = {}
        self.ents = set()
        self.chunks = set()
        self.player = None

        self.material = granite
Esempio n. 35
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
 def test_distance_no_obstacle(self):
     config = {
         'name': 'ultrasonic-sensor-front',
         'type': 'ultrasonic_sensor',
         'x_offset': 0,
         'y_offset': -91.5,
         'brick': 0,
         'port': 'ev3-ports:in3'
     }
     robot = MagicMock()
     us = UltrasonicSensor(config, robot)
     us.setup_pymunk_shape(1, None)
     us.sprite = MagicMock()
     us.sprite.angle = 0
     space = Space()
     val = us.distance(space)
     self.assertEqual(val, 2550)
Esempio n. 37
0
class World(object):
    "Container for everything in the model, eg: Rooms and Chunks"

    def __init__(self):
        # pylint: disable-msg=W0212
        #   Access to a protected member '_space': ack
        init_pymunk()
        self.space = Space()
        self.space.gravity = (0, 0)
        self.space._space.contents.elasticIterations = 10
        self.static_body = Body(inf, inf)

        self.rooms = {}
        self.ents = set()
        self.chunks = set()
        self.player = None

        self.material = granite


    def add_to_pymunk(self):
        for room in self.rooms.itervalues():
            room.add_to_body(self.space, self.static_body)


    def add_chunk(self, chunk, position, angle=0):
        chunk.add_to_space(self.space, position, angle)
        self.chunks.add(chunk)


    def add_ent(self, ent, position, angle=0.0):
        ent.body.position = position
        ent.body.angle = angle
        self.space.add(ent.body)
        for shape in ent.shapes:
            self.space.add(shape)
        self.ents.add(ent)


    def tick(self, delta_t):
        if hasattr(self, 'player'):
            self.player.move()
        self.space.step(delta_t)
Esempio n. 38
0
 def add_to(self, space: pymunk.Space):
     space.add(self.body, self.shape)
     return self
Esempio n. 39
0
 def add_to(self, space: pymunk.Space):
     space.add(self.body)
     for shape in self.shape:
         space.add(shape)
     return self
Esempio n. 40
0
 def __init__(self, debug_draw=None):
     self.space = Space()
     self.debug_draw = debug_draw
Esempio n. 41
0
class World(object):

    def __init__(self):
        self.items = []
        self.words = []
        self.springs = []
        init_pymunk()
        self.space = Space()
        self.space.resize_static_hash()
        self.space.resize_active_hash()

    def add_item(self, item):
##        self.items.append(item)
        self.space.add(item.shape)
        self.space.add(item.body)

    def add_spring(self, spring):
        self.springs.append(spring)
        self.space.add(spring)


    def add_word(self, word):
        self.words.append(word)

    def update(self):
        self.space.step(1.0)
Esempio n. 42
0
class PhysicsWorld(object):

    def __init__(self):
        self.space = None

    def init(self):
        init_pymunk()
        self.space = Space()
        self.space.gravity = (0, -0.002)
        self.space.resize_static_hash()
        self.space.resize_active_hash()


    def add(self, item, position, static):
        item.body.position = position
        if static:
            self.space.add_static(item.shape)
        else:
            self.space.add(item.body)
            self.space.add(item.shape)
            if item.rest_angle_spring:
                self.space.add(item.rest_angle_spring)


    def update(self, items):
        for item in items.itervalues():
            item.physics.update()

        self.space.step(1)
Esempio n. 43
0
 def init(self):
     init_pymunk()
     self.space = Space()
     self.space.gravity = (0, -0.002)
     self.space.resize_static_hash()
     self.space.resize_active_hash()
Esempio n. 44
0
class Main(Scene):

	FADE_SPEED = 75

	def load(self):
		self.world_size = Size(3000, 3000)

		self.camera = Camera(self.size, self.world_size, 1000, 10)

		self._tool = None
		self.tool = None

		self.batch = graphics.Batch()
		self.background = CameraGroup(graphics.OrderedGroup(0), self.camera)
		self.foreground = CameraGroup(graphics.OrderedGroup(1), self.camera)
		self.playerg = CameraGroup(graphics.OrderedGroup(2), self.camera)
		self.world_ui = CameraGroup(graphics.OrderedGroup(3), self.camera)
		self.ui = graphics.OrderedGroup(2)

		self.space = Space()
		self.space.gravity = (0.0, 0.0)
		buffer = 100
		borders = Body()
		borders.position = (0, 0)
		left = Segment(borders, (-buffer, -buffer), (-buffer, self.world_size.height+buffer), buffer)
		bottom = Segment(borders, (-buffer, -buffer), (self.world_size.width+buffer, -buffer), buffer)
		right = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(self.world_size.width+buffer, -buffer), buffer)
		top = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(-buffer, self.world_size.height+buffer), buffer)
		self.space.add_static(left, bottom, right, top)

		self.stars = Stars(self.world_size, self.batch, self.background)

		self.asteroids = Asteroid.populate(50, 100, self.world_size, self.batch, self.foreground, self.space)

		if not self.asteroids:
			print("None of a particular resource on this asteroid belt, that'd be unfair. Trying again.")
			self.end(Main())
			return

		self.home_world = choice([asteroid for asteroid in self.asteroids if asteroid.position.y > self.world_size.height/4*3])
		self.home_world.type = "home"
		self.home_world.populated = True

		x, y = self.home_world.position
		self.camera.move(Vector(x-self.size.width/2, y-self.size.height/2))

		# Let's make stuff a bit more interesting.
		for asteroid in self.asteroids:
			if not asteroid.type == "home":
				asteroid.body.apply_impulse((triangular(-20000, 20000, 0), triangular(-20000, 20000, 0)))

		x, y = self.home_world.position
		self.player = Person(x+150, y+150, self.batch, self.playerg, self.space)
		self.mouse = x+150, y+150

		centre = Vector(self.size.width/2, self.size.height/2)
		image = centre_image(resource.image("logo.png"))
		self.logo = sprite.Sprite(image, centre.x, centre.y, batch=self.batch, group=self.ui)
		self.logo.opacity = 255
		self.fade = True
		self.faded = False

		planet = centre_image(resource.image("planet.png"))
		x = self.world_size.width/2
		y = planet.height/2
		self.planet_sprite = sprite.Sprite(planet, x, y, batch=self.batch, group=self.world_ui)
		self.win_box = BB(x-200, y-200, x+200, y+200)

		#self.tools = sorted([tool(self.space) for tool in Tool.__subclasses__()], key=attrgetter("order"), reverse=True)
		#self.buttons = {tool: Button(30, 30+number*50, tool.image, tool.description, self.use_tool(tool), self.ui, self.batch) for number, tool in enumerate(self.tools)}

		self.constraints = set()

	def use_tool(self, tool):
		"""For callback usage."""
		def f():
		  self.tool = tool
		return f

	@property
	def tool(self):
		return self._tool

	@tool.setter
	def tool(self, tool):
		if tool:
			if self._tool and not self._tool == tool:
				self._tool.end_selecting()
				self.buttons[self._tool].normal()
				self.window.set_mouse_cursor(self.window.get_system_mouse_cursor(self.window.CURSOR_DEFAULT))
				self.selecting = False
				self.selection = []
			self.window.set_mouse_cursor(self.window.get_system_mouse_cursor(self.window.CURSOR_CROSSHAIR))
			self.selecting = True
			self.buttons[tool].using()
		else:
			if self._tool:
				self._tool.end_selecting()
				self.buttons[self._tool].normal()
			self.window.set_mouse_cursor(self.window.get_system_mouse_cursor(self.window.CURSOR_DEFAULT))
			self.selecting = False
			self.selection = []
		self._tool = tool

	def key_pressed(self, symbol, modifiers):
		self.fade = True
		#self.camera.key_pressed(symbol)

	def key_released(self, symbol, modifiers):
		pass
		#self.camera.key_released(symbol)

	def mouse_pressed(self, x, y, key, modifiers):
		self.fade = True
		#for button in self.buttons.values():
		#	if button.point_over(x, y):
		#		button.callback()
		#		return
		if self.selecting:
			for asteroid in self.asteroids:
				clicked = self.camera.translate(x, y)
				if asteroid.point_over(*clicked):
					self.selection.append((asteroid, clicked))
					self.tool = self.tool.selection(self.selection, self.constraints)
					return
			self.tool = None
			return

	def mouse_motion(self, x, y, dx, dy):
		self.mouse = self.camera.translate(x, y)
		#for button in self.buttons.values():
	#		if button.point_over(x, y):
	#			button.on_mouse_over()
	#		else:
	#			button.on_mouse_leave()

	def mouse_drag(self, x, y, dx, dy, buttons, modifiers):
		if buttons & window.mouse.RIGHT:
			self.camera.mouse_dragged(dx, dy)

	def update(self, frame_time):
		self.constraints = {constraint for constraint in self.constraints if not constraint.update(self.batch, self.foreground)}
		if self.fade and not self.faded:
			self.logo.opacity -= Main.FADE_SPEED*frame_time
			if self.logo.opacity < 0:
				self.logo.opacity = 0
				del self.logo
				self.faded = True
		self.player.target = self.mouse
		self.player.update()
		x, y = self.player.body.position
		self.camera.x, self.camera.y = x-self.size.width/2, y-self.size.height/2
		self.camera.update(frame_time)
		self.space.step(1/60)
		if self.win_box.contains_vect(self.player.body.position):
			self.end(Win())

	def draw(self):
		self.batch.draw()
Esempio n. 45
0
	def load(self):
		self.world_size = Size(3000, 3000)

		self.camera = Camera(self.size, self.world_size, 1000, 10)

		self._tool = None
		self.tool = None

		self.batch = graphics.Batch()
		self.background = CameraGroup(graphics.OrderedGroup(0), self.camera)
		self.foreground = CameraGroup(graphics.OrderedGroup(1), self.camera)
		self.playerg = CameraGroup(graphics.OrderedGroup(2), self.camera)
		self.world_ui = CameraGroup(graphics.OrderedGroup(3), self.camera)
		self.ui = graphics.OrderedGroup(2)

		self.space = Space()
		self.space.gravity = (0.0, 0.0)
		buffer = 100
		borders = Body()
		borders.position = (0, 0)
		left = Segment(borders, (-buffer, -buffer), (-buffer, self.world_size.height+buffer), buffer)
		bottom = Segment(borders, (-buffer, -buffer), (self.world_size.width+buffer, -buffer), buffer)
		right = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(self.world_size.width+buffer, -buffer), buffer)
		top = Segment(borders, (self.world_size.width+buffer, self.world_size.height+buffer),
			(-buffer, self.world_size.height+buffer), buffer)
		self.space.add_static(left, bottom, right, top)

		self.stars = Stars(self.world_size, self.batch, self.background)

		self.asteroids = Asteroid.populate(50, 100, self.world_size, self.batch, self.foreground, self.space)

		if not self.asteroids:
			print("None of a particular resource on this asteroid belt, that'd be unfair. Trying again.")
			self.end(Main())
			return

		self.home_world = choice([asteroid for asteroid in self.asteroids if asteroid.position.y > self.world_size.height/4*3])
		self.home_world.type = "home"
		self.home_world.populated = True

		x, y = self.home_world.position
		self.camera.move(Vector(x-self.size.width/2, y-self.size.height/2))

		# Let's make stuff a bit more interesting.
		for asteroid in self.asteroids:
			if not asteroid.type == "home":
				asteroid.body.apply_impulse((triangular(-20000, 20000, 0), triangular(-20000, 20000, 0)))

		x, y = self.home_world.position
		self.player = Person(x+150, y+150, self.batch, self.playerg, self.space)
		self.mouse = x+150, y+150

		centre = Vector(self.size.width/2, self.size.height/2)
		image = centre_image(resource.image("logo.png"))
		self.logo = sprite.Sprite(image, centre.x, centre.y, batch=self.batch, group=self.ui)
		self.logo.opacity = 255
		self.fade = True
		self.faded = False

		planet = centre_image(resource.image("planet.png"))
		x = self.world_size.width/2
		y = planet.height/2
		self.planet_sprite = sprite.Sprite(planet, x, y, batch=self.batch, group=self.world_ui)
		self.win_box = BB(x-200, y-200, x+200, y+200)

		#self.tools = sorted([tool(self.space) for tool in Tool.__subclasses__()], key=attrgetter("order"), reverse=True)
		#self.buttons = {tool: Button(30, 30+number*50, tool.image, tool.description, self.use_tool(tool), self.ui, self.batch) for number, tool in enumerate(self.tools)}

		self.constraints = set()
Esempio n. 46
0
def initSpace():
  space = Space()
  space.gravity = Vec2d(0.0, -900.0)
  space.collision_bias = 0

  # attach collision handlers (defined at the end of the file)
  space.add_collision_handler(
    Rocket.collisionType,
    Platform.collisionType,
    begin = rocketHandler
  )
  space.add_collision_handler(
    Player.collisionType,
    Explosion.collisionType,
    begin = explosionHandler
  )
  space.add_collision_handler(
    Player.collisionType,
    Trigger.collisionType,
    begin    = triggerOn,
    separate = triggerOff
  )
  space.add_collision_handler(
    Player.collisionType,
    Platform.collisionType,
    pre_solve = notifyPlayer,
  )

  return space
Esempio n. 47
0
class World(object):

    def __init__(self):
        self.items = []
        init_pymunk()
        self.space = Space()
        self.space.gravity = (0, -0.5)
        self.space.resize_static_hash()
        self.space.resize_active_hash()
        self.leaves = []
        self.end_game = False
        

    def add_item(self, item):
        if isinstance(item, Bough):
            self.leaves.append(item)
        self.items.append(item)
        item.create_body()
        item.add_to_space(self.space)

    def remove_item(self, item):
        self.items.remove(item)
        item.remove_from_space(self.space)


    def update(self):
        self.space.step(0.5)
        for item in self.items:
            item.update()

    def remove_collided(self):
        for item in self.items:
            if item.status == "Collided":
                self.remove_item(item)
            
    def tick(self):
        max_limit = len(self.leaves) - 1
        if len(self.leaves) == 0:
                max_limit = 0 
##                print "End Level"
                self.end_game = True

        else:
##            print max_limit
            randno = random.randint(0, max_limit)
##            print randno
            leaf = self.leaves.pop(randno)
##            print leaf
            leaf.remove_from_tree(self.space)

    def add_cherry(self, x, y):
        cherry = Cherry(x, y)
        self.add_item(cherry)

    def add_owange(self, x, y):
        owange = Owange(x, y)
        self.add_item(owange)



    def add_collision_handler( self, 
                               col_typ1, 
                               col_typ2, 
                               begin=None, 
                               pre_solve=None,
                               post_solve=None, 
                               separate=None, 
                               **kwargs
        ):
        self.space.add_collision_handler(
            col_typ1, col_typ2,
            begin, pre_solve,
            post_solve, separate,
            **kwargs)