Example #1
0
    def __init__(self):
        super(Pulley, self).__init__()
        y, L, a, b = 16.0, 12.0, 1.0, 2.0
        # The ground
        ground = self.world.create_static_body(
            shapes=[edgeShape(vertices=[(-40, 0), (40, 0)]),
                    circleShape(radius=2, pos=(-10.0, y + b + L)),
                    circleShape(radius=2, pos=(10.0, y + b + L))]
        )

        body_a = self.world.create_dynamic_body(
            position=(-10, y),
            fixtures=fixtureDef(shape=polygonShape(box=(a, b)), density=5.0),
        )
        body_b = self.world.create_dynamic_body(
            position=(10, y),
            fixtures=fixtureDef(shape=polygonShape(box=(a, b)), density=5.0),
        )

        self.pulley = self.world.CreatePulleyJoint(
            body_a=body_a,
            body_b=body_b,
            anchorA=(-10.0, y + b),
            anchorB=(10.0, y + b),
            groundAnchorA=(-10.0, y + b + L),
            groundAnchorB=(10.0, y + b + L),
            ratio=1.5,
        )
def load_chain(world, data, dynamic):
    chain = []
    for ind in range(len(data)):
        row = data[ind]
        circle = circleShape(pos=(0, 0), radius=0.001)
        if dynamic:
            new_body = world.CreateDynamicBody(position=row, userData=ind)
            new_body.CreateFixture(
                fixtureDef(shape=circle, density=1, friction=0.3))
            # if ind > 0:
            #     world.CreateRevoluteJoint(bodyA=chain[ind-1], bodyB=new_body, anchor=chain[ind-1].worldCenter)
        else:
            new_body = world.CreateStaticBody(position=row, shapes=[circle])
        chain.append(new_body)
    return chain
Example #3
0
 def _create_particle(self, mass, x, y, ttl):
     p = self.world.CreateDynamicBody(
         position=(x, y),
         angle=0.0,
         fixtures=fixtureDef(
             shape=circleShape(radius=2 / SCALE, pos=(0, 0)),
             density=mass,
             friction=0.1,
             categoryBits=0x0100,
             maskBits=0x001,  # collide only with ground
             restitution=0.3))
     p.ttl = ttl
     self.particles.append(p)
     self._clean_particles(False)
     return p
 def _make_point(self):
     point = self._world.CreateDynamicBody(position=(0, 0),
                                           angle=0.0,
                                           fixedRotation=True,
                                           linearDamping=10.0,
                                           fixtures=fixtureDef(
                                               shape=circleShape(
                                                   radius=POINT_RADIUS,
                                                   pos=(0, 0)),
                                               density=0.01,
                                               friction=1.0,
                                               restitution=0.3,
                                           ))
     point.bullet = True
     return point
Example #5
0
 def _create_ball(self, mass, x, y, ttl, radius):
     p = self.world.CreateDynamicBody(
         position=(x, y),
         angle=0,
         fixtures=fixtureDef(
             shape=circleShape(radius=radius / SCALE, pos=(0, 0)),
             density=mass,
             friction=0.1,
             groupIndex=1,
             categoryBits=0x0300,
             maskBits=0x001,  # collide only with ground
             restitution=0.5))
     p.ttl = ttl
     self.balls.append(p)
     self._clean_balls(False)
     return p
Example #6
0
 def build_obstacle(self):
     pos = copy.deepcopy(self.move_range[0])
     pos[self.mode] = np.random.uniform(low=self.move_range[0][self.mode],
                                        high=self.move_range[1][self.mode])
     self.dynamic_body = self.world.CreateDynamicBody(
         position=(pos[0], pos[1]),
         angle=0.0,
         fixtures=fixtureDef(shape=circleShape(radius=0.3, pos=(0, 0)),
                             density=5.0,
                             friction=0,
                             categoryBits=0x001,
                             maskBits=0x0010,
                             restitution=1.0))
     self.dynamic_body.color1 = (0.7, 0.2, 0.2)
     self.dynamic_body.color2 = (0.7, 0.2, 0.2)
     self.set_linear_vel(init=True)
Example #7
0
 def _create_particle(self, mass, x, y, ttl):                          # particle is the stuff come out of the engine
     p = self.world.CreateDynamicBody(
         position=(x, y-0.5),
         angle=0.0,
         fixtures=fixtureDef(
             shape=circleShape(radius=3 / SCALE, pos=(0, 0)),          # define the size of the particle
             density=mass,
             friction=0.1,
             categoryBits=0x0100,
             maskBits=0x001,  # collide only with ground
             restitution=0.3)
     )
     p.ttl = ttl                                                       # not understood yet ??? what is ttl ???
     self.particles.append(p)
     self._clean_particles(False)
     return p
Example #8
0
 def _create_particle(self, mass, x, y):
     p = self.world.CreateDynamicBody(
         position = (x,y),
         angle=0.0,
         fixtures = fixtureDef(
             shape=circleShape(radius=2/SCALE, pos=(0,0)),
             density=mass,
             friction=0.1,
             categoryBits=0x0100,
             maskBits=0x001,  # collide only with ground
             restitution=0.9)
             )
     p.ttl = 1
     self.particles.append(p)
     self._clean_particles(False)
     return p
 def _create_particle(self, mass, x, y, ttl):
     """Create particles for better visualization of impulse position."""
     p = self.world.CreateDynamicBody(
         position=(x, y),
         angle=0.0,
         fixtures=fixtureDef(
             shape=circleShape(radius=2 / SCALE, pos=(0, 0)),
             density=mass,
             friction=0.1,
             categoryBits=0x0100,
             maskBits=0x001,
             restitution=0.3)
     )
     p.ttl = ttl
     self.particles.append(p)
     self._clean_particles(False)
     return p
Example #10
0
    def _create_puck(self, position, color):
        puck = self.world.CreateDynamicBody(
            position=position,
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=10/SCALE, pos=(0,0)),
                density=10.0,
                friction=0.1,
                categoryBits=0x001,
                maskBits=0x0010,  # collide only with ground
                restitution=0.95)  # 0.99 bouncy
        )
        puck.color1 = color
        puck.color2 = color
        puck.linearDamping = 0.05

        return puck
    def __init__(self, scale, motors_torque, nb_steps_under_water):
        '''
            Creates a climber, which cannot survive under water and cannot touch ground.

            Args:
                scale: Scale value used in the environment (to adapt the embodiment to its environment)
                motors_torque: Maximum torque the embodiment can use on its motors
                nb_steps_under_water: How many consecutive steps the embodiment can survive under water
        '''
        super(ClimberAbstractBody, self).__init__(scale, motors_torque, nb_steps_under_water)

        self.body_type = BodyTypesEnum.CLIMBER
        self.sensors = []
        self.SENSOR_FD = fixtureDef(
            shape=circleShape(radius=0.05),
            density=1.0,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x1,
            isSensor=True
        )
    def create_agents_team_deathmatch(self):
        upper_y = PLAYFIELD + STATE_H / 2
        lower_y = - PLAYFIELD + STATE_H / 2
        upper_x = PLAYFIELD + STATE_W / 2
        lower_x = -PLAYFIELD + STATE_W / 2
        #self.agent_radius = 4

        for agent in self.agents:
            agent_body = self.world.CreateDynamicBody(
                position=(np.random.uniform(low=lower_x + self.agent_radius, high=upper_x - self.agent_radius), np.random.uniform(low=lower_y + self.agent_radius, high=upper_y - self.agent_radius)),
                fixtures=fixtureDef(shape=circleShape(
                    radius=self.agent_radius), density=2),
             )
            agent.body = agent_body
            agent_body.linearDamping = .3
            agent_body.angularDamping = .3
            agent_body.angle = np.random.uniform(low=0, high=2*pi)
            agent_body.userData = {"class": EntityType.AGENT, 'agent': agent, 'last_shot': self.time, 'toBeDestroyed': False, 'communicate': 0}
            agent.is_alive = True
            agent.game_over = False
            agent.reward = 0
