예제 #1
0
def getCartConstraints(cart_shape, track_shape, pole_shape):
    cart_width, cart_height = getShapeWidthHeight(cart_shape)
    track_width, _ = getShapeWidthHeight(track_shape)
    track_c_1 = pymunk.GrooveJoint(
        track_shape.body,
        cart_shape.body,
        (0, 0),  # Groove start on track
        (track_width, 0),  # Groove end on track
        # Body local anchor on cart
        (0, 0))
    # Make constraints as 'strong' as possible
    track_c_1.error_bias = 0.0001
    track_c_2 = pymunk.GrooveJoint(
        track_shape.body,
        cart_shape.body,
        (0, 0),  # Groove start on track
        (track_width, 0),  # Groove end on track
        # Body local anchor on cart
        (cart_width, 0))
    track_c_2.error_bias = 0.0001
    cart_pole_c = pymunk.PivotJoint(
        cart_shape.body,
        pole_shape.body,
        # Body local anchor on cart
        (cart_width / 2, cart_height / 2),
        # Body local achor on pole
        (0, 0))
    cart_pole_c.error_bias = 0.0001

    return (track_c_1, track_c_2, cart_pole_c)
예제 #2
0
 def _init_joints(self):
     # Creates the slider
     self.rails1 = pymunk.GrooveJoint(self.floor.body, self.cart.body, \
         self.pos_left + Vec2d(42.0,0), self.pos_right + Vec2d(-162.0,0), \
         self.cart.body.position - (35.0, 0.0))
     self.rails2 = pymunk.GrooveJoint(self.floor.body, self.cart.body, \
         self.pos_left + Vec2d(42.0,0), self.pos_right + Vec2d(-162.0,0), \
         self.cart.body.position + (35.0, 0.0))
     # Add the slider joints to the space
     self.space.add(self.rails1, self.rails2)
     # Creates the pole's pivot
     self.pivot = pymunk.PivotJoint(self.cart.body, self.pole.body, \
             self._cart_calc_xy_pos())
     # Add the pivot joint to the space
     self.space.add(self.pivot)
예제 #3
0
def add_player(space, pos):
    body = pymunk.Body(100, pymunk.inf)  ####Body
    body.position = pos
    bodyShape = pymunk.Circle(body, 20, (0, 0))
    bodyShape.friction = 0.1
    bodyShape.elasticity = 0.0
    bodyShape.filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS
                                          ^ 1)
    bodyShape.collision_type = 1
    space.add(body, bodyShape)

    contact = pymunk.Body(10, 1000)  ####Sole
    contact.position = (pos[0], pos[1] - 100)
    contactRadius = 2
    contactShape = pymunk.Segment(contact, (0, 0), (0, 100), 4)
    contactShape.filter = pymunk.ShapeFilter(categories=1)
    contactShape.friction = 3.5
    contactShape.elasticity = 0.0
    contactShape.collision_type = 2
    space.add(contact, contactShape)

    ##################Adding constraints to a system################
    slider = pymunk.GrooveJoint(contact, body, (0, -100), (0, 200), (0, 0))
    space.add(slider)
    spring = pymunk.DampedSpring(contact, body, (0, 0), (0, 0), 100, 20000,
                                 200)
    space.add(spring)

    return [body, contact, spring]
예제 #4
0
    def testGrooveJoint(self):
        a, b = p.Body(10, 10), p.Body(20, 20)
        a.position = 10, 10
        b.position = 20, 20
        j = p.GrooveJoint(a, b, (5, 0), (7, 7), (3, 3))

        self.assertEqual(j.anchr2, (3, 3))
        self.assertEqual(j.groove_a, (5, 0))
        self.assertEqual(j.groove_b, (7, 7))
예제 #5
0
 def __init__(self, space):
     super().__init__(10, pymunk.inf)
     self.position = 640, 100
     shape = pymunk.Segment(self, (-50, 0), (50, 0), 8)
     shape.elasticity = 0.98
     shape.collision_type = collision_types["player"]
     joint = pymunk.GrooveJoint(space.static_body, self, (100, 100),
                                (1180, 100), (0, 0))
     space.add(self, shape, joint)
예제 #6
0
    def create_wheel(self, wheel_side):
        if wheel_side not in ['rear', 'front']:
            raise Exception('Wheel position must be front or rear')
        wheel_objects = []

        wheel_mass = getattr(self, wheel_side + '_wheel_mass')
        wheel_radius = getattr(self, wheel_side + '_wheel_radius')
        wheel_position = getattr(self, wheel_side + '_wheel_position')
        wheel_friction = getattr(self, wheel_side + '_wheel_friction')
        wheel_elasticity = getattr(self, wheel_side + '_wheel_elasticity')
        wheel_damp_position = getattr(self,
                                      wheel_side + '_wheel_damp_position')
        wheel_damp_length = getattr(self, wheel_side + '_wheel_damp_length')
        wheel_damp_stiffness = getattr(self,
                                       wheel_side + '_wheel_damp_stiffness')
        wheel_damp_damping = getattr(self, wheel_side + '_wheel_damp_damping')

        wheel_body = pymunk.Body(
            wheel_mass,
            pymunk.moment_for_box(wheel_mass,
                                  (wheel_radius * 2, wheel_radius * 2)))
        wheel_body.position = (wheel_position[0] * self.x_modification,
                               wheel_position[1])

        wheel_shape = pymunk.Poly.create_box(
            wheel_body, (wheel_radius * 2, wheel_radius * 2))
        wheel_shape.filter = pymunk.ShapeFilter(group=self.car_group)
        wheel_shape.color = 255, 34, 150
        wheel_shape.friction = wheel_friction
        wheel_shape.elasticity = wheel_elasticity
        wheel_objects.append(wheel_shape)

        wheel_grove = pymunk.GrooveJoint(
            self.car_body, wheel_body,
            (wheel_damp_position[0] * self.x_modification,
             wheel_damp_position[1]),
            (wheel_damp_position[0] * self.x_modification,
             wheel_damp_position[1] - wheel_damp_length * 1.5), (0, 0))
        wheel_objects.append(wheel_grove)

        wheel_damp = pymunk.DampedSpring(
            wheel_body,
            self.car_body,
            anchor_a=(0, 0),
            anchor_b=(wheel_damp_position[0] * self.x_modification,
                      wheel_damp_position[1]),
            rest_length=wheel_damp_length,
            stiffness=wheel_damp_stiffness,
            damping=wheel_damp_damping)
        wheel_objects.append(wheel_damp)

        wheel_motor = None
        if (wheel_side == 'rear' and self.drive in [self.AWD, self.FR]) or (
                wheel_side == 'front' and self.drive in [self.AWD, self.FF]):
            wheel_motor = pymunk.SimpleMotor(wheel_body, self.car_body, 0)

        return wheel_body, wheel_motor, wheel_objects
