Exemplo n.º 1
0
 def __init__(self, p, *args, d=2, color=None, friction=1):
     p = Vec2d(p)
     for v in args:
         shape = pymunk.Segment(b0, p, p + v, d)
         shape.color = LIGHTGRAY
         shape.elasticity = 1
         shape.friction = friction
         if color != None:
             shape.color = color
         p = p + v
         space.add(shape)
Exemplo n.º 2
0
def reset_bodies(space):
    for body in space.bodies:
        body.position = Vec2d(*body.start_position)
        body.force = 0, 0
        body.torque = 0
        body.velocity = 0, 0
        body.angular_velocity = 0
    color = pygame.Color(random.randint(1, 255), random.randint(1, 255),
                         random.randint(1, 255))
    for shape in space.shapes:
        shape.color = color
Exemplo n.º 3
0
    def on_touch_down(self, touch):
        cpos = Vec2d(touch.x, touch.y)
        space = self.game.get_space()
        shape = space.point_query_first(cpos)

        if shape is not None:
            body = shape.body
            x1, y1 = cpos.int_tuple
            x2, y2 = body.position.int_tuple
            self.delta = (x1 - x2, y1 - y2)
            self.current_body = body
    def create_sonar(self):
        self.sonar_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        vertex = self.get_car_contour_vertices()
        offset = Vec2d(5, 0).rotated(self.car_body.angle)
        self.sonar_body.position = (vertex[1] + vertex[0]) / 2 - offset

        self.sonar_shape = pymunk.Circle(self.sonar_body, self.car_sonar_size)
        self.sonar_shape.collision_type = self.body_collision_type
        self.sonar_shape.color = cyan

        self.space.add(self.sonar_shape, self.sonar_body)
Exemplo n.º 5
0
    def transform(self, x, y):
        W = pyxel.width
        H = pyxel.height
        s = self.scale
        x_ = (x - self.x) * s + W / 2
        y_ = H / 2 - (y - self.y) * s

        cos, sin = self._cos, self._sin
        xt = cos * x_ - sin * y_
        yt = sin * x_ + cos * y_
        return Vec2d(xt, yt)
Exemplo n.º 6
0
        def target_force(position, other_position, repulse=True):
            # specify a potential field
            v = Vec2d(tuple(other_position - position))
            l = v.normalize_return_length()

            if repulse:
                v *= (-50.0 / l)
            else:
                v *= (l / 50.0)

            return v
Exemplo n.º 7
0
 def _add_walls(self) -> None:
     static_lines = [
         pymunk.Segment(self._space.static_body, Vec2d(50, 50),
                        Vec2d(950, 50), 2),
         pymunk.Segment(self._space.static_body, Vec2d(50, 50),
                        Vec2d(50, 350), 2),
         pymunk.Segment(self._space.static_body, Vec2d(50, 350),
                        Vec2d(950, 350), 2),
         pymunk.Segment(self._space.static_body, Vec2d(950, 350),
                        Vec2d(950, 50), 2)
     ]
     static_lines[0].friction = 1.0
     self.space.add(static_lines)
Exemplo n.º 8
0
 def __init__(self,
              a,
              b,
              anchor_a,
              anchor_b,
              stiffness=1000,
              damping=10,
              rest_length=None,
              **parameters):
     super().__init__(a, b, **parameters)
     self.anchor_a = Vec2d(anchor_a)
     self.anchor_b = Vec2d(anchor_b)
     if rest_length is None:
         world_pos_a = a.position + anchor_a
         world_pos_b = b.position + anchor_b
         rest_length = (world_pos_a - world_pos_b).get_length()
     self._rest_length = rest_length
     self.original_rest_length = rest_length
     self.stiffness = stiffness
     self.damping = damping
Exemplo n.º 9
0
    def create_poly(self, points, mass=5.0, pos=(0, 0)):

        moment = pm.moment_for_poly(mass, points)
        # moment = 1000
        body = pm.Body(mass, moment)
        body.position = Vec2d(pos)
        shape = pm.Poly(body, points)
        shape.friction = 0.5
        shape.collision_type = COLLTYPE_DEFAULT
        self.space.add(body, shape)
        return shape