Example #13
0
    def attach_fixtures(self, name, body, fixture_def, scale):
        rigid_body_to_attach = next(rb for rb in self.rigid_bodies if rb.name == name)
        if rigid_body_to_attach is None:
            raise Exception("No rigidBody with this name was found.")

        _origin = rigid_body_to_attach.origin*scale

        for polygon in rigid_body_to_attach.polygons:
            _vertices = []
            for vertex in polygon.vertices:
                _vertex = vertex*scale
                _vertices.append((_vertex[0] - _origin[0], _vertex[1] - _origin[1]))
            fixture_def.shape = polygonShape(vertices=_vertices)
            body.CreateFixture(fixture_def)

        for circle in rigid_body_to_attach.circles:
            _center = circle.center*scale
            center = (_center[0] - _origin[0], _center[1] - _origin[1])
            radius = circle.radius*scale
            fixture_def.shape = circleShape(center, radius)
            body.CreateFixture(fixture_def)
Example #14
0
 def build_obstacle(self):
     pos = copy.deepcopy(self.move_range[0])
     if self.mode == 2:
         theta = np.random.random() * np.pi * 2
         pos = np.array([np.cos(theta), np.sin(theta)
                         ]) * self.distance + np.array(self.move_range[1])
     else:
         pos[self.mode] = np.random.uniform(
             low=self.move_range[0][self.mode],
             high=self.move_range[1][self.mode])
     self.dynamic_body = self.world.CreateDynamicBody(
         position=(pos[0], pos[1]),
         angle=0.0,
         fixtures=fixtureDef(shape=circleShape(radius=0.3, pos=(0, 0)),
                             density=5.0,
                             friction=0,
                             categoryBits=0x001,
                             maskBits=0x0010,
                             restitution=1.0))
     self.dynamic_body.color1 = (0.7, 0.2, 0.2)
     self.dynamic_body.color2 = (0.7, 0.2, 0.2)
     self.step(init=True)
 def agentShoot(self, agent):
     agentPos = agent.body.position
     agentRotation = agent.body.angle
     x = cos(agentRotation)
     y = sin(agentRotation)
     if agent.is_alive == False or len(agent.body.fixtures) == 0:
         return
     # a new shot is only allowed every 1.0 seconds
     if self.time - agent.body.userData['last_shot'] < 1.0:
         return
     agent.body.userData['last_shot'] = self.time
     bullet_radius = self.agent_radius / 4
     bullet_impulse = 140 * bullet_radius * bullet_radius
     radius = agent.body.fixtures[0].shape.radius
     bullet = self.world.CreateDynamicBody(
         position=(agentPos[0] + (bullet_radius + radius + 1)*x, agentPos[1] + (bullet_radius + radius + 1)*y),
         fixtures=fixtureDef(shape=circleShape(
             radius=bullet_radius), density=1),
     )
     bullet.fixtures[0].sensor = True
     bullet.userData = {'agent': agent, 'class': EntityType.BULLET}
     bullet.ApplyLinearImpulse((bullet_impulse*x,bullet_impulse*y), bullet.worldCenter, True)
     bullet.linearDamping = 0
    def reset(self):
        self._destroy()
        self.world.contactListener_bug_workaround = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_bug_workaround
        self.game_over = False
        self.prev_shaping = None
        self.scroll = 0.0
        self.lidar_render = 0

        W = VIEWPORT_W / SCALE
        H = VIEWPORT_H / SCALE

        self._generate_terrain(self.hardcore)
        self._generate_clouds()

        # Process the fixtures
        # PolygonShape: vertices
        # EdgeShape: vertices
        # CircleShape: radius
        # friction, density, restitution, maskBits, categoryBits
        self.fixtures = {}
        for k in self.fixture_defs.keys():
            if self.fixture_defs[k]['FixtureShape']['Type'] == 'PolygonShape' or \
               self.fixture_defs[k]['FixtureShape']['Type'] == 'EdgeShape':
                fixture_shape = polygonShape(
                    vertices=[(x / SCALE, y / SCALE)
                              for x, y in self.fixture_defs[k]['FixtureShape']
                              ['Vertices']])
            elif self.fixture_defs[k]['FixtureShape']['Type'] == 'CircleShape':
                fixture_shape = circleShape(
                    radius=self.fixture_defs[k]['FixtureShape']['Radius'] /
                    SCALE)
            else:
                print("Invalid fixture type: " +
                      self.fixture_defs[k]['FixtureShape'])
                assert (False)
            self.fixtures[k] = fixtureDef(
                shape=fixture_shape,
                friction=self.fixture_defs[k]['Friction'],
                density=self.fixture_defs[k]['Density'],
                restitution=self.fixture_defs[k]['Restitution'],
                maskBits=self.fixture_defs[k]['MaskBits'],
                categoryBits=self.fixture_defs[k]['CategoryBits'])

        # Process the dynamic bodies
        # position, angle,  fixture,
        self.bodies = {}
        for k in self.body_defs.keys():
            self.bodies[k] = self.world.CreateDynamicBody(
                position=[x / SCALE for x in self.body_defs[k]['Position']],
                angle=self.body_defs[k]['Angle'],
                fixtures=self.fixtures[self.body_defs[k]['FixtureName']])
            self.bodies[k].color1 = self.body_defs[k]['Color1']
            self.bodies[k].color2 = self.body_defs[k]['Color2']
            self.bodies[k].can_touch_ground = self.body_defs[k][
                'CanTouchGround']
            self.bodies[k].ground_contact = False

            # Apply a force to the 'center' body
            if k == 'Hull':
                self.bodies[k].ApplyForceToCenter((self.np_random.uniform(
                    -self.body_defs[k]['InitialForceScale'],
                    self.body_defs[k]['InitialForceScale']), 0), True)
        self.body_state_order = copy.deepcopy(list(self.bodies.keys()))

        # Process the joint motors
        # bodyA, bodyB, localAnchorA, localAnchorB, enableMotor, enableLimit,
        # maxMotorTorque, motorSpeed, lowerAngle, upperAngle
        self.joints = {}
        for k in self.joint_defs.keys():
            self.joints[k] = self.world.CreateJoint(
                revoluteJointDef(
                    bodyA=self.bodies[self.joint_defs[k]['BodyA']],
                    bodyB=self.bodies[self.joint_defs[k]['BodyB']],
                    localAnchorA=[
                        x / SCALE for x in self.joint_defs[k]['LocalAnchorA']
                    ],
                    localAnchorB=[
                        x / SCALE for x in self.joint_defs[k]['LocalAnchorB']
                    ],
                    enableMotor=self.joint_defs[k]['EnableMotor'],
                    enableLimit=self.joint_defs[k]['EnableLimit'],
                    maxMotorTorque=self.joint_defs[k]['MaxMotorTorque'],
                    motorSpeed=self.joint_defs[k]['MotorSpeed'],
                    lowerAngle=self.joint_defs[k]['LowerAngle'],
                    upperAngle=self.joint_defs[k]['UpperAngle']))
        self.joint_action_order = copy.deepcopy(list(self.joints.keys()))

        # Make sure hull is last
        self.drawlist = self.terrain + list(self.bodies.values())

        class LidarCallback(Box2D.b2.rayCastCallback):
            def ReportFixture(self, fixture, point, normal, fraction):
                if (fixture.filterData.categoryBits & 1) == 0:
                    return 1
                self.p2 = point
                self.fraction = fraction
                return 0

        self.lidar = [LidarCallback() for _ in range(10)]

        return self.step(np.array([0] * np.prod(self.action_space.shape)))[0]