예제 #7
0
 def testGroove(self):
     a, b = p.Body(10, 10), p.Body(20, 20)
     j = p.GrooveJoint(a, b, (1, 2), (3, 4), (0, 0))
     self.assertEqual(j.groove_a, (1, 2))
     self.assertEqual(j.groove_b, (3, 4))
     j.groove_a = (5, 6)
     j.groove_b = (7, 8)
     self.assertEqual(j.groove_a, (5, 6))
     self.assertEqual(j.groove_b, (7, 8))
예제 #8
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 = []
예제 #9
0
    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)
예제 #10
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
예제 #11
0
 def __init__(self, space, position):
     super().__init__(1, pymunk.inf)
     self.position = position.x, position.y + 18
     shape = pymunk.Circle(self, 10)
     shape.elasticity = 0.98
     shape.collision_type = collision_types["ball"]
     self.spc = space
     self.on_paddle = True
     self.velocity_func = self.constant_velocity
     self.joint = pymunk.GrooveJoint(space.static_body, self, (100, 118),
                                     (1180, 118), (0, 0))
     space.add(self, shape, self.joint)
예제 #12
0
    def testPickle(self):
        a, b = p.Body(10, 10), p.Body(20, 20)
        j = p.GrooveJoint(a, b, (1, 2), (3, 4), (5, 6))

        s = pickle.dumps(j)
        j2 = pickle.loads(s)

        self.assertEqual(j.groove_a, j2.groove_a)
        self.assertEqual(j.groove_b, j2.groove_b)
        self.assertEqual(j.anchor_b, j2.anchor_b)
        self.assertEqual(j.a.mass, j2.a.mass)
        self.assertEqual(j.b.mass, j2.b.mass)
예제 #13
0
파일: game.py 프로젝트: bitcraft/sanic
    def handle_moving_platform(self, shape):
        logger.info('loading moving platform %s', shape)

        assert (not shape.body.is_static)

        shape.layers = 3
        shape.collision_type = 0
        shape.body.velocity_func = ignore_gravity
        shape.body.moment = pymunk.inf

        shape.cache_bb()
        bb = shape.bb
        rect = pygame.Rect(
            (bb.left, bb.top, bb.right - bb.left, bb.top - bb.bottom))
        rect.normalize()

        height = 100
        anchor1 = shape.body.position
        anchor2 = shape.body.position - (0, height)

        joint = pymunk.GrooveJoint(self.space.static_body, shape.body, anchor1,
                                   anchor2, (0, 0))

        spring = pymunk.DampedSpring(self.space.static_body, shape.body,
                                     anchor2, (0, 0), height, 10000, 50)

        self.space.add(joint, spring)

        gids = [self.tmx_data.map_gid(i)[0][0] for i in (1, 2, 3)]
        colorkey = (255, 0, 255)
        tile_width = self.tmx_data.tilewidth

        s = pygame.Surface((rect.width, rect.height))
        s.set_colorkey(colorkey)
        s.fill(colorkey)

        tile = self.tmx_data.getTileImageByGid(gids[0])
        s.blit(tile, (0, 0))
        tile = self.tmx_data.getTileImageByGid(gids[1])
        for x in range(0, rect.width - tile_width, tile_width):
            s.blit(tile, (x, 0))
        tile = self.tmx_data.getTileImageByGid(gids[2])
        s.blit(tile, (rect.width - tile_width, 0))

        spr = sprite.BoxSprite(shape)
        spr.original_surface = s
        m = models.Basic()
        m.sprite = spr

        self.add_model(m)