Exemplo n.º 10
0
    def create_ball(self, point, mass=1.0, radius=15.0):

        moment = pm.moment_for_circle(mass, 0.0, radius)
        ball_body = pm.Body(mass, moment)
        ball_body.position = Vec2d(point)

        ball_shape = pm.Circle(ball_body, radius)
        ball_shape.friction = 1.5
        ball_shape.collision_type = COLLTYPE_DEFAULT
        self.space.add(ball_body, ball_shape)
        return ball_shape
 def scenario7(self):
     self.createObservedBall(25, 1, 150, 150, 1.0, 400, -100)
     # Create Initial Lines
     lines = [[750, 750, 750, 50], [50, 50, 50, 750], [750, 750, 50, 750],
              [50, 50, 750, 50]]
     for line in lines:
         self.createBoundaries(line)
     h = 5
     sizes = 27
     for y in range(1, h + 1):
         x = 50
         s = 20
         p = Vec2d(100, 100) + Vec2d(x + y * s * 4, 0)
         verts = [(random.randint(-sizes, 0), random.randint(0, sizes)),
                  (random.randint(0, sizes), random.randint(-sizes, 0)),
                  (random.randint(-sizes, 0), random.randint(0, sizes)),
                  (random.randint(0, sizes), random.randint(-sizes, 0))]
         self.create_poly(verts, 1, p, random.randint(-500, 500),
                          random.randint(-500, 500))
     self.seconds = 50
Exemplo n.º 12
0
 def put_box(self, layer_num, x_pos, y_pos, rect_width):
     # print('layer_num: {}, x_pos: {}, y_pos: {}, rect_width: {} in put_box: '.format(layer_num, x_pos, y_pos, rect_width))
     mass = 50.0
     moment = pymunk.moment_for_box(mass, (rect_width, self.rect_height))
     body = pymunk.Body(mass, moment)
     body.position = Vec2d(x_pos, y_pos)
     shape = pymunk.Poly.create_box(body, (rect_width, self.rect_height))
     shape.friction = 0.3
     # print('shape.body.area: {}, shape.body.area/rect_height: {}, rect_width: {}'.format(shape.area, shape.area/self.rect_height, rect_width))
     self.space.add(body, shape)
     self.boxes[layer_num].append(shape)
Exemplo n.º 13
0
def make_emitter():
    return arcade.Emitter(
        pos=Vec2d(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2),
        # pos=Vec2d.zero(),
        emit_controller=arcade.EmitterIntervalWithTime(0.0004, 15.0),
        particle_factory=lambda emitter: arcade.LifetimeParticle(
            filename_or_texture=TEXTURE,
            vel=arcade.rand_in_circle(Vec2d.zero(), 5.0),
            lifetime=1.0,
            scale=0.5,
            alpha=128))
Exemplo n.º 14
0
def curriculum_speed_factory(
        min_speed=3,
        max_speed=45,
        min_turn_rate_multiplier=0,
        max_turn_rate_multiplier=2,
        total_length=10000,
        random_seed=2,
        ) -> Callable[['TrajectoryTrackingProcess'], Tuple[List[Tuple[Vec2d, float]], bool]]:
    r = random.Random(random_seed)

    speed = (max_speed + min_speed) / 2

    # start with a straight line

    waypoints = [(Vec2d(0, 0), speed), (Vec2d(.001, 0), speed)]

    length = 0.0
    angle = 0.0

    def add_segment(segment_length, segment_angle):
        nonlocal angle, length, speed
        angle += segment_angle
        length += segment_length

        delta = Vec2d(segment_length, 0.0)
        delta.rotate(angle)
        waypoints.append((waypoints[-1][0] + delta, speed))

    while length < total_length:
        d = length / total_length

        segment_length = 100

        max_delta_speed = d * .5 * (max_speed - min_speed)
        speed = min(max_speed, max(min_speed, speed + r.uniform(-max_delta_speed, max_delta_speed)))
        add_segment(segment_length, 0)

    def curriculum_angled_path_generator(process: 'TrajectoryTrackingProcess') -> Tuple[List[Tuple[Vec2d, float]], bool]:
        return deepcopy(waypoints), False

    return curriculum_angled_path_generator