Example #17
0
    def hard_reset(self):
        self._destroy()
        #self.world.contactListener_keepref = ContactDetector(self)
        #self.world.contactListener = self.world.contactListener_keepref
        self.game_over = False
        self.prev_shaping = None

        W = VIEWPORT_W / SCALE
        H = VIEWPORT_H / SCALE

        self.drawlist = []

        # terrain
        self.moon = self.world.CreateStaticBody(shapes=edgeShape(
            vertices=[(0, H / 8), (W, H / 8)]))
        self.moon.CreateEdgeFixture(vertices=[(W / 8, 0), (W / 8, H)],
                                    density=0,
                                    friction=0.1)
        self.moon.CreateEdgeFixture(vertices=[(0, H * 7 / 8), (W, H * 7 / 8)],
                                    density=0,
                                    friction=0.1)
        self.moon.CreateEdgeFixture(vertices=[(W * 7 / 8, 0), (W * 7 / 8, H)],
                                    density=0,
                                    friction=0.1)

        self.moon.color1 = (0.9, 0.9, 0.9)
        self.moon.color2 = (0.9, 0.9, 0.9)

        self.robot = self.world.CreateDynamicBody(
            position=(random.randint(W * 2 / 8, W * 6 / 8),
                      random.randint(H * 2 / 8, H * 6 / 8)),
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=10 / SCALE, pos=(0, 0)),
                density=5.0,
                friction=0.1,
                categoryBits=0x0010,
                maskBits=0x001,  # collide only with ground
                restitution=0.5)  # 0.99 bouncy
        )
        self.robot.color1 = (1, 1, 0)
        self.robot.color2 = (0.1, 0.1, 0.1)

        self.ball = self.world.CreateDynamicBody(
            position=(random.randint(W * 2 / 8, W * 6 / 8),
                      random.randint(H * 2 / 8, H * 6 / 8)),
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=5 / SCALE, pos=(0, 0)),
                density=5.0,
                friction=0.1,
                categoryBits=0x0010,
                maskBits=0x001,  # collide only with ground
                restitution=0.5)  # 0.99 bouncy
        )
        self.ball.color1 = (0.9, 0.4, 0.0)
        self.ball.color2 = (0.8, 0.4, 0.05)

        self.drawlist += [self.robot]
        self.drawlist += [self.ball]
        self.drawlist += [self.moon]
        return self._step(np.array([0, 0]) if self.continuous else 0)[0]
    def _reset(self):
        self._destroy()

        self.world.contactListener_keepref = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_keepref
        self.stepnumber = 0
        ground = self.world.CreateStaticBody(
            fixtures=fixtureDef(
                shape=polygonShape(
                    vertices=[(0, GROUNDHEIGHT - BODY_WIDTH), (W, GROUNDHEIGHT - BODY_WIDTH), (W, GROUNDHEIGHT),
                              (0, GROUNDHEIGHT)]),
                friction=0.8,
                restitution=0.1)
        )
        ground.color1 = rgb(255, 255, 255)
        self.objects.append(ground)

        initial_x = W / 4
        initial_y = GROUNDHEIGHT + 3 * SEGMENT_LENGTH + HEAD_RADIUS * 3

        head = self.world.CreateDynamicBody(
            position=(initial_x, initial_y),
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=HEAD_RADIUS, pos=(0, 0)),
                density=0.25,
                friction=0.5,
                categoryBits=0x0010,
                maskBits=0x001,
                restitution=0.1)
        )
        head.color1 = rgb(255, 255, 255)
        self.objects.append(head)

        upper_body = self.world.CreateDynamicBody(
            position=(initial_x, initial_y - HEAD_RADIUS),
            angle=0.1,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                             (+BODY_WIDTH / 2, 0),
                                             (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                             (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                friction=0.5,
                categoryBits=0x0010,
                maskBits=0x001,
                restitution=0.1)
        )
        upper_body.color1 = rgb(255, 255, 255)
        self.objects.append(upper_body)

        neck_joint = revoluteJointDef(
            bodyA=head,
            bodyB=upper_body,
            localAnchorA=(0, -HEAD_RADIUS),
            localAnchorB=(0, 0),
            enableLimit=True,
            lowerAngle=-np.pi / 4,
            upperAngle=np.pi / 4,
            maxMotorTorque=MAX_MOTOR_TORQUE,
            motorSpeed=0.0,
            enableMotor=True
        )
        neck_joint = self.world.CreateJoint(neck_joint)
        self.joints.append(neck_joint)

        lower_body = self.world.CreateDynamicBody(
            position=(initial_x, initial_y - HEAD_RADIUS - BODY_WIDTH * 4),
            angle=0,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                             (+BODY_WIDTH / 2, 0),
                                             (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                             (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                friction=0.5,
                categoryBits=0x0010,
                maskBits=0x001,
                restitution=0.1)
        )
        lower_body.color1 = rgb(255, 255, 255)
        self.objects.append(lower_body)

        back_joint = revoluteJointDef(
            bodyA=upper_body,
            bodyB=lower_body,
            localAnchorA=(0, -BODY_WIDTH * 4),
            localAnchorB=(0, 0),
            enableLimit=True,
            lowerAngle=-np.pi / 6,
            upperAngle=np.pi / 3,
            maxMotorTorque=MAX_MOTOR_TORQUE,
            motorSpeed=0.0,
            enableMotor=True
        )
        back_joint = self.world.CreateJoint(back_joint)
        self.joints.append(back_joint)

        for side in (-1, 1):
            # legs
            upper_leg = self.world.CreateDynamicBody(
                position=(initial_x, initial_y - HEAD_RADIUS - 2 * SEGMENT_LENGTH),
                angle=0.5 * side,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                                 (+BODY_WIDTH / 2, 0),
                                                 (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                                 (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                    friction=0.5,
                    categoryBits=0x0010,
                    maskBits=0x001,
                    restitution=0.1)
            )
            upper_leg.color1 = rgb(255, 255, 255)
            self.objects.append(upper_leg)

            upper_leg_joint = revoluteJointDef(
                bodyA=lower_body,
                bodyB=upper_leg,
                localAnchorA=(0, -BODY_WIDTH * 4),
                localAnchorB=(0, 0),
                enableLimit=True,
                lowerAngle=-np.pi / 4,
                upperAngle=np.pi / 4,
                maxMotorTorque=MAX_MOTOR_TORQUE,
                motorSpeed=0.0,
                enableMotor=True
            )
            upper_leg_joint = self.world.CreateJoint(upper_leg_joint)
            self.joints.append(upper_leg_joint)

            lower_leg = self.world.CreateDynamicBody(
                position=(initial_x, initial_y - HEAD_RADIUS - 3 * SEGMENT_LENGTH),
                angle=0.5 * side,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                                 (+BODY_WIDTH / 2, 0),
                                                 (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                                 (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                    friction=0.5,
                    categoryBits=0x0010,
                    maskBits=0x001,
                    restitution=0.1)
            )
            lower_leg.color1 = rgb(255, 255, 255)
            lower_leg.ground_contact = False
            self.objects.append(lower_leg)

            lower_leg_joint = revoluteJointDef(
                bodyA=upper_leg,
                bodyB=lower_leg,
                localAnchorA=(0, -BODY_WIDTH * 4),
                localAnchorB=(0, 0),
                enableLimit=True,
                lowerAngle=-np.pi / 2,
                upperAngle=0,
                maxMotorTorque=MAX_MOTOR_TORQUE,
                motorSpeed=0.0,
                enableMotor=True
            )
            lower_leg_joint = self.world.CreateJoint(lower_leg_joint)
            self.joints.append(lower_leg_joint)

            # arms
            upper_arm = self.world.CreateDynamicBody(
                position=(initial_x, initial_y - HEAD_RADIUS),
                angle=0.5 * side,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                                 (+BODY_WIDTH / 2, 0),
                                                 (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                                 (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                    friction=0.5,
                    categoryBits=0x0010,
                    maskBits=0x001,
                    restitution=0.1)
            )
            upper_arm.color1 = rgb(255, 255, 255)
            self.objects.append(upper_arm)

            upper_arm_joint = revoluteJointDef(
                bodyA=upper_body,
                bodyB=upper_arm,
                localAnchorA=(0, 0),
                localAnchorB=(0, 0),
                enableLimit=True,
                lowerAngle=-np.pi / 2,
                upperAngle=np.pi / 2,
                maxMotorTorque=MAX_MOTOR_TORQUE,
                motorSpeed=0.0,
                enableMotor=True
            )
            upper_arm_joint = self.world.CreateJoint(upper_arm_joint)
            self.joints.append(upper_arm_joint)

            lower_arm = self.world.CreateDynamicBody(
                position=(initial_x, initial_y - HEAD_RADIUS - SEGMENT_LENGTH),
                angle=0.5 * side,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=((-BODY_WIDTH / 2, 0),
                                                 (+BODY_WIDTH / 2, 0),
                                                 (BODY_WIDTH / 2, -SEGMENT_LENGTH),
                                                 (-BODY_WIDTH / 2, -SEGMENT_LENGTH))), density=1.0,
                    friction=0.5,
                    categoryBits=0x0010,
                    maskBits=0x001,
                    restitution=0.1)
            )
            lower_arm.color1 = rgb(255, 255, 255)
            self.objects.append(lower_arm)

            lower_arm_joint = revoluteJointDef(
                bodyA=upper_arm,
                bodyB=lower_arm,
                localAnchorA=(0, -BODY_WIDTH * 4),
                localAnchorB=(0, 0),
                enableLimit=True,
                lowerAngle=0,
                upperAngle=np.pi / 2,
                maxMotorTorque=MAX_MOTOR_TORQUE,
                motorSpeed=0.0,
                enableMotor=True
            )
            lower_arm_joint = self.world.CreateJoint(lower_arm_joint)
            self.joints.append(lower_arm_joint)

        return self._step(np.array([0.0] * 10))[0]
Example #19
0
    def _create_tiles(self):
        self.tiles = []
        self.tiles_poly = []
        w, s = 1, 4  # width and step of tiles:
        if self.agent:
            TILES = {
                '2': [(-ROAD_WIDTH / 2 - (i + 1) * w, ROAD_WIDTH / 2)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '3': [(-ROAD_WIDTH / 2 - (i + 1) * w, -ROAD_WIDTH / 2)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '4': [(-ROAD_WIDTH / 2, -ROAD_WIDTH / 2 - (i + 1) * w)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '5': [(ROAD_WIDTH / 2, -ROAD_WIDTH / 2 - (i + 1) * w)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '6': [(ROAD_WIDTH / 2 + (i + 1) * w, -ROAD_WIDTH / 2)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '7': [(ROAD_WIDTH / 2 + (i + 1) * w, ROAD_WIDTH / 2)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '8': [(ROAD_WIDTH / 2, ROAD_WIDTH / 2 + (i + 1) * w)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '9': [(-ROAD_WIDTH / 2, ROAD_WIDTH / 2 + (i + 1) * w)
                      for i in range(int(ROAD_WIDTH), int(PLAYFIELD), s)],
                '34': [(START_2[0] + math.cos(rad) * SMALL_TURN,
                        START_2[1] + math.sin(rad) * SMALL_TURN)
                       for rad in np.linspace(np.pi / 2, 0, 6)],
                '36': [(-ROAD_WIDTH + rad, -ROAD_WIDTH // 2)
                       for rad in np.linspace(0, 2 * ROAD_WIDTH, 6)],
                '38': [(START_1[0] + math.cos(rad) * BIG_TURN,
                        START_1[1] + math.sin(rad) * BIG_TURN)
                       for rad in np.linspace(-np.pi / 2, 0, 6)] + [TARGET_8],
                '56': [(START_3[0] + math.cos(rad) * SMALL_TURN,
                        START_3[1] + math.sin(rad) * SMALL_TURN)
                       for rad in np.linspace(np.pi, np.pi / 2, 6)],
                '58': [(ROAD_WIDTH // 2, -ROAD_WIDTH + rad)
                       for rad in np.linspace(0, 2 * ROAD_WIDTH, 6)],
                '52': [(START_2[0] + math.cos(rad) * BIG_TURN,
                        START_2[1] + math.sin(rad) * BIG_TURN)
                       for rad in np.linspace(0, np.pi / 2, 6)] + [TARGET_2],
                '78': [(START_4[0] + math.cos(rad) * SMALL_TURN,
                        START_4[1] + math.sin(rad) * SMALL_TURN)
                       for rad in np.linspace(-np.pi / 2, -np.pi, 6)],
                '72': [(ROAD_WIDTH - rad, ROAD_WIDTH // 2)
                       for rad in np.linspace(0, 2 * ROAD_WIDTH, 6)],
                '74':
                [(START_3[0] + math.cos(rad) * BIG_TURN,
                  START_3[1] + math.sin(rad) * BIG_TURN)
                 for rad in np.linspace(np.pi / 2, np.pi, 6)] + [TARGET_4],
                '92': [(START_1[0] + math.cos(rad) * SMALL_TURN,
                        START_1[1] + math.sin(rad) * SMALL_TURN)
                       for rad in np.linspace(0, -np.pi / 2, 6)],
                '94': [(-ROAD_WIDTH // 2, ROAD_WIDTH - rad)
                       for rad in np.linspace(0, 2 * ROAD_WIDTH, 6)],
                '96': [(START_4[0] + math.cos(rad) * BIG_TURN,
                        START_4[1] + math.sin(rad) * BIG_TURN)
                       for rad in np.linspace(-np.pi, -np.pi / 2, 6)],
            }
            self.tiles_poly = TILES[self.car.hull.path[0]] + TILES[
                self.car.hull.path] + TILES[self.car.hull.path[1]]

            for tile in self.tiles_poly:
                t = self.world.CreateStaticBody(
                    position=tile,
                    fixtures=fixtureDef(shape=circleShape(radius=0.5),
                                        isSensor=True))
                t.road_visited = False
                t.name = 'tile'
                t.userData = t
                self.tiles.append(t)
Example #20
0
 def reset(self):
     self.nstep_internal = -1
     self._destroy()
     self.world.contactListener_keepref = ContactDetector(self)
     self.world.contactListener = self.world.contactListener_keepref
     self.game_over = False
     self.prev_shaping = None
     # Walls
     for i, w in enumerate(WALL_POS):
         wbody = self.world.CreateStaticBody(
             position=w,
             fixtures=fixtureDef(
                 shape=polygonShape(vertices=WALL_VERT if i %
                                    2 else WALL_HORZ),
                 density=5.0,
                 friction=0.1,
                 # categoryBits=0x0010,
                 # maskBits=0x001,  # collide only with ground
                 restitution=0.0))
         wbody.color1 = (0.0, 0.0, 0.0)
         wbody.color2 = (0.0, 0.0, 0.0)
         self.walls.append(wbody)
     # Target
     target_x = xy2pixel(-0.5, 'W')
     target_y = xy2pixel(1., 'H')
     self.target = self.world.CreateStaticBody(
         position=(target_x, target_y),
         angle=0.0,
         fixtures=fixtureDef(
             shape=circleShape(pos=(0, 0), radius=4 * DD),
             density=5.0,
             friction=0.1,
             categoryBits=0x0010,
             # maskBits=0x001,  # collide only with ground
             # restitution=0.0
         ))
     self.target.color1 = (0.4, 0.9, 0.4)
     self.target.color2 = (0.4, 0.9, 0.4)
     # Striker
     striker_init_x = xy2pixel(0., 'W')
     striker_init_y = xy2pixel(0., 'H')
     self.striker = self.world.CreateDynamicBody(
         position=(striker_init_x, striker_init_y),
         angle=0.0,
         linearDamping=0.05,
         angularDamping=0.5,
         fixtures=fixtureDef(
             shape=polygonShape(vertices=STIKER_POLY),
             density=5.0,
             friction=0.1,
             # categoryBits=0x0010,
             # maskBits=0x0010,  # collide only with ground
             restitution=0.0)  # 0.99 bouncy
     )
     self.striker.color1 = (0.9, 0.4, 0.4)
     self.striker.color2 = (0.9, 0.4, 0.4)
     # Puck
     puck_init_x = xy2pixel(0., 'W')
     puck_init_y = xy2pixel(0., 'H')
     self.puck = self.world.CreateDynamicBody(
         position=(puck_init_x, puck_init_y),
         angle=0.0,
         linearDamping=self.BALL_DAMPING,  # EFFECTIVE!
         fixtures=fixtureDef(
             shape=circleShape(pos=(0, 0), radius=DD),
             density=5.0,
             friction=0.9,
             categoryBits=0x0010,
             maskBits=0x001,  # collide only with ground
             restitution=0.1)  # 0.99 bouncy
     )
     self.puck.color1 = (0.4, 0.4, 0.9)
     self.puck.color2 = (0.4, 0.4, 0.9)
     # Draw objects
     self.drawlist = [self.target] + self.walls + [self.striker, self.puck]
     return self._get_state()
Example #21
0
    def __init__(self):
        EzPickle.__init__(self)
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.moon = None
        self.lander = None
        self.particles = []

        self.prev_reward = None

        # useful range is -1 .. +1, but spikes can be higher
        self.observation_space = spaces.Box(-np.inf,
                                            np.inf,
                                            shape=(8, ),
                                            dtype=np.float32)

        # fixtureDef
        self.lander_fd = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in LANDER_POLY]),
            density=5.0,
            friction=0.1,
            categoryBits=0x0010,
            maskBits=0x001,  # collide only with ground
            restitution=0.0)  # 0.99 bouncy

        self.leg_fd = fixtureDef(shape=polygonShape(box=(LEG_W / SCALE,
                                                         LEG_H / SCALE)),
                                 density=1.0,
                                 restitution=0.0,
                                 categoryBits=0x0020,
                                 maskBits=0x001)

        self.create_partcle_mass_35_fd = fixtureDef(
            shape=circleShape(radius=2 / SCALE, pos=(0, 0)),
            density=3.5,
            friction=0.1,
            categoryBits=0x0100,
            maskBits=0x001,  # collide only with ground
            restitution=0.3)

        self.create_partcle_mass_07_fd = fixtureDef(
            shape=circleShape(radius=2 / SCALE, pos=(0, 0)),
            density=0.7,
            friction=0.1,
            categoryBits=0x0100,
            maskBits=0x001,  # collide only with ground
            restitution=0.3)

        moon_w = VIEWPORT_W / SCALE
        self.moon_fd = fixtureDef(shape=edgeShape(vertices=[(0, 0), (moon_w,
                                                                     0)]),
                                  density=0,
                                  friction=0.1)

        if self.continuous:
            # Action is two floats [main engine, left-right engines].
            # Main engine: -1..0 off, 0..+1 throttle from 50% to 100% power. Engine can't work with less than 50% power.
            # Left-right:  -1.0..-0.5 fire left engine, +0.5..+1.0 fire right engine, -0.5..0.5 off
            self.action_space = spaces.Box(-1, +1, (2, ), dtype=np.float32)
        else:
            # Nop, fire left engine, main engine, right engine
            self.action_space = spaces.Discrete(4)

        self.reset()
 def _build_obs_range(self):
     self.obs_range_plt = self.world.CreateKinematicBody(position=(self.drone.position[0], self.drone.position[1]), angle=0.0,
                                                         fixtures=fixtureDef(shape=circleShape(radius=np.float64(self.max_obs_range), pos=(0, 0)),
                                                                             density=0, friction=0, categoryBits=0x0100,
                                                                             maskBits=0x000, restitution=0.3))
     self.obs_range_plt.color1 = (0.2, 0.2, 0.4)
     self.obs_range_plt.color2 = (0.6, 0.6, 0.6)
Example #23
0
    restitution=0.0)  # 0.99 bouncy

LEG_FD = fixtureDef(shape=polygonShape(box=(LEG_W / 2, LEG_H / 2)),
                    density=1.0,
                    restitution=0.0,
                    categoryBits=BIPED_CATEGORY,
                    maskBits=BIPED_MASK)

LOWER_FD = fixtureDef(shape=polygonShape(box=(0.8 * LEG_W / 2, LEG_H / 2)),
                      density=1.0,
                      restitution=0.0,
                      categoryBits=BIPED_CATEGORY,
                      maskBits=BIPED_MASK)

BALL_FD = fixtureDef(
    shape=circleShape(pos=(0, 0), radius=BALLR),
    density=0.5,  # 0.5
    friction=0.1,
    # friction=0.9, # OLD
    categoryBits=BALL_CATEGORY,
    maskBits=BALL_MASK,
    restitution=0.7)  # 0.99 bouncy

BALL_DAMPING = 1.


class ContactDetector(contactListener):
    def __init__(self, env):
        contactListener.__init__(self)
        self.env = env
Example #24
0
        def _create_decoration():
            objs = []
            objs.append(self.world.CreateStaticBody(
                position=(W/2, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=circleShape(radius=100/SCALE, pos=(0,0)),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (0.8,0.8,0.8)
            objs[-1].color2 = (0.8,0.8,0.8)

            objs.append(self.world.CreateStaticBody(
                position=(W/2, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=circleShape(radius=100/SCALE, pos=(0,0)),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (0.8,0.8,0.8)
            objs[-1].color2 = (0.8,0.8,0.8)

            objs.append(self.world.CreateStaticBody(
                position=(W/2-250/SCALE, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=circleShape(radius=70/SCALE, pos=(0,0)),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (255./255,204./255,191./255)
            objs[-1].color2 = (255./255,204./255,191./255)

            poly = [(0,100),(100,100),(100,-100),(0,-100)]
            objs.append(self.world.CreateStaticBody(
                position=(W/2-240/SCALE, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE, y/SCALE) for x, y in poly]),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (1,1,1)
            objs[-1].color2 = (1,1,1)

            objs.append(self.world.CreateStaticBody(
                position=(W/2+250/SCALE, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=circleShape(radius=70/SCALE, pos=(0,0)),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (255./255,204./255,191./255)
            objs[-1].color2 = (255./255,204./255,191./255)

            poly = [(100,100),(0,100),(0,-100),(100,-100)]
            objs.append(self.world.CreateStaticBody(
                position=(W/2+140/SCALE, H/2),
                angle=0.0,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE, y/SCALE) for x, y in poly]),
                    categoryBits = 0x0,
                    maskBits=0x0)
            ))
            objs[-1].color1 = (1,1,1)
            objs[-1].color2 = (1,1,1)

            return objs
# border_body2 = world.CreateStaticBody(position=(0,-0.4), shapes=border_shape_h)

# border_body3 = world.CreateStaticBody(position=(0.59,0), shapes=border_shape_v)

# border_body4 = world.CreateStaticBody(position=(-0.6,0), shapes=border_shape_v)

# env = [env_body, border_body1, border_body2, border_body3, border_body4]
# env = [env_body]
env = []

# create dynamic bodies
snowflakes = []

for ind in range(len(data)):
    row = data[ind]
    circle = circleShape(pos=(0, 0), radius=SNOWBALL_RADIUS)
    snowflake_body = world.CreateDynamicBody(position=row, userData=ind)
    fixture = snowflake_body.CreateFixture(
        fixtureDef(shape=circle, density=1, friction=0.3))
    snowflakes.append(snowflake_body)

force_magnitude = 1
force_decrement = force_magnitude / (end_frame - start_frame - 1)
# force_decrement = 0
force_vec = vec2(0.0001, 0)

# main game loop
running = True
frame = start_frame
while running:
    # Check the event queue
Example #26
0
    def _reset(self):
        self._destroy()
        self.world.contactListener_bug_workaround = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_bug_workaround
        self.game_over = False
        self.prev_shaping = None
        self.scroll = 0.0
        self.lidar_render = 0

        W = VIEWPORT_W / SCALE
        H = VIEWPORT_H / SCALE

        self._generate_terrain(self.hardcore)
        #        self._generate_clouds()

        init_x = TERRAIN_STEP * TERRAIN_STARTPAD / 2
        init_y = TERRAIN_HEIGHT + 2 * LEG_H
        self.hull = self.world.CreateDynamicBody(
            position=(init_x, init_y),
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in HULL_POLY]),
                density=11.0,
                friction=0.1,
                categoryBits=0x0020,
                maskBits=0x001,  # collide only with ground
                restitution=0.0)  # 0.99 bouncy
        )
        self.hull.color1 = (0.5, 0.4, 0.9)
        self.hull.color2 = (0.3, 0.3, 0.5)
        self.hull.ApplyForceToCenter(
            (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True)

        self.head = self.world.CreateDynamicBody(
            position=(init_x - 2 / SCALE, init_y + (HULL_H + 10) / SCALE),
            fixtures=fixtureDef(
                shape=circleShape(pos=[0, 0], radius=7.0 / SCALE),
                density=1.0,
                friction=0.1,
                categoryBits=0x0020,
                maskBits=0x001,  # collide only with ground
                restitution=0.0)  # 0.99 bouncy
        )
        self.head.color1 = (1.0, 0.4, 0.9)
        self.head.color2 = (0.3, 1.0, 0.5)
        #self.head.ApplyForceToCenter((self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True)

        self.legs = []
        self.arms = []
        self.joints = []

        rjd1 = revoluteJointDef(
            bodyA=self.head,
            bodyB=self.hull,
            localAnchorA=(0, 0),
            localAnchorB=(0, +(HULL_H) / SCALE),
            #            enableMotor=True,
            #            enableLimit=True,
            #            maxMotorTorque=MOTORS_TORQUE,
            #            motorSpeed = -1,
            #            lowerAngle = -0.8,
            #            upperAngle = 1.1,
        )

        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(init_x, init_y - LEG_H / 2 - LEG_DOWN),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(LEG_W / 2,
                                                            LEG_H / 2)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x001))
            leg.color1 = (0.6 - i / 10., 0.3 - i / 10., 0.5 - i / 10.)
            leg.color2 = (0.4 - i / 10., 0.2 - i / 10., 0.3 - i / 10.)
            rjd = revoluteJointDef(
                bodyA=self.hull,
                bodyB=leg,
                localAnchorA=(0, LEG_DOWN),
                localAnchorB=(0, LEG_H / 2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed=i,
                lowerAngle=-0.8,
                upperAngle=1.1,
            )
            self.legs.append(leg)
            self.joints.append(self.world.CreateJoint(rjd))

            lower = self.world.CreateDynamicBody(
                position=(init_x, init_y - LEG_H * 3 / 2 - LEG_DOWN),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(0.8 * LEG_W / 2,
                                                            LEG_H / 2)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x001))
            lower.color1 = (0.6 - i / 10., 0.3 - i / 10., 0.5 - i / 10.)
            lower.color2 = (0.4 - i / 10., 0.2 - i / 10., 0.3 - i / 10.)
            rjd = revoluteJointDef(
                bodyA=leg,
                bodyB=lower,
                localAnchorA=(0, -LEG_H / 2),
                localAnchorB=(0, LEG_H / 2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed=1,
                lowerAngle=-1.6,
                upperAngle=-0.1,
            )
            lower.ground_contact = False
            self.legs.append(lower)
            self.joints.append(self.world.CreateJoint(rjd))

        for i in [-1, +1]:
            arm = self.world.CreateDynamicBody(
                position=(init_x, init_y - arm_H / 2 + (HULL_H) / SCALE),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(arm_W / 2,
                                                            arm_H / 2)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x001))
            arm.color1 = (0.6 - i / 10., 0.3 - i / 10., 0.5 - i / 10.)
            arm.color2 = (0.4 - i / 10., 0.2 - i / 10., 0.3 - i / 10.)
            rjd = revoluteJointDef(
                bodyA=self.hull,
                bodyB=arm,
                localAnchorA=(0, (HULL_H) / SCALE),
                localAnchorB=(0, arm_H / 2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed=-i,
                lowerAngle=-0.8,
                upperAngle=0.8,
            )
            self.arms.append(arm)
            self.joints.append(self.world.CreateJoint(rjd))

#            lower_arm = self.world.CreateDynamicBody(
#                position = (init_x, init_y - arm_H*3/2 + (HULL_H)/SCALE),
#                angle = (i*0.05),
#                fixtures = fixtureDef(
#                    shape=polygonShape(box=(0.8*arm_W/2, arm_H/2)),
#                    density=1.0,
#                    restitution=0.0,
#                    categoryBits=0x0020,
#                    maskBits=0x001)
#                )
#            lower_arm.color1 = (0.6-i/10., 0.3-i/10., 0.5-i/10.)
#            lower_arm.color2 = (0.4-i/10., 0.2-i/10., 0.3-i/10.)
#            rjd = revoluteJointDef(
#                bodyA=arm,
#                bodyB=lower_arm,
#                localAnchorA=(0, -arm_H/2),
#                localAnchorB=(0, arm_H/2),
#                enableMotor=True,
#                enableLimit=True,
#                maxMotorTorque=MOTORS_TORQUE,
#                motorSpeed = 1,
#                lowerAngle = -1.6,
#                upperAngle = -0.1,
#                )
#            lower_arm.ground_contact = False
#            self.arms.append(lower_arm)
#            self.joints.append(self.world.CreateJoint(rjd))

        self.joints.append(self.world.CreateJoint(rjd1))
        self.drawlist = self.terrain + self.legs + self.arms + [self.hull] + [
            self.head
        ]

        class LidarCallback(Box2D.b2.rayCastCallback):
            def ReportFixture(self, fixture, point, normal, fraction):
                if (fixture.filterData.categoryBits & 1) == 0:
                    return 1
                self.p2 = point
                self.fraction = fraction
                return 0

        self.lidar = [LidarCallback() for _ in range(10)]

        self.ss = 1
        self.a = np.array([0, 0, 0, 0])
        return self._step([0])

        class LidarCallback(Box2D.b2.rayCastCallback):
            def ReportFixture(self, fixture, point, normal, fraction):
                if (fixture.filterData.categoryBits & 1) == 0:
                    return 1
                self.p2 = point
                self.fraction = fraction
                return 0

        self.lidar = [LidarCallback() for _ in range(10)]

        self.a = np.array([0, 0, 0, 0])
        return self._step(0)
Example #27
0
class BikeDef:
    """Defines constants for bike geometry and joints
    """

    # fixture151
    chassis_poly_2 = [(0.5925927162170410, 0.3970571756362915),
                      (0.5049575567245483, 0.5745437145233154),
                      (-0.1241288781166077, 0.3671160936355591),
                      (-0.3777002990245819, 0.01054022461175919),
                      (-0.1886725425720215, -0.3709129691123962),
                      (-0.01139009092003107, -0.4074897468090057),
                      (0.2494194805622101, -0.3823029100894928),
                      (0.4150831103324890, -0.01518678665161133)]
    chassis_fd_2 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_2]),
        density=1.0,
        friction=0.1,
        categoryBits=0x0020,
        restitution=0.1)

    # fixture155
    chassis_poly_3 = [(-0.1139258146286011, 0.3664703369140625),
                      (-0.7596390247344971, 0.4362251460552216),
                      (-0.7564918398857117, 0.3531839251518250),
                      (-0.3745602667331696, 0.004400946199893951)]
    chassis_fd_3 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_3]),
        density=0.01999,
        friction=0.10,
        categoryBits=0x0020,
        restitution=0.10)

    # fixture153
    chassis_poly_4 = [(0.9036020040512085, 0.4347184896469116),
                      (0.5974624752998352, 0.4441443085670471),
                      (0.4807239770889282, 0.2040471434593201),
                      (0.8664048910140991, 0.3509610295295715)]
    chassis_fd_4 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_4]),
        density=3.0,
        friction=0.1,
        categoryBits=0x0020,
        restitution=0.1)

    # fixture152
    chassis_poly_5 = [(0.8914304971694946, -0.07865893840789795),
                      (0.4427454471588135, 0.8150310516357422),
                      (0.3581824004650116, 0.7722809314727783),
                      (0.8068674802780151, -0.1214089989662170)]
    chassis_fd_5 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_5]),
        density=3.0,
        friction=0.1,
        categoryBits=0x0020,
        restitution=0.1)

    # fixture156
    chassis_poly_6 = [(-0.7481837272644043, 0.4318268001079559),
                      (-1.322828769683838, 0.4704772233963013),
                      (-1.085322141647339, 0.3916769027709961),
                      (-0.7573439478874207, 0.3553154766559601)]
    chassis_fd_6 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_6]),
        density=1.0,
        friction=0.1,
        categoryBits=0x0020,
        maskBits=0x00,
        restitution=0.1)

    # fixture150
    chassis_poly_7 = [(0.5167351365089417, 0.8024124503135681),
                      (0.258435457944870, 0.821202814579010),
                      (0.2579171955585480, 0.7468612790107727),
                      (0.5162168145179749, 0.7280706763267517)]
    chassis_fd_7 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_7]),
        density=1.0,
        friction=0.1,
        categoryBits=0x0020,
        restitution=0.1)

    # fixture154
    chassis_poly_8 = [(1.313481688499451, 0.2247920632362366),
                      (1.158682703971863, 0.3579198122024536),
                      (0.9046562314033508, 0.4359158873558044),
                      (0.8647161722183228, 0.3494157195091248)]
    chassis_fd_8 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_8]),
        density=3.0,
        friction=0.1,
        categoryBits=0x0020,
        restitution=0.1)

    # fixture11
    chassis_poly_9 = [(-0.4820806682109833, -0.3676601052284241),
                      (-0.5027866363525391, -0.2698271274566650),
                      (-0.6006187200546265, -0.2905341386795044),
                      (-0.5799126625061035, -0.3883671164512634)]
    chassis_fd_9 = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in chassis_poly_9]),
        density=76.0,
        friction=0.2,
        categoryBits=0x0020,
        maskBits=0x00,
        restitution=0.0)

    # fixture157
    front_wheel_fd = fixtureDef(
        shape=circleShape(radius=0.492374),
        density=0.07999,
        restitution=0.200,
        friction=0.0100,
        categoryBits=0x0020,
    )

    # fixture159
    rear_wheel_fd = fixtureDef(shape=circleShape(radius=0.450131),
                               density=0.01,
                               restitution=0.100,
                               friction=0.600,
                               categoryBits=0x0020)

    # fixture158
    swingarm_poly = [(0.4536499977111816, 0.06558109819889069),
                     (0.4325839877128601, 0.1579640060663223),
                     (-0.4387759864330292, -0.04519569873809814),
                     (-0.4177089929580688, -0.1375789940357208)]
    swingarm_fd = fixtureDef(
        shape=polygonShape(vertices=[(x, y) for x, y in swingarm_poly]),
        density=0.5000,
        restitution=0.100,
        friction=0.100,
        categoryBits=0x0020,
    )