예제 #14
0
def main():
    ### PyGame init
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont("Arial", 16)
    ### Physics stuff
    space = pymunk.Space()
    draw_options = pymunk.pygame_util.DrawOptions(screen)

    ### Game area
    # walls - the left-top-right walls
    static_lines = [
        pymunk.Segment(space.static_body, (50, 50), (50, 550), 2),
        pymunk.Segment(space.static_body, (50, 550), (550, 550), 2),
        pymunk.Segment(space.static_body, (550, 550), (550, 50), 2)
    ]
    for line in static_lines:
        line.color = THECOLORS['lightgray']
        line.elasticity = 1.0

    space.add(static_lines)

    # bottom - a sensor that removes anything touching it
    bottom = pymunk.Segment(space.static_body, (50, 50), (550, 50), 2)
    bottom.sensor = True
    bottom.collision_type = collision_types["bottom"]
    bottom.color = THECOLORS['red']

    def remove_first(arbiter, space, data):
        ball_shape = arbiter.shapes[0]
        space.remove(ball_shape, ball_shape.body)
        return True

    h = space.add_collision_handler(collision_types["ball"],
                                    collision_types["bottom"])
    h.begin = remove_first
    space.add(bottom)

    ### Player ship
    player_body = pymunk.Body(500, pymunk.inf)
    player_body.position = 300, 100

    player_shape = pymunk.Segment(player_body, (-50, 0), (50, 0), 8)
    player_shape.color = THECOLORS["red"]
    player_shape.elasticity = 1.0
    player_shape.collision_type = collision_types["player"]

    def pre_solve(arbiter, space, data):
        # We want to update the collision normal to make the bounce direction
        # dependent of where on the paddle the ball hits. Note that this
        # calculation isn't perfect, but just a quick example.
        set_ = arbiter.contact_point_set
        if len(set_.points) > 0:
            player_shape = arbiter.shapes[0]
            width = (player_shape.b - player_shape.a).x
            delta = (player_shape.body.position - set_.points[0].point_a.x).x
            normal = Vec2d(0, 1).rotated(delta / width / 2)
            set_.normal = normal
            set_.points[0].distance = 0
        arbiter.contact_point_set = set_
        return True

    h = space.add_collision_handler(collision_types["player"],
                                    collision_types["ball"])
    h.pre_solve = pre_solve

    # restrict movement of player to a straigt line
    move_joint = pymunk.GrooveJoint(space.static_body, player_body, (100, 100),
                                    (500, 100), (0, 0))
    space.add(player_body, player_shape, move_joint)
    global state
    # Start game
    setup_level(space, player_body)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "breakout.png")

            elif event.type == KEYDOWN and event.key == K_LEFT:
                player_body.velocity = (-600, 0)
            elif event.type == KEYUP and event.key == K_LEFT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player_body.velocity = (600, 0)
            elif event.type == KEYUP and event.key == K_RIGHT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_r:
                setup_level(space, player_body)
            elif event.type == KEYDOWN and event.key == K_SPACE:
                spawn_ball(space, player_body.position + (0, 40),
                           random.choice([(1, 10), (-1, 10)]))

        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        space.debug_draw(draw_options)

        state = []
        for x in space.shapes:
            s = "%s %s %s" % (x, x.body.position, x.body.velocity)
            state.append(s)

        ### Update physics
        fps = 60
        dt = 1. / fps
        space.step(dt)

        ### Info and flip screen
        screen.blit(
            font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]),
            (0, 0))
        screen.blit(
            font.render("Move with left/right arrows, space to spawn a ball",
                        1, THECOLORS["darkgrey"]), (5, height - 35))
        screen.blit(
            font.render("Press R to reset, ESC or Q to quit", 1,
                        THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
예제 #15
0
 def __init__(self, a, b, groove_a, groove_b, anchor_b):
     joint = pymunk.GrooveJoint(a, b, groove_a, groove_b, anchor_b)
     joint.collide_bodies = False
     space.add(joint)
예제 #16
0
def main():
    ### PyGame init
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont("Arial", 16)
    ### Physics stuff
    space = pymunk.Space()

    ### Game area
    # walls - the left-top-right walls
    static_lines = [
        pymunk.Segment(space.static_body, (50, 50), (50, 550), 5),
        pymunk.Segment(space.static_body, (50, 550), (550, 550), 5),
        pymunk.Segment(space.static_body, (550, 550), (550, 50), 5)
    ]
    for line in static_lines:
        line.color = THECOLORS['lightgray']
        line.elasticity = 1.0

    space.add(static_lines)

    # bottom - a sensor that removes anything touching it
    bottom = pymunk.Segment(space.static_body, (50, 50), (550, 50), 5)
    bottom.sensor = True
    bottom.collision_type = 1
    bottom.color = THECOLORS['red']

    def remove_first(space, arbiter):
        first_shape = arbiter.shapes[0]
        space.add_post_step_callback(space.remove, first_shape,
                                     first_shape.body)
        return True

    space.add_collision_handler(0, 1, begin=remove_first)
    space.add(bottom)

    ### Player ship
    player_body = pymunk.Body(500, pymunk.inf)
    player_shape = pymunk.Circle(player_body, 35)
    player_shape.color = THECOLORS["red"]
    player_shape.elasticity = 1.0
    player_body.position = 300, 100
    # restrict movement of player to a straigt line
    move_joint = pymunk.GrooveJoint(space.static_body, player_body, (100, 100),
                                    (500, 100), (0, 0))
    space.add(player_body, player_shape, move_joint)
    global state
    # Start game
    setup_level(space, player_body)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, "breakout.png")

            elif event.type == KEYDOWN and event.key == K_LEFT:
                player_body.velocity = (-600, 0)
            elif event.type == KEYUP and event.key == K_LEFT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player_body.velocity = (600, 0)
            elif event.type == KEYUP and event.key == K_RIGHT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_r:
                setup_level(space, player_body)
            elif event.type == KEYDOWN and event.key == K_SPACE:
                spawn_ball(space, player_body.position + (0, 40),
                           random.choice([(1, 1), (-1, 1)]))

        ### Clear screen
        screen.fill(THECOLORS["black"])

        ### Draw stuff
        pymunk.pygame_util.draw(screen, space)

        state = []
        for x in space.shapes:
            s = "%s %s %s" % (x, x.body.position, x.body.velocity)
            state.append(s)
        ### Update physics
        fps = 60
        dt = 1. / fps
        space.step(dt)
        ### Info and flip screen
        screen.blit(
            font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]),
            (0, 0))
        screen.blit(
            font.render("Move with left/right arrows, space to spawn a ball",
                        1, THECOLORS["darkgrey"]), (5, height - 35))
        screen.blit(
            font.render("Press R to reset, ESC or Q to quit", 1,
                        THECOLORS["darkgrey"]), (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
예제 #17
0
def fill_space(space, custom_color=(255, 255, 0, 255)):
    captions = []

    ### Static
    captions.append(((50, 680), "Static Shapes"))

    #Static Segments
    segments = [
        pymunk.Segment(space.static_body, (10, 400), (10, 600), 0),
        pymunk.Segment(space.static_body, (20, 400), (20, 600), 1),
        pymunk.Segment(space.static_body, (30, 400), (30, 600), 3),
        pymunk.Segment(space.static_body, (50, 400), (50, 600), 5)
    ]
    space.add(segments)

    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (40, 630)
    b.angle = 3.14 / 7
    s = pymunk.Segment(b, (-30, 0), (30, 0), 2)
    space.add(s)

    # Static Circles
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120, 630)
    s = pymunk.Circle(b, 10)
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120, 630)
    s = pymunk.Circle(b, 10, (-30, 0))
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120, 560)
    b.angle = 3.14 / 4
    s = pymunk.Circle(b, 40)
    space.add(s)

    # Static Polys
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120, 460)
    b.angle = 3.14 / 4
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)])
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (120, 500)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)], t, radius=3)
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (50, 430)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -50), (50, 0), (30, 50), (-30, 50), (-50, 0)], t)
    space.add(s)

    ### Kinematic
    captions.append(((220, 680), "Kinematic Shapes"))

    # Kinematic Segments
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    segments = [
        pymunk.Segment(b, (180, 400), (180, 600), 0),
        pymunk.Segment(b, (190, 400), (190, 600), 1),
        pymunk.Segment(b, (200, 400), (200, 600), 3),
        pymunk.Segment(b, (220, 400), (220, 600), 5)
    ]
    space.add(segments)

    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (210, 630)
    b.angle = 3.14 / 7
    s = pymunk.Segment(b, (-30, 0), (30, 0), 2)
    space.add(s)

    # Kinematic Circles
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290, 630)
    s = pymunk.Circle(b, 10)
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290, 630)
    s = pymunk.Circle(b, 10, (-30, 0))
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290, 560)
    b.angle = 3.14 / 4
    s = pymunk.Circle(b, 40)
    space.add(s)

    # Kinematic Polys
    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290, 460)
    b.angle = 3.14 / 4
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)])
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (290, 500)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)], t, radius=3)
    space.add(s)

    b = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
    b.position = (230, 430)
    t = pymunk.Transform(ty=-100)
    s = pymunk.Poly(b, [(0, -50), (50, 0), (30, 50), (-30, 50), (-50, 0)], t)
    space.add(s)

    ### Dynamic
    captions.append(((390, 680), "Dynamic Shapes"))

    #Dynamic Segments
    b = pymunk.Body(1, 1)
    segments = [
        pymunk.Segment(b, (350, 400), (350, 600), 0),
        pymunk.Segment(b, (360, 400), (360, 600), 1),
        pymunk.Segment(b, (370, 400), (370, 600), 3),
        pymunk.Segment(b, (390, 400), (390, 600), 5),
    ]
    space.add(segments)

    b = pymunk.Body(1, 1)
    b.position = (380, 630)
    b.angle = 3.14 / 7
    s = pymunk.Segment(b, (-30, 0), (30, 0), 2)
    space.add(s)

    # Dynamic Circles
    b = pymunk.Body(1, 1)
    b.position = (460, 630)
    s = pymunk.Circle(b, 10)
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (460, 630)
    s = pymunk.Circle(b, 10, (-30, 0))
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (460, 560)
    b.angle = 3.14 / 4
    s = pymunk.Circle(b, 40)
    space.add(s)

    # Dynamic Polys

    b = pymunk.Body(1, 1)
    b.position = (460, 460)
    b.angle = 3.14 / 4
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)])
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (460, 500)
    s = pymunk.Poly(b, [(0, -25), (30, 25), (-30, 25)],
                    pymunk.Transform(ty=-100),
                    radius=3)
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (400, 430)
    s = pymunk.Poly(b, [(0, -50), (50, 0), (30, 50), (-30, 50), (-50, 0)],
                    pymunk.Transform(ty=-100))
    space.add(s)

    ###Constraints

    # PinJoints
    captions.append(((560, 660), "Pin Joints"))
    a = pymunk.Body(1, 1)
    a.position = (550, 600)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (650, 620)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PinJoint(a, b)
    space.add(sa, sb, a, b, j)

    a = pymunk.Body(1, 1)
    a.position = (550, 550)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (650, 570)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PinJoint(a, b, anchor_a=(0, 20), anchor_b=(0, -20))
    space.add(sa, sb, a, b, j)

    # SlideJoints
    captions.append(((560, 490), "Slide Joint"))
    a = pymunk.Body(1, 1)
    a.position = (550, 430)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (650, 450)
    sb = pymunk.Circle(b, 20)
    j = pymunk.SlideJoint(a,
                          b,
                          anchor_a=(0, 20),
                          anchor_b=(0, -20),
                          min=10,
                          max=30)
    space.add(sa, sb, a, b, j)

    # PivotJoints
    captions.append(((560, 390), "Pivot Joint"))
    a = pymunk.Body(1, 1)
    a.position = (550, 330)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (650, 350)
    sb = pymunk.Circle(b, 20)
    j = pymunk.PivotJoint(a, b, (600, 320))
    space.add(sa, sb, a, b, j)

    # GrooveJoints
    captions.append(((760, 660), "Groove Joint"))
    a = pymunk.Body(1, 1)
    a.position = (750, 600)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (850, 620)
    sb = pymunk.Circle(b, 20)
    j = pymunk.GrooveJoint(a, b, (790, 610), (790, 620), (840, 620))
    space.add(sa, sb, a, b, j)

    # DampedSpring
    captions.append(((760, 550), "Damped Spring"))
    a = pymunk.Body(1, 1)
    a.position = (750, 480)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (850, 500)
    sb = pymunk.Circle(b, 20)
    j = pymunk.DampedSpring(a, b, (0, 0), (0, 10), 100, 1, 1)
    space.add(sa, sb, a, b, j)

    # DampedRotarySpring
    captions.append(((740, 430), "Damped Rotary Spring"))
    a = pymunk.Body(1, 1)
    a.position = (750, 350)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (850, 380)
    sb = pymunk.Circle(b, 20)
    j = pymunk.DampedRotarySpring(a, b, 10, 1, 1)
    space.add(sa, sb, a, b, j)

    # RotaryLimitJoint
    captions.append(((740, 300), "Rotary Limit Joint"))
    a = pymunk.Body(1, 1)
    a.position = (750, 220)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (850, 250)
    sb = pymunk.Circle(b, 20)
    j = pymunk.RotaryLimitJoint(a, b, 1, 2)
    b.angle = 3
    space.add(sa, sb, a, b, j)

    # RatchetJoint
    captions.append(((740, 170), "Ratchet Joint"))
    a = pymunk.Body(1, 1)
    a.position = (750, 100)
    sa = pymunk.Circle(a, 20)
    b = pymunk.Body(1, 1)
    b.position = (850, 120)
    sb = pymunk.Circle(b, 20)
    j = pymunk.RatchetJoint(a, b, 1, 0.1)
    b.angle = 3
    space.add(sa, sb, a, b, j)

    # GearJoint and SimpleMotor omitted since they are similar to the already
    # added joints

    # TODO: more stuff here :)

    ### Other

    # Objects in custom color
    captions.append(((150, 150), "Custom Color (static & dynamic)"))
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (200, 200)
    s = pymunk.Circle(b, 40)
    s.color = custom_color
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (300, 200)
    s = pymunk.Circle(b, 40)
    s.color = custom_color
    space.add(s)

    # Collision
    captions.append(((450, 150), "Collisions"))
    b = pymunk.Body(body_type=pymunk.Body.STATIC)
    b.position = (470, 200)
    s = pymunk.Circle(b, 40)
    space.add(s)

    b = pymunk.Body(1, 1)
    b.position = (500, 250)
    s = pymunk.Circle(b, 40)
    space.add(s)

    # Sleeping
    captions.append(((50, 150), "Sleeping"))
    b = pymunk.Body(1, 1)
    b.position = (75, 200)
    space.sleep_time_threshold = 0.01
    s = pymunk.Circle(b, 40)
    space.add(s, b)
    b.sleep()
    space.step(0.000001)

    return captions