Exemplo n.º 15
0
 def MakeSwitches():
     switches.append(
         ScoreZone(SWITCH_NAME,
                   context,
                   Vec2d((15, 21)),
                   True,
                   False,
                   False,
                   context.switchColor[0],
                   radius=3,
                   retKey=SWITCH_RETKEY))
     switches.append(
         ScoreZone(SWITCH_NAME,
                   context,
                   Vec2d((15, 8)),
                   True,
                   False,
                   False,
                   context.switchColor[1],
                   radius=3,
                   retKey=SWITCH_RETKEY))
     switches.append(
         ScoreZone(SWITCH_NAME,
                   context,
                   Vec2d((41, 21)),
                   True,
                   False,
                   False,
                   context.switchColor[0],
                   radius=3,
                   retKey=SWITCH_RETKEY))
     switches.append(
         ScoreZone(SWITCH_NAME,
                   context,
                   Vec2d((41, 8)),
                   True,
                   False,
                   False,
                   context.switchColor[1],
                   radius=3,
                   retKey=SWITCH_RETKEY))
Exemplo n.º 16
0
def path_center_of_mass(seq):
    """
    Center of mass of a path.
    """
    M = 0.0
    cm = Vec2d(0, 0)
    for a, b in zip(seq[:-1], seq[1:]):
        a, b = map(Vec2d, (a, b))
        m = (b - a).length
        M += m
        cm += (m / 2) * (a + b)
    return cm / M
Exemplo n.º 17
0
 def __init__(self, pos, radius=.4, mass=50):
     self.mass = mass
     self.radius = radius
     self.pos = Vec2d(pos)
     self.body = None
     self.shape = None
     self.scene: Scene = None
     self.keys_down = set()
     self.is_jump = False
     self.is_pick = False
     self.is_put = False
     self.pick_dir = (1, 0)
def emitter_37():
    """Rotating emitter. Particles initial velocity is relative to emitter's angle."""
    e = arcade.Emitter(pos=CENTER_POS,
                       emit_controller=arcade.EmitterIntervalWithTime(
                           DEFAULT_EMIT_INTERVAL, DEFAULT_EMIT_DURATION),
                       particle_factory=lambda emitter: arcade.
                       LifetimeParticle(filename_or_texture=TEXTURE,
                                        vel=Vec2d(0.0, 2.0),
                                        lifetime=2.0,
                                        scale=DEFAULT_SCALE))
    e.change_angle = 10.0
    return emitter_37.__doc__, e
def emitter_22():
    """Interval, emit from center, velocity in fixed angle and speed"""
    e = arcade.Emitter(pos=CENTER_POS,
                       emit_controller=arcade.EmitterIntervalWithTime(
                           0.2, DEFAULT_EMIT_DURATION),
                       particle_factory=lambda emitter: arcade.
                       LifetimeParticle(filename_or_texture=TEXTURE,
                                        vel=Vec2d(1.0, 1.0),
                                        lifetime=DEFAULT_PARTICLE_LIFETIME,
                                        scale=DEFAULT_SCALE,
                                        alpha=128))
    return emitter_22.__doc__, e
Exemplo n.º 20
0
    def try_spawn_vehicle(self, offset: float = 0) -> bool:
        # print('try_spawn_vehicle')
        velocity = Vec2d(
            random.gauss(self.speed_mean, self.speed_standard_deviation), 0)
        position, angle = self.road.road_to_global(
            Vec2d(offset, (self.road.lane_center_offsets[random.randrange(
                0, self.road.num_lanes)])))

        vehicle = VehicleLaneFollower(self, (64, 64, 200), position, velocity,
                                      velocity.length, angle)

        if not self.can_place_entity(vehicle, 10):
            # print('remove ', position, angle)
            vehicle.discard()
            # print('try_spawn_vehicle remove ', vehicle.id)
            return False

        # print('try_spawn_vehicle add ', vehicle.id, vehicle.position, vehicle.velocity)
        # vehicle.handle_collision =
        self.num_vehicles = self.num_vehicles + 1
        return True
Exemplo n.º 21
0
def create_bananas(space):
    mass = 10
    size = 50
    points = [(-size, -size), (-size, size), (size, size), (size, -size)]
    moment = pymunk.moment_for_poly(mass, points, (0, 0))
    body = pymunk.Body(mass, moment)
    x = random.randint(0, 500)
    body.position = Vec2d(x, x)
    banana = pymunk.Poly(body, points, (0, 0))
    banana.elasticity = 0.95
    space.add(body, banana)
    return banana
Exemplo n.º 22
0
    def wander(self, t):
        """Return a small lissajous wander."""
        xperiod = 0.3
        sx = sin(xperiod * t)
        px = sx * abs(sx)

        vx = cos(xperiod * t)
        self.sprite._scale_x = copysign(max(0.3, abs(vx)), vx)
        return Vec2d(
            1.5 * px,
            0.2 * sin(0.2 * t),
        )
Exemplo n.º 23
0
 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