Example #28
0
    def reset(self):
        self._destroy()
        self.world.contactListener_bug_workaround = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_bug_workaround
        self.game_over = False
        self.prev_shaping = None
        self.scroll = 0.0
        self.lidar_render = 0

        W = VIEWPORT_W / SCALE
        H = VIEWPORT_H / SCALE

        self._generate_terrain(self.hardcore)
        self._generate_clouds()

        # Process the fixtures
        # PolygonShape: vertices
        # EdgeShape: vertices
        # CircleShape: radius
        # friction, density, restitution, maskBits, categoryBits
        self.fixtures = {}
        for k in self.fixture_defs.keys():
            if self.fixture_defs[k]['FixtureShape']['Type'] == 'PolygonShape' or \
               self.fixture_defs[k]['FixtureShape']['Type'] == 'EdgeShape':
                fixture_shape = polygonShape(
                    vertices=[(x / SCALE, y / SCALE)
                              for x, y in self.fixture_defs[k]['FixtureShape']
                              ['Vertices']])
            elif self.fixture_defs[k]['FixtureShape']['Type'] == 'CircleShape':
                fixture_shape = circleShape(
                    radius=self.fixture_defs[k]['FixtureShape']['Radius'] /
                    SCALE)
            else:
                print("Invalid fixture type: " +
                      self.fixture_defs[k]['FixtureShape'])
                assert (False)
            self.fixtures[k] = fixtureDef(
                shape=fixture_shape,
                friction=self.fixture_defs[k]['Friction'],
                density=self.fixture_defs[k]['Density'],
                restitution=self.fixture_defs[k]['Restitution'],
                maskBits=self.fixture_defs[k]['MaskBits'],
                categoryBits=self.fixture_defs[k]['CategoryBits'])

        # Process the dynamic bodies
        # position, angle,  fixture,
        self.bodies = {}
        for k in self.body_defs.keys():
            if False and k == 'Hull':
                self.bodies[k] = self.world.CreateStaticBody(
                    position=[
                        x / SCALE for x in self.body_defs[k]['Position']
                    ],
                    angle=self.body_defs[k]['Angle'],
                    fixtures=[
                        self.fixtures[f]
                        for f in self.body_defs[k]['FixtureNames']
                    ])
            else:
                self.bodies[k] = self.world.CreateDynamicBody(
                    position=[
                        x / SCALE for x in self.body_defs[k]['Position']
                    ],
                    angle=self.body_defs[k]['Angle'],
                    fixtures=[
                        self.fixtures[f]
                        for f in self.body_defs[k]['FixtureNames']
                    ])
            self.bodies[k].color1 = self.body_defs[k]['Color1']
            self.bodies[k].color2 = self.body_defs[k]['Color2']
            self.bodies[k].can_touch_ground = self.body_defs[k][
                'CanTouchGround']
            self.bodies[k].ground_contact = False
            self.bodies[k].depth = self.body_defs[k]['Depth']
            self.bodies[k].connected_body = []
            self.bodies[k].connected_joints = []

            # Apply a force to the 'center' body
            if k == 'Hull':
                self.bodies[k].ApplyForceToCenter((self.np_random.uniform(
                    -self.body_defs[k]['InitialForceScale'],
                    self.body_defs[k]['InitialForceScale']), 0), True)
        self.body_state_order = copy.deepcopy(list(self.bodies_to_report_keys))
        self.all_bodies_order = copy.deepcopy(
            self.body_state_order) + copy.deepcopy([
                k for k in self.body_defs.keys()
                if k not in self.body_state_order
            ])
        for i in range(len(self.all_bodies_order)):
            k = self.all_bodies_order[i]
            self.bodies[k].index = i

        # Process the joint motors
        # bodyA, bodyB, localAnchorA, localAnchorB, enableMotor, enableLimit,
        # maxMotorTorque, motorSpeed, lowerAngle, upperAngle
        self.joints = {}
        for k in self.joint_defs.keys():
            self.joints[k] = self.world.CreateJoint(
                revoluteJointDef(
                    bodyA=self.bodies[self.joint_defs[k]['BodyA']],
                    bodyB=self.bodies[self.joint_defs[k]['BodyB']],
                    localAnchorA=[
                        x / SCALE for x in self.joint_defs[k]['LocalAnchorA']
                    ],
                    localAnchorB=[
                        x / SCALE for x in self.joint_defs[k]['LocalAnchorB']
                    ],
                    enableMotor=self.joint_defs[k]['EnableMotor'],
                    enableLimit=self.joint_defs[k]['EnableLimit'],
                    maxMotorTorque=self.joint_defs[k]['MaxMotorTorque'],
                    motorSpeed=self.joint_defs[k]['MotorSpeed'],
                    lowerAngle=self.joint_defs[k]['LowerAngle'],
                    upperAngle=self.joint_defs[k]['UpperAngle']))
            self.joints[k].depth = self.joint_defs[k]['Depth']
            self.joints[k].connected_body = []
            self.joints[k].connected_joints = []

        # Process the body linkages
        # bodyA, bodyB, anchor
        self.linkages = {}
        for k in self.linkage_defs.keys():
            self.linkages[k] = self.world.CreateJoint(
                weldJointDef(bodyA=self.bodies[self.linkage_defs[k]['BodyA']],
                             bodyB=self.bodies[self.linkage_defs[k]['BodyB']],
                             localAnchorA=[
                                 x / SCALE
                                 for x in self.linkage_defs[k]['LocalAnchorA']
                             ],
                             localAnchorB=[
                                 x / SCALE
                                 for x in self.linkage_defs[k]['LocalAnchorB']
                             ],
                             frequencyHz=self.linkage_defs[k]['FrequencyHz']))

        # Joints we want to report state is a superset of joints we want to allow action
        self.joint_action_order = copy.deepcopy(list(self.enabled_joints_keys))
        if self.truncate_state:
            self.joint_state_order = copy.deepcopy(self.joint_action_order) \
                + copy.deepcopy([k for k in self.joint_defs.keys()
                    if k not in self.joint_action_order and self.joint_defs[k]['ReportState']])
        else:
            self.joint_state_order = copy.deepcopy(self.joint_action_order) \
                + copy.deepcopy([k for k in self.joint_defs.keys()
                    if k not in self.joint_action_order])

        self.all_joints_order = copy.deepcopy(
            self.joint_state_order) + copy.deepcopy([
                k for k in self.joint_defs.keys()
                if k not in self.joint_state_order
            ])
        for i in range(len(self.all_joints_order)):
            k = self.all_joints_order[i]
            self.joints[k].index = i

        # Construct index links between bodies and joints
        for k in self.joint_defs.keys():
            self.bodies[self.joint_defs[k]['BodyA']].connected_body.append(
                self.bodies[self.joint_defs[k]['BodyB']].index)
            self.bodies[self.joint_defs[k]['BodyB']].connected_body.append(
                self.bodies[self.joint_defs[k]['BodyA']].index)
            self.bodies[self.joint_defs[k]['BodyA']].connected_joints.append(
                self.joints[k].index)
            self.bodies[self.joint_defs[k]['BodyB']].connected_joints.append(
                self.joints[k].index)

            self.joints[k].connected_body.append(
                self.bodies[self.joint_defs[k]['BodyA']].index)
            self.joints[k].connected_body.append(
                self.bodies[self.joint_defs[k]['BodyB']].index)

        # Construct index links between hull segments via linkages
        for k in self.linkage_defs.keys():
            self.bodies[self.linkage_defs[k]['BodyA']].connected_body.append(
                self.bodies[self.linkage_defs[k]['BodyB']].index)
            self.bodies[self.linkage_defs[k]['BodyB']].connected_body.append(
                self.bodies[self.linkage_defs[k]['BodyA']].index)

        # Construct index links between joints connected to same body
        for k_joint in self.joints.keys():
            for i_body in self.joints[k_joint].connected_body:
                k_body = self.all_bodies_order[i_body]
                for i_jointB in self.bodies[k_body].connected_joints:
                    # Avoid adding self-links
                    if self.joints[k_joint].index == i_jointB:
                        continue
                    # Keep uniqueness of lists
                    if i_jointB in self.joints[k_joint].connected_joints:
                        continue
                    self.joints[k_joint].connected_joints.append(i_jointB)

        # Make sure hull is last
        self.drawlist = self.terrain + list(self.bodies.values())

        class LidarCallback(Box2D.b2.rayCastCallback):
            def ReportFixture(self, fixture, point, normal, fraction):
                if (fixture.filterData.categoryBits & 1) == 0:
                    return 1
                self.p2 = point
                self.fraction = fraction
                return 0

        self.lidar = [LidarCallback() for _ in range(10)]

        ob, _, _, info = self.step(np.zeros(self.action_space.shape))
        return ob, info