예제 #18
0
def main():
    driver_type = 0
    full_screen = False
    stencil_buffer = False
    vsync = False
    run_app = True

    from video_choice_dialog import has_pywingui
    if has_pywingui:
        from video_choice_dialog import ChoiceDialog, IDOK, IDCANCEL
        dialog = ChoiceDialog()
        dialog.driver_type = driver_type
        dialog.full_screen = full_screen
        dialog.stencil_buffer = stencil_buffer
        dialog.vsync = vsync
        dialogResult = dialog.DoModal()
        if dialogResult == IDOK:
            driver_type = dialog.driver_type
            full_screen = dialog.full_screen
            stencil_buffer = dialog.stencil_buffer
            vsync = dialog.vsync
        elif dialogResult == IDCANCEL:
            run_app = False

    if run_app:
        global pymunk, irr, Vec2d, color_darkgray

        import math, random
        import os

        import pymunk
        from pymunk import Vec2d

        import pyirrlicht as irr

        ### Physics stuff
        space = pymunk.Space()

        ### Game area
        # walls - the left-top-right walls
        static_lines = [
            pymunk.Segment(space.static_body, (50, 50), (50, 550), 5),
            pymunk.Segment(space.static_body, (50, 550), (550, 550), 5),
            pymunk.Segment(space.static_body, (550, 550), (550, 50), 5)
        ]
        for line in static_lines:
            line.color = irr.SColor(255, 200, 200, 200)
            line.elasticity = 1.0

        space.add(static_lines)

        # bottom - a sensor that removes anything touching it
        bottom = pymunk.Segment(space.static_body, (50, 50), (550, 50), 5)
        bottom.sensor = True
        bottom.collision_type = 1
        bottom.color = irr.SColor(255, 255, 0, 0)

        def remove_first(space, arbiter):
            first_shape = arbiter.shapes[0]
            space.add_post_step_callback(space.remove, first_shape,
                                         first_shape.body)
            return True

        space.add_collision_handler(0, 1, begin=remove_first)
        space.add(bottom)

        ### Player ship
        player_body = pymunk.Body(500, pymunk.inf)
        player_shape = pymunk.Circle(player_body, 35)
        player_shape.color = irr.SColor(255, 255, 0, 0)
        player_shape.elasticity = 1.0
        player_body.position = 300, 100
        # restrict movement of player to a straigt line
        move_joint = pymunk.GrooveJoint(space.static_body, player_body,
                                        (100, 100), (500, 100), (0, 0))
        space.add(player_body, player_shape, move_joint)

        # Start game
        setup_level(space, player_body)

        ### pyirrlicht init
        class UserIEventReceiver(irr.IEventReceiver):
            #~ mouse_button_down = False
            #~ mouse_position = Vec2d(0, 0)
            KeyIsDown = {}
            for key in range(irr.KEY_KEY_CODES_COUNT):
                KeyIsDown[key] = False

            def OnEvent(self, evt):
                event = irr.SEvent(evt)
                self.mouse_button_down = False
                self.mouse_position = Vec2d(0, 0)
                if event.EventType is irr.EET_KEY_INPUT_EVENT:
                    self.KeyIsDown[
                        event.KeyInput.Key] = event.KeyInput.PressedDown
                    if event.KeyInput.Key == irr.KEY_LEFT:
                        if event.KeyInput.PressedDown:
                            player_body.velocity = (-600, 0)
                        else:
                            player_body.velocity = 0, 0
                    elif event.KeyInput.Key == irr.KEY_RIGHT:
                        if event.KeyInput.PressedDown:
                            player_body.velocity = (600, 0)
                        else:
                            player_body.velocity = 0, 0
                    elif event.KeyInput.Key == irr.KEY_KEY_R:
                        setup_level(space, player_body)
                #~ elif event.EventType is irr.EET_MOUSE_INPUT_EVENT:
                #~ if event.MouseInput.EventType == irr.EMIE_LMOUSE_PRESSED_DOWN:
                #~ self.mouse_button_down = True
                #~ self.mouse_position.x = event.MouseInput.X
                #~ self.mouse_position.y = event.MouseInput.Y
                return False

            def IsKeyDown(self, keyCode):
                return self.KeyIsDown[keyCode]

        if not driver_type:
            driver_type = irr.EDT_SOFTWARE

        window_size = irr.dimension2du(width, height)
        device = irr.createDevice(driver_type, window_size, 16, full_screen,
                                  stencil_buffer, vsync)

        if device:
            device.setWindowCaption('pyMunk breakout game')
            device.setResizable(True)
            video_driver = device.getVideoDriver()
            gui_environment = device.getGUIEnvironment()
            font = irr.CGUITTFont(
                gui_environment, os.environ['SYSTEMROOT'] + '/Fonts/arial.ttf',
                16)
            if not font:
                font = gui_environment.getBuiltInFont()

            space_drawer = SpaceDrawer(space, video_driver)

            i_event_receiver = UserIEventReceiver()
            device.setEventReceiver(i_event_receiver)
            color_white = irr.SColor(255, 255, 255, 255)
            color_darkgray = irr.SColor(255, 100, 100, 100)
            color_screen = irr.SColor(255, 0, 0, 0)
            ticks = 60
            dt = 1. / ticks
            while device.run():
                if device.isWindowActive():
                    if i_event_receiver.IsKeyDown(irr.KEY_ESCAPE):
                        break
                    elif i_event_receiver.IsKeyDown(irr.KEY_SPACE):
                        spawn_ball(space, player_body.position + (0, 40),
                                   random.choice([(1, 1), (-1, 1)]))

                    ### Clear screen
                    if video_driver.beginScene(True, True, color_screen):

                        ### Draw stuff
                        space_drawer.draw()

                        ### Info
                        font.draw("fps: %d" % video_driver.getFPS(),
                                  irr.recti(0, 0, 100, 20), color_white)
                        font.draw(
                            "Move with left/right arrows, space to spawn a ball",
                            irr.recti(5, height - 35, 300, 20), color_darkgray)
                        font.draw("Press R to reset, ESC or Q to quit",
                                  irr.recti(5, height - 20, 300, 20),
                                  color_darkgray)

                        video_driver.endScene()

                    ### Update physics
                    if device.getTimer().getTime() > ticks:
                        space.step(dt)

                    device.sleep(1)
                else:
                    device._yield()

            device.closeDevice()