Exemplo n.º 24
0
 def MakeScales():
     scales.append(
         ScoreZone(SCALE_NAME,
                   context,
                   Vec2d((28, 20)),
                   True,
                   False,
                   False,
                   context.scaleColor[0],
                   radius=3.5,
                   retKey=SCALE_RETKEY))
     scales.append(
         ScoreZone(SCALE_NAME,
                   context,
                   Vec2d((28, 9)),
                   True,
                   False,
                   False,
                   context.scaleColor[1],
                   radius=3.5,
                   retKey=SCALE_RETKEY))
Exemplo n.º 25
0
    def __init__(self, pos, angle, length, space, mass=5.0):
        ''' parater angle is clockwise value '''
        radius = 3
        moment = 1000
        body = pm.Body(mass, moment)
        body.position = Vec2d(pos)

        power = mass * 2000
        impulse = power * Vec2d(0, 1)
        # the angle of rotated function is counter-clockwise, need to reverse it
        angle = -angle
        body.apply_impulse_at_local_point(impulse.rotated(angle))

        shape = pm.Circle(body, radius, (0, 0))
        shape.friction = 1
        shape.collision_type = COLLISION_EXPLODE
        space.add(body, shape)
        self.body = body
        self.shape = shape
        self.orig_pos = pos
        self.length = length
Exemplo n.º 26
0
    def create_palm(self, point, radius):
        moment = pm.moment_for_circle(10000, 0.0, radius)
        palm_body = pm.Body(10000, moment)
        palm_body.position = Vec2d(point)
        palm_body.velocity_func = maintain_velocity

        palm_shape = pm.Circle(palm_body, radius)
        palm_shape.friction = 20
        palm_shape.collision_type = COLLTYPE_FINGERTIP
        palm_shape.elasticity = .5
        self.space.add(palm_body, palm_shape)
        return palm_shape
Exemplo n.º 27
0
    def create_fingertip(self, point, mass=1000.0, radius=TIP_RADIUS):
        moment = pm.moment_for_circle(mass, 0.0, radius)
        fingertip_body = pm.Body(mass, moment)
        fingertip_body.position = Vec2d(point)
        fingertip_body.velocity_func = maintain_velocity

        fingertip_shape = pm.Circle(fingertip_body, radius)
        fingertip_shape.friction = 20
        fingertip_shape.collision_type = COLLTYPE_FINGERTIP
        fingertip_shape.elasticity = .9999
        self.space.add(fingertip_body, fingertip_shape)
        return fingertip_shape
Exemplo n.º 28
0
 def draw(self):
     p2 = self.body.position
     p1 = Vec2d(self.Collection, FLOOR_LEVEL)
     distance = int(euclidean_distance(p1, p2))
     midpt = midpoint(p1, p2) + Vec2d(15, 15)
     p1 = flip_vec(p1)
     p2 = flip_vec(p2)
     pygame.draw.line(self.screen, THECOLORS[self.Color], p1, p2, 1)
     font = pygame.font.Font(pygame.font.match_font("freemonobold"), 25)
     line = str(distance)
     text = font.render(line, 0, THECOLORS[self.Color])
     self.screen.blit(text, flip_vec(midpt))
     # sprite
     r = self.object.radius
     v = self.body.position
     rot = self.body.angle
     p = Vec2d(int(v.x), int(flipy(v.y)))
     self.sprite.move(p)
     self.sprite.rotate(rot)
     self.sprites.update()
     self.sprites.draw(self.screen)
Exemplo n.º 29
0
    def create_ball(self, point, mass=4.0, radius=BALL_DEFAULT_RADIUS):

        moment = pm.moment_for_circle(mass, 0.0, radius)
        ball_body = pm.Body(mass, moment)
        ball_body.position = Vec2d(point)

        ball_shape = pm.Circle(ball_body, radius)
        ball_shape.friction = .5
        ball_shape.elasticity = .9999
        ball_shape.collision_type = COLLTYPE_DEFAULT
        self.space.add(ball_body, ball_shape)
        return ball_shape
Exemplo n.º 30
0
    def on_new_level(self):
        # Physics stuff
        self.space = pymunk.Space()
        self.space.gravity = Vec2d(0.0, -1200.0)

        self.player = Player(x=100,
                             y=600,
                             group=self.background,
                             space=self.space,
                             game=self)
        self.window.push_handlers(self.player.key_handler)
        self.current_level().create(self.space, self.background)