Example #29
0
    def reset(self):
        if self.scores is None:
            self.scores = deque(maxlen=100)
        else:
            if self.achieve_goal:
                self.scores.append(1)
            else:
                self.scores.append(0)

        if self.verbose:
            self.verbosing()

        self.game_over = False
        self.prev_shaping = None
        self.achieve_goal = False
        self.strike_by_obstacle = False
        self.speed_table = np.zeros(len(OBSTACLE_POSITIONS))
        # timer
        self.energy = 1
        # clean up objects in the Box 2D world
        self._destroy()
        # create lidar objects
        self.lidar = [LidarCallback() for _ in range(self.num_beams)]
        self.world.contactListener_keepref = ContactDetector(self)
        self.world.contactListener = self.world.contactListener_keepref

        # create new world
        self.moon = self.world.CreateStaticBody(shapes=edgeShape(
            vertices=[(0, 0), (W, 0)]))
        p1 = (1, 1)
        p2 = (W - 1, 1)
        self.moon.CreateEdgeFixture(
            vertices=[p1, p2],
            density=100,
            friction=0,
            restitution=1.0,
        )
        self._build_wall()
        self.moon.color1 = (0.0, 0.0, 0.0)
        self.moon.color2 = (0.0, 0.0, 0.0)

        # create obstacles
        self._build_obstacles()

        # create controller object
        while True:
            drone_pos = (int(np.random.randint(1, 10)),
                         int(np.random.randint(1, 5)))
            self.drone = self.world.CreateDynamicBody(
                position=drone_pos,
                angle=0.0,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                                 for x, y in DRONE_POLY]),
                    density=5.0,
                    friction=0.1,
                    categoryBits=0x0010,
                    maskBits=0x003,  # collide all but obs range object
                    restitution=0.0)  # 0.99 bouncy
            )
            self.drone.color1 = (0.5, 0.4, 0.9)
            self.drone.color2 = (0.3, 0.3, 0.5)
            self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)
            if self.game_over:
                self.world.DestroyBody(self.drone)
                self.game_over = False
            else:
                break
        # create goal
        goal_pos = GOAL_POS[np.random.randint(len(GOAL_POS))]
        self.goal = self.world.CreateStaticBody(
            position=goal_pos,
            angle=0.0,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in DRONE_POLY]),
                density=5.0,
                friction=0.1,
                categoryBits=0x002,
                maskBits=0x0010,  # collide only with control device
                restitution=0.0)  # 0.99 bouncy
        )
        self.goal.color1 = (0., 0.5, 0)
        self.goal.color2 = (0., 0.5, 0)

        self.obs_range_plt = self.world.CreateKinematicBody(
            position=(self.drone.position[0], self.drone.position[1]),
            angle=0.0,
            fixtures=fixtureDef(
                shape=circleShape(radius=np.float64(self.max_obs_range),
                                  pos=(0, 0)),
                density=0,
                friction=0,
                categoryBits=0x0100,
                maskBits=0x000,  # collide with nothing
                restitution=0.3))
        self.obs_range_plt.color1 = (0.2, 0.2, 0.4)
        self.obs_range_plt.color2 = (0.6, 0.6, 0.6)
        self.drawlist = [self.obs_range_plt, self.drone, self.goal
                         ] + self.walls + self.obstacles
        self._observe_lidar(drone_pos)
        self.world.Step(1.0 / FPS, 6 * 30, 2 * 30)
        return np.copy(self.array_observation())