예제 #19
0
파일: arc_0.2.py 프로젝트: ElouLeol/arc
def main():
    main_run = True
    while main_run:

        background = random.choice(level_color)

        pygame.init()
        screen = pygame.display.set_mode((w, he))
        clock = pygame.time.Clock()
        running = True
        font = pygame.font.SysFont("Arial", 16)
        font_end = pygame.font.SysFont("Arial", 50)

        space = pymunk.Space()
        draw_options = pymunk.pygame_util.DrawOptions(screen)

        #Отрисовка, добавление полей
        static_lines = [
            pymunk.Segment(space.static_body, (50, 50), (50, 550), 2),
            pymunk.Segment(space.static_body, (50, 550), (550, 550), 2),
            pymunk.Segment(space.static_body, (550, 550), (550, 50), 2)
        ]
        for line in static_lines:
            line.color = THECOLORS['lightgray']
            line.elasticity = 1.0
        space.add(static_lines)  #Добавление в space

        #Создание нижней границы и изменение её свойств
        bottom = pymunk.Segment(space.static_body, (50, 50), (550, 50), 2)
        bottom.sensor = True
        bottom.collision_type = collision_types['bottom']
        bottom.color = THECOLORS['red']

        #Функция обработчика столкновений для нижней границы, удаляем всё что прикаснётся к ней
        def remove_first(arbiter, space, data):
            global score
            if score < 0:
                score = 0
            else:
                score -= 5

            ball_shape = arbiter.shapes[0]
            space.remove(ball_shape, ball_shape.body)
            return True

        h = space.add_collision_handler(collision_types['ball'],
                                        collision_types['bottom'])
        h.begin = remove_first
        space.add(bottom)

        player_body = pymunk.Body(500, pymunk.inf)
        player_body.position = 300, 100
        player_shape = pymunk.Segment(player_body, (-50, 0), (50, 0), 8)
        player_shape.color = THECOLORS['red']
        player_shape.elasticity = 1.0
        player_shape.collision_type = collision_types['player']

        def pre_solve(arbiter, space, data):
            set_ = arbiter.contact_point_set
            if len(set_.points) > 0:
                player_shape = arbiter.shapes[0]
                w_ = (player_shape.b - player_shape.a).x
                delta = (player_shape.body.position -
                         set_.points[0].point_a.x).x
                normal = Vec2d(0, 1).rotated(delta / w_ / 2)
                set_.normal = normal
                set_.points[0].distance = 0
            arbiter.contact_point_set = set_
            return True

        h = space.add_collision_handler(collision_types["player"],
                                        collision_types["ball"])
        h.pre_solve = pre_solve
        #Ограничение движения игрока
        move_joint = pymunk.GrooveJoint(
            space.static_body, player_body, (100, 100), (500, 100),
            (0, 0))  #Добавляем объект который будет ограничивать движение
        space.add(player_body, player_shape, move_joint)
        global state
        #Старт
        setup_level(space, player_body)

        pygame.mixer.music.load('PFW.mp3')
        pygame.mixer.music.play(-1)

        #Главный цикл
        while running:
            global win_cond_2
            global win_cond
            global score
            global level_count
            global cheat_win

            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                    main_run = False
                elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                    running = False
                    main_run = False
                elif event.type == KEYDOWN and event.key == K_p:
                    pygame.image.save(screen, "breakout.png")
                elif event.type == KEYDOWN and event.key == K_LEFT:
                    player_body.velocity = (-600, 0)
                elif event.type == KEYUP and event.key == K_LEFT:
                    player_body.velocity = 0, 0

                elif event.type == KEYDOWN and event.key == K_RIGHT:
                    player_body.velocity = (600, 0)
                elif event.type == KEYUP and event.key == K_RIGHT:
                    player_body.velocity = 0, 0

                elif event.type == KEYDOWN and event.key == K_n:
                    #setup_level(space, player_body)
                    win_cond_2 = 0
                    #win_cond=0
                    score = 0
                    level_count = 0
                    running = False
                elif event.type == KEYDOWN and event.key == K_w:
                    cheat_win = True

                elif event.type == KEYDOWN and event.key == K_u:
                    global lock_balls
                    lock_balls = 0

                if event.type == KEYDOWN and event.key == K_l:
                    screen.blit(font.render(('Пауза'), 8, THECOLORS["white"]),
                                (500, 20))
                    print('Пауза')
                    while 1:
                        event2 = pygame.event.wait()
                        if event2.type == KEYDOWN and event2.key == K_l:
                            #screen.blit(font.render(('Пауза'), 8, THECOLORS["black"]), (500,20))
                            break

                elif event.type == KEYDOWN and event.key == K_SPACE:
                    spawn_ball(space, player_body.position + (0, 40),
                               random.choice([(1, 10), (-1, 10)]))

            screen.fill(background)

            space.debug_draw(draw_options)
            global win
            if win_cond == 0 or cheat_win:
                print('if')
                if score >= win_cond_2 or cheat_win:
                    screen.blit(
                        font_end.render('ПОБЕДА!', 50, THECOLORS['green']),
                        (he // 2 - 150, w // 2 - 50))
                    screen.blit(
                        font.render(('press "R" to restart'), 8,
                                    THECOLORS["white"]),
                        (he // 2 - 150, w // 2))
                    screen.blit(
                        font.render(('Пройдено уровней: ' + str(level_count)),
                                    8, THECOLORS["white"]), (he // 2, w // 2))
                    keystate = pygame.key.get_pressed()
                    if keystate[pygame.K_r]:
                        win = True
                        level_count += 1
                        cheat_win = False
                        running = False
                        if score >= 30:
                            score -= 15
                        if score >= 50:
                            score -= 25
                else:
                    screen.blit(
                        font_end.render('ПОРАЖЕНИЕ!', 50, THECOLORS['red']),
                        (he // 2 - 150, w // 2 - 50))
                    screen.blit(
                        font.render(str(round(score)), 8, THECOLORS["white"]),
                        (he // 2 - 150, w // 2))
                    keystate = pygame.key.get_pressed()
                    if keystate[pygame.K_n]:
                        win = False

            #FPS
            fps = 60
            dt = 1. / fps
            space.step(dt)
            #Пишем текст
            screen.blit(
                font.render("FPS: " + str(clock.get_fps()), 1,
                            THECOLORS["white"]), (0, 0))
            screen.blit(
                font.render(
                    "Управление кнопками влево вправо , пробел для того чтобы создать новый мяч",
                    1, THECOLORS["darkgrey"]), (5, he - 35))
            screen.blit(
                font.render("N - рестарт , ESC или Q для выхода ", 1,
                            THECOLORS["red"]), (5, he - 20))

            screen.blit(
                font.render(
                    str(score) + ' осталось: ' + str(win_cond), 8,
                    THECOLORS["white"]), (55, 55))
            screen.blit(
                font.render(('Пройдено уровней: ' + str(level_count)), 8,
                            THECOLORS["white"]), (300, 520))
            screen.blit(font.render(str(win_cond_2), 8, THECOLORS["white"]),
                        (500, 55))

            pygame.display.flip()
            clock.tick(fps)
예제 #20
0
def main():

    running = True

    pygame.init()
    screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    pygame.display.set_caption('SwingUp!')
    clock = pygame.time.Clock()

    ### init our pymunk space and apply gravity to it
    space = pymunk.Space()
    space.gravity = (0.0, -4000)

    # to prevent the pendulum from blowing up, we introduce
    # a system wide damping
    space.damping = 0.6

    draw_options = pymunk.pygame_util.DrawOptions(screen)

    agent_body, agent_shape = setup_agent()
    pole_body, pole_shape = setup_pole()

    move_x_joint = pymunk.GrooveJoint(space.static_body, agent_body,
                                      (0, DISPLAY_HEIGHT / 2),
                                      (DISPLAY_WIDTH, DISPLAY_HEIGHT / 2),
                                      (0, 0))
    pj = pymunk.PivotJoint(pole_body, agent_body, (
        0,
        75,
    ), (0, 0))
    pj.distance = 0
    pj.error_bias = pow(1.0 - 1.0, 60.0)
    pj.collide_bodies = False
    space.add(agent_body, agent_shape, pole_body, pole_shape, move_x_joint, pj)

    keys = {'left': False, 'right': False}

    force_direction = 0

    # We want to apply a constant force to our dynamic cart as we are keeping
    # our respective arrow key pressed. If we were to apply this force in our
    # event for loop, this would lead us to a situation in which the force
    # would be applied in one single step only as we are solely tracking
    # keyup / keydown behaviours for performance reasons. Hence, we rather
    # need to keep track on which action should be executed and perform on
    # every step, meaning after our for event loop which figures out whether
    # something changed.
    #
    # To achieve this behaviour, we introduce a variable named `force_direction`
    # which will act as an indicator if we need to apply force and if so,
    # as a multiplier in order to apply the right direction:
    #
    #             y ^
    #               |
    #               |
    #               |
    #  ------------------------- > x
    #  <- negative  |  positive ->
    #  action= - 1  |   action = 1
    #               |
    #
    #           action = 0
    #
    # + If we do not have any user input, action is 0
    # + If the user presses `<` , action is -1
    # + If the user presses `>` , action is 1
    # + If the user releases `<` or `>` a and no other key is pressed
    #   action is 0
    # + If the user releases `<` or `>` and the opposite direction key
    #   meaning `>` or `<` is pressed, the action is inverted:
    #   -1 -> 1 | 1 -> -1

    while running:

        for event in pygame.event.get():
            if event.type == QUIT or \
                event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
                break

            elif event.type == KEYDOWN and event.key == K_LEFT:
                keys['left'] = True
                force_direction = -1

            elif event.type == KEYUP and event.key == K_LEFT:
                keys['left'] = False
                if not keys['right']:
                    force_direction = 0
                else:
                    force_direction = 1

            elif event.type == KEYDOWN and event.key == K_RIGHT:
                keys['right'] = True
                force_direction = 1

            elif event.type == KEYUP and event.key == K_RIGHT:
                keys['right'] = False
                if not keys['left']:
                    force_direction = 0
                else:
                    force_direction = -1

        f = (force_direction * 7000, 0)

        agent_body.apply_force_at_local_point(f, agent_body.position)

        # NOTE: `step` HAS to be float/double
        space.step(1 / FRAMERATE)

        screen.fill(WHITE)
        space.debug_draw(draw_options)

        pygame.display.flip()
        clock.tick(FRAMERATE)
예제 #21
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    font = pygame.font.SysFont('Arial', 16)

    space = pymunk.Space()
    draw_options = pymunk.pygame_util.DrawOptions(screen)

    # walls
    static_lines = [
        pymunk.Segment(space.static_body, (50, 50), (50, 550), 2),
        pymunk.Segment(space.static_body, (50, 550), (550, 550), 2),
        pymunk.Segment(space.static_body, (550, 550), (550, 50), 2)
    ]
    for line in static_lines:
        line.color = THECOLORS['lightgray']
        line.elasticity = 1.0

    space.add(static_lines)

    # bottom sensor
    bottom = pymunk.Segment(space.static_body, (50, 50), (550, 50), 2)
    bottom.sensor = True
    bottom.collision_type = collision_types['bottom']
    bottom.color = THECOLORS['red']

    def remove_first(arbiter, space, data):
        ball_shape = arbiter.shapes[0]
        space.remove(ball_shape, ball_shape.body)
        return True

    h = space.add_collision_handler(collision_types['ball'],
                                    collision_types['bottom'])
    h.begin = remove_first
    space.add(bottom)

    # player
    player_body = pymunk.Body(500, pymunk.inf)
    player_body.position = 300, 100

    player_shape = pymunk.Segment(player_body, (-50, 0), (50, 0), 8)
    player_shape.color = THECOLORS['red']
    player_shape.elasticity = 1.0
    player_shape.collision_type = collision_types['player']

    def pre_solve(arbiter, space, data):
        set_ = arbiter.contact_point_set
        if len(set_.points) > 0:
            player_shape = arbiter.shapes[0]
            width = (player_shape.b - player_shape.a).x
            delta = (player_shape.body.position - set_.points[0].point_a.x).x
            normal = Vec2d(0, 1).rotated(delta / width / 2)
            set_.normal = normal
            set_.points[0].distance = 0
        arbiter.contact_point_set = set_
        return True

    h = space.add_collision_handler(collision_types['player'],
                                    collision_types['ball'])
    h.pre_solve = pre_solve

    # restricting movement of player to a straight line
    move_joint = pymunk.GrooveJoint(space.static_body, player_body, (100, 100),
                                    (500, 100), (0, 0))
    space.add(player_body, player_shape, move_joint)
    global state

    setup_level(space, player_body)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]):
                running = False
            elif event.type == KEYDOWN and event.key == K_p:
                pygame.image.save(screen, 'breakout.png')

            elif event.type == KEYDOWN and event.key == K_LEFT:
                player_body.velocity = (-600, 0)
            elif event.type == KEYUP and event.key == K_LEFT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_RIGHT:
                player_body.velocity = (600, 0)
            elif event.type == KEYUP and event.key == K_RIGHT:
                player_body.velocity = 0, 0

            elif event.type == KEYDOWN and event.key == K_r:
                setup_level(space, player_body)
            elif event.type == KEYDOWN and event.key == K_SPACE:
                spawn_ball(space, player_body.position + (0, 40),
                           random.choice([(1, 10), (-1, 10)]))

        screen.fill(THECOLORS['black'])
        space.debug_draw(draw_options)

        state = []
        for x in space.shapes:
            s = '%s %s %s' % (x, x.body.position, x.body.velocity)
            state.append(s)

        fps = 60.0
        dt = 1. / fps
        space.step(dt)

        screen.blit(
            font.render(f'fps: {str(clock.get_fps())}', 1, THECOLORS['white']),
            (0, 0))
        screen.blit(
            font.render('Move with arrow keys, space to spawn a ball', 1,
                        THECOLORS['darkgrey']), (5, height - 35))
        screen.blit(
            font.render('Press R to reset, ESC or Q to quit', 1,
                        THECOLORS['darkgrey']), (5, height - 20))

        pygame.display.flip()
        clock.tick(fps)
예제 #22
0
b2 = add_ball(space, (150, 60), box_offset)
c = pymunk.SlideJoint(b1, b2, (20, 0), (-20, 0), 40, 80)
txts[box_offset] = inspect.getdoc(c)
space.add(c)

box_offset = box_size * 2, 0
b1 = add_ball(space, (50, 60), box_offset)
b2 = add_ball(space, (150, 60), box_offset)
c = pymunk.PivotJoint(b1, b2, Vec2d(box_offset) + (100, 60))
txts[box_offset] = inspect.getdoc(c)
space.add(c)

box_offset = box_size * 3, 0
b1 = add_ball(space, (50, 60), box_offset)
b2 = add_ball(space, (150, 60), box_offset)
c = pymunk.GrooveJoint(b1, b2, (50, 50), (50, -50), (-50, 0))
txts[box_offset] = inspect.getdoc(c)
space.add(c)

box_offset = box_size * 4, 0
b1 = add_ball(space, (50, 60), box_offset)
b2 = add_ball(space, (150, 60), box_offset)
c = pymunk.DampedSpring(b1, b2, (30, 0), (-30, 0), 20, 5, 0.3)
txts[box_offset] = inspect.getdoc(c)
space.add(c)

box_offset = box_size * 5, 0
b1 = add_bar(space, (50, 80), box_offset)
b2 = add_bar(space, (150, 80), box_offset)
# Add some joints to hold the circles in place.
space.add(
예제 #23
0
 def testAnchor(self):
     a, b = p.Body(10, 10), p.Body(20, 20)
     j = p.GrooveJoint(a, b, (0, 0), (0, 0), (1, 2))
     self.assertEqual(j.anchor_b, (1, 2))
     j.anchor_b = (3, 4)
     self.assertEqual(j.anchor_b, (3, 4))
예제 #24
0
 def create_groove_joint(self, bodyA, bodyB):
     relative_pos = bodyB.body.position - bodyA.body.position
     joint = pymunk.GrooveJoint(bodyA.body, bodyB.body, (0, 0),
                                relative_pos * 2, (0, 0))
     joint.max_force = 1500000
     return joint