# border_body3 = world.CreateStaticBody(position=(0.59,0), shapes=border_shape_v)

# border_body4 = world.CreateStaticBody(position=(-0.6,0), shapes=border_shape_v)

# env = [env_body, border_body1, border_body2, border_body3, border_body4]
# env = [env_body]
# env = []

# create strings
string1 = data_to_vecs(
    pd.read_csv("frame0stroke2.csv", delimiter=",", header=None))
chain1 = []
for ind in range(len(string1)):
    row = string1[ind]
    circle = circleShape(pos=(0, 0), radius=0.001)
    new_body = world.CreateDynamicBody(position=row, userData=ind)
    fixture = new_body.CreateFixture(
        fixtureDef(shape=circle, density=1, friction=0.3))
    chain1.append(new_body)

    if ind > 0:
        world.CreateRevoluteJoint(bodyA=chain1[ind - 1],
                                  bodyB=new_body,
                                  anchor=chain1[ind - 1].worldCenter)

world.CreateRevoluteJoint(bodyA=chain1[0],
                          bodyB=balloon1_knot_body,
                          anchor=chain1[0].worldCenter)

string2 = data_to_vecs(
                      categoryBits=0x0020,
                      maskBits=0x001)

ARM_FD = fixtureDef(shape=polygonShape(box=(ARM_W / 2, ARM_H / 2)),
                    density=1.0,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001)

UPPER_FD = fixtureDef(shape=polygonShape(box=(0.8 * LEG_W / 2, LEG_H / 2)),
                      density=1.0,
                      restitution=0.0,
                      categoryBits=0x0020,
                      maskBits=0x001)

HEAD_FD = fixtureDef(shape=circleShape(radius=HEAD_R),
                     density=1.0,
                     restitution=0.0,
                     categoryBits=0x0020,
                     maskBits=0x001)


class ContactDetector(contactListener):
    def __init__(self, env):
        contactListener.__init__(self)
        self.env = env

    def BeginContact(self, contact):
        # Die if head, hull, or arms touch ground
        for fixt in [self.env.head, self.env.hull] + self.env.arms:
            if fixt == contact.fixtureA.body or fixt == contact.fixtureB.body:
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("SuperKoolt spel")
clock = pygame.time.Clock()

world = b2d.world(gravity=(0, -GRAVITY), doSleep=True)

world.CreateStaticBody(position=(0, 0),
                       shapes=b2d.polygonShape(box=(0.01, 100)))  #Left wall
world.CreateStaticBody(position=(float(WIDTH / PPM), 0),
                       shapes=b2d.polygonShape(box=(0.01, 100)))  #Right wall
world.CreateStaticBody(position=(0, float(HEIGHT / PPM)),
                       shapes=b2d.polygonShape(box=(100, 0.01)))  #Ceiling

pad_body = world.CreateKinematicBody(position=(WIDTH / (PPM * 2),
                                               0.3 - PAD_RADIUS),
                                     shapes=b2d.circleShape(radius=PAD_RADIUS))
pad_body.mass = 10000
pad_body.fixedRotation = True

pygame.key.set_repeat(10, 10)

balls = []


def draw():
    screen.fill((0, 0, 0, 255))  #Clear screen
    for ball in balls:
        draw_circle(ball, BALL_RADIUS)
    draw_circle(pad_body, PAD_RADIUS)

    screen.blit(font.render(str(frames / TARGET_FPS), 1, (255, 255, 255)),