Пример #1
0
    def __init__(self):
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World()
        self.terrain = None
        self.hull = None

        self.prev_shaping = None

        self.fd_polygon = fixtureDef(
                        shape = polygonShape(vertices=
                        [(0, 0),
                         (1, 0),
                         (1, -1),
                         (0, -1)]),
                        friction = FRICTION)

        self.fd_edge = fixtureDef(
                    shape = edgeShape(vertices=
                    [(0, 0),
                     (1, 1)]),
                    friction = FRICTION,
                    categoryBits=0x0001,
                )

        self.reset()

        high = np.array([np.inf]*24)
        self.action_space = spaces.Box(np.array([-1,-1,-1,-1]), np.array([+1,+1,+1,+1]))
        self.observation_space = spaces.Box(-high, high)
Пример #2
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,
        )
Пример #3
0
 def __init__(self, world, init_angle, init_x, init_y):
     self.world = world
     self.hull = self.world.CreateDynamicBody(
         position = (init_x, init_y),
         angle = init_angle,
         fixtures = [
             fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY1 ]), density=1.0),
             fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY2 ]), density=1.0),
             fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY3 ]), density=1.0),
             fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY4 ]), density=1.0)
             ]
         )
     self.hull.color = (0.8,0.0,0.0)
     self.wheels = []
     self.fuel_spent = 0.0
     WHEEL_POLY = [
         (-WHEEL_W,+WHEEL_R), (+WHEEL_W,+WHEEL_R),
         (+WHEEL_W,-WHEEL_R), (-WHEEL_W,-WHEEL_R)
         ]
     for wx,wy in WHEELPOS:
         front_k = 1.0 if wy > 0 else 1.0
         w = self.world.CreateDynamicBody(
             position = (init_x+wx*SIZE, init_y+wy*SIZE),
             angle = init_angle,
             fixtures = fixtureDef(
                 shape=polygonShape(vertices=[ (x*front_k*SIZE,y*front_k*SIZE) for x,y in WHEEL_POLY ]),
                 density=0.1,
                 categoryBits=0x0020,
                 maskBits=0x001,
                 restitution=0.0)
                 )
         w.wheel_rad = front_k*WHEEL_R*SIZE
         w.color = WHEEL_COLOR
         w.gas   = 0.0
         w.brake = 0.0
         w.steer = 0.0
         w.phase = 0.0  # wheel angle
         w.omega = 0.0  # angular velocity
         w.skid_start = None
         w.skid_particle = None
         rjd = revoluteJointDef(
             bodyA=self.hull,
             bodyB=w,
             localAnchorA=(wx*SIZE,wy*SIZE),
             localAnchorB=(0,0),
             enableMotor=True,
             enableLimit=True,
             maxMotorTorque=180*900*SIZE*SIZE,
             motorSpeed = 0,
             lowerAngle = -0.4,
             upperAngle = +0.4,
             )
         w.joint = self.world.CreateJoint(rjd)
         w.tiles = set()
         w.userData = w
         self.wheels.append(w)
     self.drawlist =  self.wheels + [self.hull]
     self.particles = []
Пример #4
0
    def _create_lander(self, lander, number_of_landers):
        initial_y = VIEWPORT_H/SCALE
        body_xpos = (lander.player_id + 1) * VIEWPORT_W/SCALE / (number_of_landers + 1)
        body_ypos = initial_y
        body = self.world.CreateDynamicBody(
            position = (body_xpos, body_ypos),
            angle=0.0,
            fixtures = 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
                )
        body.color1 = (0.5,0.4,0.9)
        body.color2 = (0.3,0.3,0.5)
        body.ApplyForceToCenter( (
            self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
            self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM)
            ), True)

        legs = []
        for i in [-1,+1]:
            leg = self.world.CreateDynamicBody(
                position = (body_xpos - i*LEG_AWAY/SCALE, body_ypos),
                angle = (i*0.05),
                fixtures = fixtureDef(
                    shape=polygonShape(box=(LEG_W/SCALE, LEG_H/SCALE)),
                    density=1.0,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001)
                )
            leg.ground_contact = False
            leg.color1 = (0.5,0.4,0.9)
            leg.color2 = (0.3,0.3,0.5)
            rjd = revoluteJointDef(
                bodyA=body,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i*LEG_AWAY/SCALE, LEG_DOWN/SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3*i  # low enough not to jump back into the sky
                )
            if i==-1:
                rjd.lowerAngle = +0.9 - 0.5  # Yes, the most esoteric numbers here, angles legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            legs.append(leg)
        lander.body, lander.legs = body, legs
Пример #5
0
    def __init__(self):
        self.trackWidth = 5.0
        self.cartWidth = 0.3
        self.cartHeight = 0.2
        self.cartMass = 10
        self.poleMass = 1
        self.force = 0.2
        self.trackThickness = self.cartHeight
        self.poleLength = 0.5
        self.poleThickness = 0.04

        self.screenSize = (640,480) #origin upper left
        self.worldSize = (float(self.trackWidth),float(self.trackWidth)) #origin at center

        self.world = b2.world(gravity=(0,-9.81),doSleep=True)
        self.framesPerSecond = 10 # used for dynamics update and for graphics update
        self.velocityIterations = 8
        self.positionIterations = 6

        # Make track bodies and fixtures
        self.trackColor = (100,100,100)
        poleCategory = 0x0002

        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackWidth/2,self.trackThickness/2)),
                          friction=0.000, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory))
        self.track = self.world.CreateStaticBody(position = (0,0), 
                                                 fixtures=f, userData={'color': self.trackColor})
        self.trackTop = self.world.CreateStaticBody(position = (0,self.trackThickness+self.cartHeight*1.1),
                                                    fixtures = f)

        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackThickness/2,self.trackThickness/2)),
                          friction=0.000, categoryBits=0x0001, maskBits=(0xFFFF & ~poleCategory))
        self.wallLeft = self.world.CreateStaticBody(position = (-self.trackWidth/2+self.trackThickness/2, self.trackThickness),
                                               fixtures=f, userData={'color': self.trackColor})
        self.wallRight = self.world.CreateStaticBody(position = (self.trackWidth/2-self.trackThickness/2, self.trackThickness),
                                                fixtures=f,userData={'color': self.trackColor})

        # Make cart body and fixture
        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.cartWidth/2,self.cartHeight/2)),
                          density=self.cartMass, friction=0.000, restitution=0.5, categoryBits=0x0001,
                          maskBits=(0xFFFF & ~poleCategory))
        self.cart = self.world.CreateDynamicBody(position=(0,self.trackThickness),
                                            fixtures=f, userData={'color':(20,200,0)})

        # Make pole pody and fixture
        # Initially pole is hanging down, which defines the zero angle.
        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.poleThickness/2, self.poleLength/2)),
                          density=self.poleMass, categoryBits=poleCategory)
        self.pole = self.world.CreateDynamicBody(position=(0,self.trackThickness+self.cartHeight/2+self.poleThickness-self.poleLength/2),
                                            fixtures=f, userData={'color':(200,20,0)})

        # Make pole-cart joint
        rj = self.world.CreateRevoluteJoint(bodyA = self.pole, bodyB = self.cart,
                                  anchor=(0,self.trackThickness+self.cartHeight/2+self.poleThickness))
Пример #6
0
    def __init__(self):
        super(Chain, self).__init__()

        # The ground
        ground = self.world.CreateBody(
            shapes=edgeShape(vertices=[(-40, 0), (40, 0)])
        )

        plank = fixtureDef(
            shape=polygonShape(box=(0.6, 0.125)),
            density=20,
            friction=0.2,
        )

        # Create one Chain (Only the left end is fixed)
        prevBody = ground
        y = 25
        numPlanks = 30
        for i in range(numPlanks):
            body = self.world.CreateDynamicBody(
                position=(0.5 + i, y),
                fixtures=plank,
            )

            # You can try a WeldJoint for a slightly different effect.
            # self.world.CreateWeldJoint(
            self.world.CreateRevoluteJoint(
                bodyA=prevBody,
                bodyB=body,
                anchor=(i, y),
            )

            prevBody = body
Пример #7
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 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
        self.throttle = 0
        self.gimbal = 0.0
        self.landed_ticks = 0
        self.stepnumber = 0
        self.smoke = []

        # self.terrainheigth = self.np_random.uniform(H / 20, H / 10)
        self.terrainheigth = H / 20
        self.shipheight = self.terrainheigth + SHIP_HEIGHT
        # ship_pos = self.np_random.uniform(0, SHIP_WIDTH / SCALE) + SHIP_WIDTH / SCALE
        ship_pos = W / 2
        self.helipad_x1 = ship_pos - SHIP_WIDTH / 2
        self.helipad_x2 = self.helipad_x1 + SHIP_WIDTH
        self.helipad_y = self.terrainheigth + SHIP_HEIGHT

        self.water = self.world.CreateStaticBody(
            fixtures=fixtureDef(
                shape=polygonShape(vertices=((0, 0), (W, 0), (W, self.terrainheigth), (0, self.terrainheigth))),
                friction=0.1,
                restitution=0.0)
        )
        self.water.color1 = rgb(70, 96, 176)

        self.ship = self.world.CreateStaticBody(
            fixtures=fixtureDef(
                shape=polygonShape(
                    vertices=((self.helipad_x1, self.terrainheigth),
                              (self.helipad_x2, self.terrainheigth),
                              (self.helipad_x2, self.terrainheigth + SHIP_HEIGHT),
                              (self.helipad_x1, self.terrainheigth + SHIP_HEIGHT))),
                friction=0.5,
                restitution=0.0)
        )

        self.containers = []
        for side in [-1, 1]:
            self.containers.append(self.world.CreateStaticBody(
                fixtures=fixtureDef(
                    shape=polygonShape(
                        vertices=((ship_pos + side * 0.95 * SHIP_WIDTH / 2, self.helipad_y),
                                  (ship_pos + side * 0.95 * SHIP_WIDTH / 2, self.helipad_y + SHIP_HEIGHT),
                                  (ship_pos + side * 0.95 * SHIP_WIDTH / 2 - side * SHIP_HEIGHT,
                                   self.helipad_y + SHIP_HEIGHT),
                                  (ship_pos + side * 0.95 * SHIP_WIDTH / 2 - side * SHIP_HEIGHT, self.helipad_y)
                                  )),
                    friction=0.2,
                    restitution=0.0)
            ))
            self.containers[-1].color1 = rgb(206, 206, 2)

        self.ship.color1 = (0.2, 0.2, 0.2)

        initial_x = W / 2 + W * np.random.uniform(-0.3, 0.3)
        initial_y = H * 0.95
        self.lander = self.world.CreateDynamicBody(
            position=(initial_x, initial_y),
            angle=0.0,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=((-ROCKET_WIDTH / 2, 0),
                                             (+ROCKET_WIDTH / 2, 0),
                                             (ROCKET_WIDTH / 2, +ROCKET_HEIGHT),
                                             (-ROCKET_WIDTH / 2, +ROCKET_HEIGHT))),
                density=1.0,
                friction=0.5,
                categoryBits=0x0010,
                maskBits=0x001,
                restitution=0.0)
        )

        self.lander.color1 = rgb(230, 230, 230)

        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(initial_x - i * LEG_AWAY, initial_y + ROCKET_WIDTH * 0.2),
                angle=(i * BASE_ANGLE),
                fixtures=fixtureDef(
                    shape=polygonShape(
                        vertices=((0, 0), (0, LEG_LENGTH / 25), (i * LEG_LENGTH, 0), (i * LEG_LENGTH, -LEG_LENGTH / 20),
                                  (i * LEG_LENGTH / 3, -LEG_LENGTH / 7))),
                    density=1,
                    restitution=0.0,
                    friction=0.2,
                    categoryBits=0x0020,
                    maskBits=0x001)
            )
            leg.ground_contact = False
            leg.color1 = (0.25, 0.25, 0.25)
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(i * LEG_AWAY, ROCKET_WIDTH * 0.2),
                localAnchorB=(0, 0),
                enableLimit=True,
                maxMotorTorque=2500.0,
                motorSpeed=-0.05 * i,
                enableMotor=True
            )
            djd = distanceJointDef(bodyA=self.lander,
                                   bodyB=leg,
                                   anchorA=(i * LEG_AWAY, ROCKET_HEIGHT / 8),
                                   anchorB=leg.fixtures[0].body.transform * (i * LEG_LENGTH, 0),
                                   collideConnected=False,
                                   frequencyHz=0.01,
                                   dampingRatio=0.9
                                   )
            if i == 1:
                rjd.lowerAngle = -SPRING_ANGLE
                rjd.upperAngle = 0
            else:
                rjd.lowerAngle = 0
                rjd.upperAngle = + SPRING_ANGLE
            leg.joint = self.world.CreateJoint(rjd)
            leg.joint2 = self.world.CreateJoint(djd)

            self.legs.append(leg)

        self.lander.linearVelocity = (
            -self.np_random.uniform(0, INITIAL_RANDOM) * START_SPEED * (initial_x - W / 2) / W,
            -START_SPEED)

        self.lander.angularVelocity = (1 + INITIAL_RANDOM) * np.random.uniform(-1, 1)

        self.drawlist = self.legs + [self.water] + [self.ship] + self.containers + [self.lander]

        if CONTINUOUS:
            return self.step([0, 0, 0])[0]
        else:
            return self.step(6)[0]
Пример #9
0
LEG_W, LEG_H = 8/SCALE, 34/SCALE

VIEWPORT_W = 600
VIEWPORT_H = 400

TERRAIN_STEP   = 14/SCALE
TERRAIN_LENGTH = 200     # in steps
TERRAIN_HEIGHT = VIEWPORT_H/SCALE/4
TERRAIN_GRASS    = 10    # low long are grass spots, in steps
TERRAIN_STARTPAD = 20    # in steps
FRICTION = 2.5

HULL_FD = fixtureDef(
                shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in HULL_POLY ]),
                density=5.0,
                friction=0.1,
                categoryBits=0x0020,
                maskBits=0x001,  # collide only with ground
                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=0x0020,
                    maskBits=0x001)

LOWER_FD = fixtureDef(
                    shape=polygonShape(box=(0.8*LEG_W/2, LEG_H/2)),
                    density=1.0,
                    restitution=0.0,
Пример #10
0
    def reset(self):
        if self.scores is None:
            self.scores = deque(maxlen=10000)
        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())
Пример #11
0
    def _generate_terrain(self, hardcore):
        GRASS, STUMP, STAIRS, PIT, _STATES_ = range(5)
        state = GRASS
        velocity = 0.0
        y = TERRAIN_HEIGHT
        counter = TERRAIN_STARTPAD
        oneshot = False
        self.terrain = []
        self.terrain_x = []
        self.terrain_y = []
        for i in range(self.terrain_length):
            x = i * TERRAIN_STEP
            self.terrain_x.append(x)

            if state == GRASS and not oneshot:
                velocity = 0.8 * velocity + 0.01 * np.sign(TERRAIN_HEIGHT - y)
                if i > TERRAIN_STARTPAD:
                    velocity += self.np_random.uniform(-1, 1) / SCALE
                y += velocity

            elif state == PIT and oneshot:
                counter = self.np_random.randint(3, 5)
                poly = [
                    (x, y),
                    (x + TERRAIN_STEP, y),
                    (x + TERRAIN_STEP, y - 4 * TERRAIN_STEP),
                    (x, y - 4 * TERRAIN_STEP),
                ]
                t = self.world.CreateStaticBody(fixtures=fixtureDef(
                    shape=polygonShape(vertices=poly), friction=FRICTION))
                t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
                self.terrain.append(t)
                t = self.world.CreateStaticBody(
                    fixtures=fixtureDef(shape=polygonShape(
                        vertices=[(p[0] + TERRAIN_STEP * counter, p[1])
                                  for p in poly]),
                                        friction=FRICTION))
                t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
                self.terrain.append(t)
                counter += 2
                original_y = y

            elif state == PIT and not oneshot:
                y = original_y
                if counter > 1:
                    y -= 4 * TERRAIN_STEP

            elif state == STUMP and oneshot:
                counter = self.np_random.randint(1, 3)
                poly = [
                    (x, y),
                    (x + counter * TERRAIN_STEP, y),
                    (x + counter * TERRAIN_STEP, y + counter * TERRAIN_STEP),
                    (x, y + counter * TERRAIN_STEP),
                ]
                t = self.world.CreateStaticBody(fixtures=fixtureDef(
                    shape=polygonShape(vertices=poly), friction=FRICTION))
                t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
                self.terrain.append(t)

            elif state == STAIRS and oneshot:
                stair_height = +1 if self.np_random.rand() > 0.5 else -1
                stair_width = self.np_random.randint(4, 5)
                stair_steps = self.np_random.randint(3, 5)
                original_y = y
                for s in range(stair_steps):
                    poly = [
                        (x + (s * stair_width) * TERRAIN_STEP,
                         y + (s * stair_height) * TERRAIN_STEP),
                        (x + ((1 + s) * stair_width) * TERRAIN_STEP,
                         y + (s * stair_height) * TERRAIN_STEP),
                        (x + ((1 + s) * stair_width) * TERRAIN_STEP,
                         y + (-1 + s * stair_height) * TERRAIN_STEP),
                        (x + (s * stair_width) * TERRAIN_STEP,
                         y + (-1 + s * stair_height) * TERRAIN_STEP),
                    ]
                    t = self.world.CreateStaticBody(fixtures=fixtureDef(
                        shape=polygonShape(vertices=poly), friction=FRICTION))
                    t.color1, t.color2 = (1, 1, 1), (0.6, 0.6, 0.6)
                    self.terrain.append(t)
                counter = stair_steps * stair_width

            elif state == STAIRS and not oneshot:
                s = stair_steps * stair_width - counter - stair_height
                n = s / stair_width
                y = original_y + (n * stair_height) * TERRAIN_STEP

            oneshot = False
            self.terrain_y.append(y)
            counter -= 1
            if counter == 0:
                counter = self.np_random.randint(TERRAIN_GRASS / 2,
                                                 TERRAIN_GRASS)
                if state == GRASS and hardcore:
                    state = self.np_random.randint(1, _STATES_)
                    oneshot = True
                else:
                    state = GRASS
                    oneshot = True

        self.terrain_poly = []
        for i in range(self.terrain_length - 1):
            poly = [(self.terrain_x[i], self.terrain_y[i]),
                    (self.terrain_x[i + 1], self.terrain_y[i + 1])]
            t = self.world.CreateStaticBody(fixtures=fixtureDef(
                shape=edgeShape(vertices=poly),
                friction=FRICTION,
                categoryBits=0x0001,
            ))
            color = (0.3, 1.0 if i % 2 == 0 else 0.8, 0.3)
            t.color1 = color
            t.color2 = color
            self.terrain.append(t)
            color = (0.4, 0.6, 0.3)
            poly += [(poly[1][0], 0), (poly[0][0], 0)]
            self.terrain_poly.append((poly, color))
        self.terrain.reverse()
Пример #12
0
    def _create_track(self):
        # Creating Road Sections:
        # See notes:
        road_s1 = [(-ROAD_WIDTH, ROAD_WIDTH), (-ROAD_WIDTH, -ROAD_WIDTH),
                   (ROAD_WIDTH, -ROAD_WIDTH), (ROAD_WIDTH, ROAD_WIDTH)]

        road_s2 = [(-PLAYFIELD, ROAD_WIDTH), (-PLAYFIELD, 0), (-ROAD_WIDTH, 0),
                   (-ROAD_WIDTH, ROAD_WIDTH)]
        road_s3 = [(-PLAYFIELD, 0), (-PLAYFIELD, -ROAD_WIDTH),
                   (-ROAD_WIDTH, -ROAD_WIDTH), (-ROAD_WIDTH, 0)]

        road_s4 = [(-ROAD_WIDTH, -ROAD_WIDTH), (-ROAD_WIDTH, -PLAYFIELD),
                   (0, -PLAYFIELD), (0, -ROAD_WIDTH)]
        road_s5 = [(0, -ROAD_WIDTH), (0, -PLAYFIELD), (ROAD_WIDTH, -PLAYFIELD),
                   (ROAD_WIDTH, -ROAD_WIDTH)]

        road_s6 = [(ROAD_WIDTH, 0), (ROAD_WIDTH, -ROAD_WIDTH),
                   (PLAYFIELD, -ROAD_WIDTH), (PLAYFIELD, 0)]
        road_s7 = [(ROAD_WIDTH, ROAD_WIDTH), (ROAD_WIDTH, 0), (PLAYFIELD, 0),
                   (PLAYFIELD, ROAD_WIDTH)]

        road_s8 = [(0, PLAYFIELD), (0, ROAD_WIDTH), (ROAD_WIDTH, ROAD_WIDTH),
                   (ROAD_WIDTH, PLAYFIELD)]
        road_s9 = [(-ROAD_WIDTH, PLAYFIELD), (-ROAD_WIDTH, ROAD_WIDTH),
                   (0, ROAD_WIDTH), (0, PLAYFIELD)]

        # Creating body of roads:
        self.road_poly = road_s1 + road_s2 + road_s3 + road_s4 + road_s5 + road_s6 + road_s7
        if self.track_form == 'X':
            self.road_poly += road_s8 + road_s9

        self.road = []

        # Creating a static object - road with names for specific section + i need to define how to listen to it:
        for i in range(0, len(self.road_poly), 4):
            r = self.world.CreateStaticBody(
                fixtures=fixtureDef(shape=polygonShape(
                    vertices=self.road_poly[i:i + 4]),
                                    isSensor=True))
            r.road_section = int(i / 4) + 1
            r.name = 'road'
            r.userData = r
            self.road.append(r)

        # Creating sidewalks:
        sidewalk_h_nw = [(-PLAYFIELD, ROAD_WIDTH + SIDE_WALK),
                         (-PLAYFIELD, ROAD_WIDTH),
                         (-ROAD_WIDTH - SIDE_WALK * 2, ROAD_WIDTH),
                         (-ROAD_WIDTH - SIDE_WALK * 2, ROAD_WIDTH + SIDE_WALK)]
        sidewalk_h_sw = [(x, y - 2 * ROAD_WIDTH - SIDE_WALK)
                         for x, y in sidewalk_h_nw]
        sidewalk_h_ne = [(x + PLAYFIELD + 2 * SIDE_WALK + ROAD_WIDTH, y)
                         for x, y in sidewalk_h_nw]
        sidewalk_h_se = [(x, y - 2 * ROAD_WIDTH - SIDE_WALK)
                         for x, y in sidewalk_h_ne]

        sidewalk_v_nw = [(-ROAD_WIDTH - SIDE_WALK, PLAYFIELD),
                         (-ROAD_WIDTH - SIDE_WALK, ROAD_WIDTH + SIDE_WALK * 2),
                         (-ROAD_WIDTH, ROAD_WIDTH + SIDE_WALK * 2),
                         (-ROAD_WIDTH, PLAYFIELD)]

        sidewalk_v_sw = [(x, y - PLAYFIELD - 2 * SIDE_WALK - ROAD_WIDTH)
                         for x, y in sidewalk_v_nw]
        sidewalk_v_ne = [(x + 2 * ROAD_WIDTH + SIDE_WALK, y)
                         for x, y in sidewalk_v_nw]
        sidewalk_v_se = [(x + 2 * ROAD_WIDTH + SIDE_WALK, y)
                         for x, y in sidewalk_v_sw]

        # sidewalk_c_nw = [(-ROAD_WIDTH-2*SIDE_WALK+np.cos(rad)*1*SIDE_WALK, ROAD_WIDTH+2*SIDE_WALK+np.sin(rad)*1*SIDE_WALK)
        #             for rad in np.linspace(-np.pi/2, 0, 12)]
        sidewalk_c_nw = sidewalk_v_nw[2:0:-1] + sidewalk_h_nw[3:1:-1] + [
            (-ROAD_WIDTH, ROAD_WIDTH)
        ]
        sidewalk_c_ne = sidewalk_h_ne[1::-1] + sidewalk_v_ne[2:0:-1] + [
            (ROAD_WIDTH, ROAD_WIDTH)
        ]
        sidewalk_c_sw = sidewalk_h_sw[3:1:-1] + sidewalk_v_sw[::3] + [
            (-ROAD_WIDTH, -ROAD_WIDTH)
        ]
        sidewalk_c_se = sidewalk_v_se[::3] + sidewalk_h_se[1::-1] + [
            (ROAD_WIDTH, -ROAD_WIDTH)
        ]

        self.all_sidewalks = [
            sidewalk_h_nw, sidewalk_h_ne, sidewalk_h_se, sidewalk_h_sw,
            sidewalk_v_nw, sidewalk_v_ne, sidewalk_v_se, sidewalk_v_sw,
            sidewalk_c_nw, sidewalk_c_ne, sidewalk_c_se, sidewalk_c_sw
        ]

        #Now let's see the static world:
        sidewalk = self.world.CreateStaticBody(fixtures=[
            fixtureDef(shape=polygonShape(vertices=sw), isSensor=True)
            for sw in self.all_sidewalks
        ])
        sidewalk.name = 'sidewalk'
        sidewalk.userData = sidewalk

        # remove===============================================================
        # w = self.world.CreateStaticBody(fixtures = fixtureDef(shape=polygonShape(box=(10,10, (20,20), 0))))
        # w.name = 'car'
        # w.userData = w
        return True
Пример #13
0
    def draw(self, world, init_x, init_y, force_to_center):
        ''' Circular body
        MAIN_BODY_FIXTURES = fixtureDef(
            shape=circleShape(radius=0.4),
            density=1.0,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F
        )
        '''
        MAIN_BODY_FIXTURES = [
            fixtureDef(
                shape=polygonShape(vertices=[(x * self.body_scale / self.SCALE,
                                              y * self.body_scale / self.SCALE)
                                             for x, y in polygon]),
                density=5.0,
                friction=0.1,
                categoryBits=0x20,
                maskBits=0x000F) for polygon in MAIN_BODY_POLYGONS
        ]

        LEG_FD = fixtureDef(shape=polygonShape(box=(self.LEG_W / 2,
                                                    self.LEG_H / 2)),
                            density=1.0,
                            restitution=0.0,
                            categoryBits=0x20,
                            maskBits=0x000F)

        LOWER_FD = fixtureDef(shape=polygonShape(box=(0.8 * self.LEG_W / 2,
                                                      self.LEG_H / 2)),
                              density=1.0,
                              restitution=0.0,
                              categoryBits=0x20,
                              maskBits=0x000F)

        main_body = world.CreateDynamicBody(position=(init_x, init_y),
                                            fixtures=MAIN_BODY_FIXTURES)

        basis_color1 = (0.6, 0.3, 0.5)
        basis_color2 = (0.4, 0.2, 0.3)
        main_body.color1 = tuple([c - 0.1 for c in basis_color1])
        main_body.color2 = tuple([c - 0.1 for c in basis_color2])
        leg_color1 = tuple([c + 0.1 for c in basis_color1])
        leg_color2 = tuple([c + 0.1 for c in basis_color2])

        main_body.ApplyForceToCenter((force_to_center, 0), True)

        main_body.userData = CustomBodyUserData(True,
                                                is_contact_critical=True,
                                                name="main_body")
        self.body_parts.append(main_body)
        self.reference_head_object = main_body

        for j in [[0, -1, 0], [0, 1, 0], [-1, 0, np.pi / 2], [1, 0,
                                                              np.pi / 2]]:
            x_position = j[0] * (HULL_BOTTOM_WIDTH * self.body_scale /
                                 self.SCALE / 2)
            y_position = j[1] * (HULL_BOTTOM_WIDTH * self.body_scale /
                                 self.SCALE / 2)
            # for i in [-1, +1]:
            leg_x = init_x + j[0] * (self.LEG_H / 2) + x_position
            leg_y = init_y + j[1] * (self.LEG_H / 2) + y_position
            leg = world.CreateDynamicBody(position=(leg_x, leg_y),
                                          angle=(j[2]),
                                          fixtures=LEG_FD)
            leg.color1 = leg_color1
            leg.color2 = leg_color2
            rjd = revoluteJointDef(
                bodyA=main_body,
                bodyB=leg,
                anchor=(init_x + x_position, init_y + y_position),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=self.MOTORS_TORQUE,
                motorSpeed=1,
                lowerAngle=-0.8,
                upperAngle=1.1,
            )

            leg.userData = CustomBodyUserData(False, name="leg")
            self.body_parts.append(leg)

            joint_motor = world.CreateJoint(rjd)
            joint_motor.userData = CustomMotorUserData(SPEED_HIP, False)
            self.motors.append(joint_motor)

            lower = world.CreateDynamicBody(
                position=(leg_x + j[0] * (self.LEG_H),
                          leg_y + j[1] * (self.LEG_H)),
                angle=(j[2]),
                fixtures=LOWER_FD)
            lower.color1 = leg_color1
            lower.color2 = leg_color2
            rjd = revoluteJointDef(
                bodyA=leg,
                bodyB=lower,
                anchor=(leg_x + j[0] * (self.LEG_H / 2),
                        leg_y + j[1] * (self.LEG_H / 2)),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=self.MOTORS_TORQUE,
                motorSpeed=1,
                lowerAngle=-1.6,
                upperAngle=-0.1,
            )

            lower.userData = CustomBodyUserData(True, name="lower")
            self.body_parts.append(lower)

            joint_motor = world.CreateJoint(rjd)
            joint_motor.userData = CustomMotorUserData(SPEED_KNEE,
                                                       True,
                                                       contact_body=lower,
                                                       angle_correction=1.0)
            self.motors.append(joint_motor)
Пример #14
0
    def create(self,
               world,
               TERRAIN_HEIGHT,
               module=None,
               node=None,
               connection_site=None,
               p_c=None,
               module_list=None,
               position=None):
        # get module height and width
        if p_c is not None and connection_site is None:
            raise (
                "When you want to attach a new component to a parent component, you have to supply",
                "a connection_site object with it. This connection_site object defines where to anchor",
                "the joint in between to components")
        n_radius = self.radius
        angle = 0

        pos = [7, 10, 0]
        if position is not None:
            pos = position
        if (p_c is not None):
            local_pos_x = math.cos(connection_site.orientation.x +
                                   math.pi / 2) * n_radius
            local_pos_y = math.sin(connection_site.orientation.x +
                                   math.pi / 2) * n_radius
            pos[0] = (local_pos_x) + connection_site.position.x
            pos[1] = (local_pos_y) + connection_site.position.y

        # This module will create one component that will be temporarily stored in ncomponent
        new_component = None
        # This module will create one joint (if a parent component is present) that will be temporarily stored in njoint
        njoint = None

        components = []
        joints = []

        if connection_site:
            angle += connection_site.orientation.x

        if (pos[1] - n_radius < TERRAIN_HEIGHT
            ):  #TODO CHANGE TO TERRAIN_HEIGT OR DO CHECK ELSEWHERE
            if node is not None:
                node.component = None
            return components, joints
        else:
            fixture = fixtureDef(shape=B2D.b2CircleShape(radius=n_radius),
                                 density=1,
                                 friction=0.1,
                                 restitution=0.0,
                                 categoryBits=0x0020,
                                 maskBits=0x001)
            new_component = world.CreateDynamicBody(position=(pos[0], pos[1]),
                                                    angle=angle,
                                                    fixtures=fixture)

            color = [255, 255, 255]
            if node is not None and module_list is not None:
                color = world.cmap(node.type / len(module_list))
            elif node is not None and module_list is None:
                print(
                    "Note: cannot assign a color to the module since the 'module_list' is not passed as an argument"
                )
            # move to component creator
            new_component.color1 = (color[0], color[1], color[2])
            new_component.color2 = (color[0], color[1], color[2])
            components.append(new_component)
            if node is not None:
                node.component = [new_component]

        if connection_site is not None:
            joint = mu.create_joint(world, p_c, new_component, connection_site,
                                    angle, self.torque)
            joints.append(joint)

        return components, joints
    def _create_rocket(self, initial_coordinates=(W / 2, H / 1.2)):
        body_color = (1, 1, 1)
        # ----------------------------------------------------------------------------------------
        # LANDER

        initial_x, initial_y = initial_coordinates
        self.lander = self.world.CreateDynamicBody(
            position=(initial_x, initial_y),
            angle=0,
            fixtures=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.lander.color1 = body_color
        self.lander.color2 = (0, 0, 0)

        if isinstance(self.settings['Initial Force'], str):
            self.lander.ApplyForceToCenter(
                (self.np_random.uniform(-INITIAL_RANDOM * 0.3,
                                        INITIAL_RANDOM * 0.3),
                 self.np_random.uniform(-1.3 * INITIAL_RANDOM,
                                        -INITIAL_RANDOM)), True)
        else:
            self.lander.ApplyForceToCenter(self.settings['Initial Force'],
                                           True)

        # COG is set in the middle of the polygon by default. x = 0 = middle.
        # self.lander.mass = 25
        # self.lander.localCenter = (0, 3) # COG
        # ----------------------------------------------------------------------------------------
        # LEGS
        self.legs = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(initial_x - i * LEG_AWAY / SCALE, initial_y),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(LEG_W / SCALE,
                                                            LEG_H / SCALE)),
                                    density=5.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x005))
            leg.ground_contact = False
            leg.color1 = body_color
            leg.color2 = (0, 0, 0)
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(-i * 0.3 / LANDER_CONSTANT, 0),
                localAnchorB=(i * 0.5 / LANDER_CONSTANT, LEG_DOWN),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3 * i  # low enough not to jump back into the sky
            )
            if i == -1:
                rjd.lowerAngle = 40 * DEGTORAD
                rjd.upperAngle = 45 * DEGTORAD
            else:
                rjd.lowerAngle = -45 * DEGTORAD
                rjd.upperAngle = -40 * DEGTORAD
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)
        # ----------------------------------------------------------------------------------------
        # NOZZLE
        self.nozzle = self.world.CreateDynamicBody(
            position=(initial_x, initial_y),
            angle=0.0,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in NOZZLE_POLY]),
                density=5.0,
                friction=0.1,
                categoryBits=0x0040,
                maskBits=0x003,  # collide only with ground
                restitution=0.0)  # 0.99 bouncy
        )
        self.nozzle.color1 = (0, 0, 0)
        self.nozzle.color2 = (0, 0, 0)
        rjd = revoluteJointDef(
            bodyA=self.lander,
            bodyB=self.nozzle,
            localAnchorA=(0, 0),
            localAnchorB=(0, 0.2),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=NOZZLE_TORQUE,
            motorSpeed=0,
            referenceAngle=0,
            lowerAngle=-13 *
            DEGTORAD,  # +- 15 degrees limit applied in practice
            upperAngle=13 * DEGTORAD)
        # The default behaviour of a revolute joint is to rotate without resistance.
        self.nozzle.joint = self.world.CreateJoint(rjd)
        # ----------------------------------------------------------------------------------------
        # self.drawlist = [self.nozzle] + [self.lander] + self.legs
        self.drawlist = self.legs + [self.nozzle] + [self.lander]
        self.initial_mass = self.lander.mass
        self.remaining_fuel = INITIAL_FUEL_MASS_PERCENTAGE * self.initial_mass
        return
Пример #16
0
    def __init__(self):

        EzPickle.__init__(self)

        self.seed()

        self.viewer = None


        self.iterations = 0

        self.current_state = [0]*24

        self.action_mask = []

        self.gait = 0

        self.support_knee_angle = 0.1

        self.moving_leg = None

        self.supporting_leg = None

        self.world = Box2D.b2World()

        self.terrain = None

        self.hull = None



        self.prev_shaping = None



        self.fd_polygon = fixtureDef(

                        shape = polygonShape(vertices=

                        [(0, 0),

                         (1, 0),

                         (1, -1),

                         (0, -1)]),

                        friction = FRICTION)



        self.fd_edge = fixtureDef(

                    shape = edgeShape(vertices=

                    [(0, 0),

                     (1, 1)]),

                    friction = FRICTION,

                    categoryBits=0x0001,

                )



        self.reset()



        high = np.array([np.inf] * 24)

        self.action_space = spaces.Discrete(3)

        self.observation_space = spaces.Box(-high, high, dtype=np.float32)
Пример #17
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)

            # left goal
            objs.append(
                self.world.CreateStaticBody(
                    position=(W / 2 - 250 / SCALE, H / 2),
                    angle=0.0,
                    fixtures=fixtureDef(shape=circleShape(radius=GOAL_SIZE /
                                                          SCALE,
                                                          pos=(0, 0)),
                                        categoryBits=0x0,
                                        maskBits=0x0)))
            orange = (239. / 255, 203. / 255, 138. / 255)
            objs[-1].color1 = orange
            objs[-1].color2 = orange

            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)

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

            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
Пример #18
0
    def _create_track(self):

        CHECKPOINTS = 12  # 12 = nombre de virages (11) + le départ (1)

        # Create checkpoints
        checkpoints = []
        self.obstacles_positions = []
        for c in range(CHECKPOINTS):
            noise = self.np_random.uniform(0, 2 * 3.14159 * 1 / CHECKPOINTS)
            alpha = 2 * 3.14159 * c / CHECKPOINTS + noise
            rad = self.np_random.uniform(TRACK_RAD / 3, TRACK_RAD)

            if c == 0:
                alpha = 0
                rad = 1.5 * TRACK_RAD
            if c == CHECKPOINTS - 1:
                alpha = 2 * 3.14159 * c / CHECKPOINTS
                self.start_alpha = 2 * 3.14159 * (-0.5) / CHECKPOINTS
                rad = 1.5 * TRACK_RAD

            checkpoints.append(
                (alpha, rad * math.cos(alpha), rad * math.sin(alpha)))
        self.road = []

        # Go from one checkpoint to another to create track
        x, y, beta = 1.5 * TRACK_RAD, 0, 0
        dest_i = 0
        laps = 0
        track = []
        no_freeze = 2500
        visited_other_side = False
        while True:
            alpha = math.atan2(y, x)
            if visited_other_side and alpha > 0:
                laps += 1
                visited_other_side = False
            if alpha < 0:
                visited_other_side = True
                alpha += 2 * 3.14159

            while True:  # Find destination from checkpoints
                failed = True

                while True:
                    dest_alpha, dest_x, dest_y = checkpoints[dest_i %
                                                             len(checkpoints)]
                    if alpha <= dest_alpha:
                        failed = False
                        break
                    dest_i += 1
                    if dest_i % len(checkpoints) == 0:
                        break

                if not failed:
                    break

                alpha -= 2 * 3.14159
                continue

            r1x = math.cos(beta)
            r1y = math.sin(beta)
            p1x = -r1y
            p1y = r1x
            dest_dx = dest_x - x  # vector towards destination
            dest_dy = dest_y - y
            # destination vector projected on rad:
            proj = r1x * dest_dx + r1y * dest_dy
            while beta - alpha > 1.5 * 3.14159:
                beta -= 2 * 3.14159
            while beta - alpha < -1.5 * 3.14159:
                beta += 2 * 3.14159
            prev_beta = beta
            proj *= SCALE
            if proj > 0.3:
                beta -= min(TRACK_TURN_RATE, abs(0.001 * proj))
            if proj < -0.3:
                beta += min(TRACK_TURN_RATE, abs(0.001 * proj))
            x += p1x * TRACK_DETAIL_STEP
            y += p1y * TRACK_DETAIL_STEP
            track.append((alpha, prev_beta * 0.5 + beta * 0.5, x, y))
            if laps > 4:
                break
            no_freeze -= 1
            if no_freeze == 0:
                break

        # Find closed loop range i1..i2, first loop should be ignored, second is OK
        i1, i2 = -1, -1
        i = len(track)
        while True:
            i -= 1
            if i == 0:
                return False  # Failed
            pass_through_start = track[i][0] > self.start_alpha and track[
                i - 1][0] <= self.start_alpha
            if pass_through_start and i2 == -1:
                i2 = i
            elif pass_through_start and i1 == -1:
                i1 = i
                break
        if self.verbose == 1:
            print("Track generation: %i..%i -> %i-tiles track" %
                  (i1, i2, i2 - i1))
        assert i1 != -1
        assert i2 != -1

        track = track[i1:i2 - 1]

        first_beta = track[0][1]
        first_perp_x = math.cos(first_beta)
        first_perp_y = math.sin(first_beta)
        # Length of perpendicular jump to put together head and tail
        well_glued_together = np.sqrt(
            np.square(first_perp_x * (track[0][2] - track[-1][2])) +
            np.square(first_perp_y * (track[0][3] - track[-1][3])))
        if well_glued_together > TRACK_DETAIL_STEP:
            return False

        # Red-white border on hard turns
        border = [False] * len(track)
        for i in range(len(track)):
            good = True
            oneside = 0
            for neg in range(BORDER_MIN_COUNT):
                beta1 = track[i - neg - 0][1]
                beta2 = track[i - neg - 1][1]
                good &= abs(beta1 - beta2) > TRACK_TURN_RATE * 0.2
                oneside += np.sign(beta1 - beta2)
            good &= abs(oneside) == BORDER_MIN_COUNT
            border[i] = good
        for i in range(len(track)):
            for neg in range(BORDER_MIN_COUNT):
                border[i - neg] |= border[i]

        # Create tiles and obstacles
        last_obstacle = 15  # pour que le début de course se passe sans obstacle
        for i in range(len(track)):

            alpha1, beta1, x1, y1 = track[i]
            alpha2, beta2, x2, y2 = track[i - 1]
            road1_l = (x1 - TRACK_WIDTH * math.cos(beta1),
                       y1 - TRACK_WIDTH * math.sin(beta1))
            road1_r = (x1 + TRACK_WIDTH * math.cos(beta1),
                       y1 + TRACK_WIDTH * math.sin(beta1))
            road2_l = (x2 - TRACK_WIDTH * math.cos(beta2),
                       y2 - TRACK_WIDTH * math.sin(beta2))
            road2_r = (x2 + TRACK_WIDTH * math.cos(beta2),
                       y2 + TRACK_WIDTH * math.sin(beta2))
            vertices = [road1_l, road1_r, road2_r, road2_l]

            self.fd_tile.shape.vertices = vertices
            t = self.world.CreateStaticBody(fixtures=self.fd_tile)
            t.userData = t
            c = 0.01 * (i % 3)
            t.color = [0, 0.128, 0.624, 0.019]
            t.road_visited = False
            t.road_friction = 1.0
            t.fixtures[0].sensor = True
            self.road_poly.append(([road1_l, road1_r, road2_r,
                                    road2_l], t.color))
            self.road.append(t)
            if border[i]:
                side = np.sign(beta2 - beta1)
                b1_l = (x1 + side * TRACK_WIDTH * math.cos(beta1),
                        y1 + side * TRACK_WIDTH * math.sin(beta1))
                b1_r = (x1 + side * (TRACK_WIDTH + BORDER) * math.cos(beta1),
                        y1 + side * (TRACK_WIDTH + BORDER) * math.sin(beta1))
                b2_l = (x2 + side * TRACK_WIDTH * math.cos(beta2),
                        y2 + side * TRACK_WIDTH * math.sin(beta2))
                b2_r = (x2 + side * (TRACK_WIDTH + BORDER) * math.cos(beta2),
                        y2 + side * (TRACK_WIDTH + BORDER) * math.sin(beta2))
                self.road_poly.append(([b1_l, b1_r, b2_r,
                                        b2_l], (1, 1, 1) if i % 2 == 0 else
                                       (1, 0, 0)))

            self.random_obs += 1
            self.seed(self.random_obs)
            if (self.np_random.uniform(0, 1) < OBSTACLE_PROB) and (
                    last_obstacle <=
                    0):  # i > 15 pour que la course soit toujours faisable
                last_obstacle = 8

                deriv_left = self.np_random.uniform(TRACK_WIDTH)
                deriv_right = TRACK_WIDTH - deriv_left

                obs1_l = (x1 - (TRACK_WIDTH - deriv_left) * math.cos(beta1),
                          y1 - (TRACK_WIDTH - deriv_left) * math.sin(beta1))
                obs1_r = (x1 + (TRACK_WIDTH - deriv_right) * math.cos(beta1),
                          y1 + (TRACK_WIDTH - deriv_right) * math.sin(beta1))
                obs2_l = (x2 - (TRACK_WIDTH - deriv_left) * math.cos(beta2),
                          y2 - (TRACK_WIDTH - deriv_left) * math.sin(beta2))
                obs2_r = (x2 + (TRACK_WIDTH - deriv_right) * math.cos(beta2),
                          y2 + (TRACK_WIDTH - deriv_right) * math.sin(beta2))

                self.obstacles_positions.append(
                    (obs1_l, obs1_r, obs2_r, obs2_l))
                vertices = [obs1_l, obs1_r, obs2_r, obs2_l]
                obstacle = fixtureDef(shape=polygonShape(vertices=vertices))

                obstacle.userData = obstacle
                obstacle.color = [0.1568, 0.598, 0.2862, 0]

                self.road_poly.append(([obs1_l, obs1_r, obs2_r,
                                        obs2_l], obstacle.color))
            last_obstacle -= 1

        self.track = track
        return True
Пример #19
0
    def _create_track(self):
        CHECKPOINTS = 12

        # Create checkpoints
        checkpoints = []
        for c in range(CHECKPOINTS):
            # alpha = 2*math.pi*c/CHECKPOINTS + \
            #     self.np_random.uniform(0, 2*math.pi*1/CHECKPOINTS)
            # rad = self.np_random.uniform(TRACK_RAD/3, TRACK_RAD)
            alpha = 2 * math.pi * c / CHECKPOINTS
            rad = TRACK_RAD
            if c == 0:
                alpha = 0
                rad = 1.5 * TRACK_RAD
            if c == CHECKPOINTS - 1:
                alpha = 2 * math.pi * c / CHECKPOINTS
                self.start_alpha = 2 * math.pi * (-0.5) / CHECKPOINTS
                rad = 1.5 * TRACK_RAD
            checkpoints.append(
                (alpha, rad * math.cos(alpha), rad * math.sin(alpha)))

        # print "\n".join(str(h) for h in checkpoints)
        # self.road_poly = [ (    # uncomment this to see checkpoints
        #    [ (tx,ty) for a,tx,ty in checkpoints ],
        #    (0.7,0.7,0.9) ) ]
        self.road = []

        # Go from one checkpoint to another to create track
        x, y, beta = 1.5 * TRACK_RAD, 0, 0
        dest_i = 0
        laps = 0
        track = []
        no_freeze = 2500
        visited_other_side = False
        while True:
            alpha = math.atan2(y, x)
            if visited_other_side and alpha > 0:
                laps += 1
                visited_other_side = False
            if alpha < 0:
                visited_other_side = True
                alpha += 2 * math.pi
            while True:  # Find destination from checkpoints
                failed = True
                while True:
                    dest_alpha, dest_x, dest_y = checkpoints[dest_i %
                                                             len(checkpoints)]
                    if alpha <= dest_alpha:
                        failed = False
                        break
                    dest_i += 1
                    if dest_i % len(checkpoints) == 0:
                        break
                if not failed:
                    break
                alpha -= 2 * math.pi
                continue
            r1x = math.cos(beta)
            r1y = math.sin(beta)
            p1x = -r1y
            p1y = r1x
            dest_dx = dest_x - x  # vector towards destination
            dest_dy = dest_y - y
            proj = r1x * dest_dx + r1y * dest_dy  # destination vector projected on rad
            while beta - alpha > 1.5 * math.pi:
                beta -= 2 * math.pi
            while beta - alpha < -1.5 * math.pi:
                beta += 2 * math.pi
            prev_beta = beta
            proj *= SCALE
            if proj > 0.3:
                beta -= min(TRACK_TURN_RATE, abs(0.001 * proj))
            if proj < -0.3:
                beta += min(TRACK_TURN_RATE, abs(0.001 * proj))
            x += p1x * TRACK_DETAIL_STEP
            y += p1y * TRACK_DETAIL_STEP
            track.append((alpha, prev_beta * 0.5 + beta * 0.5, x, y))
            if laps > 4:
                break
            no_freeze -= 1
            if no_freeze == 0:
                break
        # print "\n".join([str(t) for t in enumerate(track)])

        # Find closed loop range i1..i2, first loop should be ignored, second is OK
        i1, i2 = -1, -1
        i = len(track)
        while True:
            i -= 1
            if i == 0:
                return False  # Failed
            pass_through_start = track[i][0] > self.start_alpha and track[
                i - 1][0] <= self.start_alpha
            if pass_through_start and i2 == -1:
                i2 = i
            elif pass_through_start and i1 == -1:
                i1 = i
                break
        if self.verbose == 1:
            print("Track generation: %i..%i -> %i-tiles track" %
                  (i1, i2, i2 - i1))
        assert i1 != -1
        assert i2 != -1

        track = track[i1:i2 - 1]

        first_beta = track[0][1]
        first_perp_x = math.cos(first_beta)
        first_perp_y = math.sin(first_beta)
        # Length of perpendicular jump to put together head and tail
        well_glued_together = np.sqrt(
            np.square(first_perp_x * (track[0][2] - track[-1][2])) +
            np.square(first_perp_y * (track[0][3] - track[-1][3])))
        if well_glued_together > TRACK_DETAIL_STEP:
            return False

        # Red-white border on hard turns
        border = [False] * len(track)
        for i in range(len(track)):
            good = True
            oneside = 0
            for neg in range(BORDER_MIN_COUNT):
                beta1 = track[i - neg - 0][1]
                beta2 = track[i - neg - 1][1]
                good &= abs(beta1 - beta2) > TRACK_TURN_RATE * 0.2
                oneside += np.sign(beta1 - beta2)
            good &= abs(oneside) == BORDER_MIN_COUNT
            border[i] = good
        for i in range(len(track)):
            for neg in range(BORDER_MIN_COUNT):
                border[i - neg] |= border[i]

        length_of_track = len(track)
        # CHECKPOINTS
        num_checkpoints = NUM_CHECKPOINTS
        # old version
        # tiles_per_checkpoint = length_of_track // num_checkpoints
        # idx_checkpoints = [idx for idx in range(
        #     len(track)) if idx % tiles_per_checkpoint == 5]
        # remaining_idx = [idx for idx in range(
        #     len(track)) if idx not in idx_checkpoints]
        # new version
        quarter_length = length_of_track // 4
        half_length = length_of_track // 2
        assert num_checkpoints < 4
        idx_checkpoints = [
            10 + i * half_length for i in range(num_checkpoints)
        ]
        remaining_idx = [
            idx for idx in range(len(track)) if idx not in idx_checkpoints
        ]
        self.checkpoint_bodies = []
        self.checkpoints = []
        # FULLY ICY TILES
        num_fully_icy_tiles = NUM_FULLY_ICY_TILES
        # old version
        idx_fully_icy_tiles = []
        for t in range(num_fully_icy_tiles):
            idx = self.np_random.choice(remaining_idx)
            length = self.np_random.randint(ICY_TILES_MIN_LENGTH,
                                            ICY_TILES_MAX_LENGTH + 1)
            for i in range(idx, idx + length):
                if i in remaining_idx:
                    idx_fully_icy_tiles.append(i)
            remaining_idx = [
                j for j in remaining_idx if j not in idx_fully_icy_tiles
            ]
        # new version
        # start_idx = self.np_random.randint(20)
        # idx_fully_icy_tiles = [
        #     start_idx + quarter_length + i for i in range(icy_tiles_length)]
        # remaining_idx = [
        #     idx for idx in remaining_idx if idx not in idx_fully_icy_tiles]
        # PARTIALLY ICY TILES
        num_partially_icy_tiles = NUM_PARTIALLY_ICY_TILES
        idx_partially_icy_tiles = []
        eta1s = {}
        eta2s = {}
        for t in range(num_partially_icy_tiles):
            idx = self.np_random.choice(remaining_idx)
            eta1 = self.np_random.uniform(0, 1)
            eta2 = self.np_random.uniform(eta1, 1)
            length = self.np_random.randint(PARTIAL_ICY_TILES_MIN_LENGTH,
                                            PARTIAL_ICY_TILES_MAX_LENGTH + 1)
            for i in range(idx, idx + length):
                if i in remaining_idx:
                    idx_partially_icy_tiles.append(i)
                    eta1s[i] = eta1
                    eta2s[i] = eta2
                remaining_idx = [
                    j for j in remaining_idx
                    if j not in idx_partially_icy_tiles
                ]
        # Create tiles
        for i in range(len(track)):
            alpha1, beta1, x1, y1 = track[i]
            alpha2, beta2, x2, y2 = track[i - 1]

            if i in idx_checkpoints:
                # Add checkpoint
                checkpoint = self.world.CreateStaticBody(fixtures=[
                    fixtureDef(shape=polygonShape(box=(0.05, 0.05, (x1, y1),
                                                       0)))
                ])
                checkpoint.fixtures[0].sensor = True
                checkpoint.color = (0, 0, 1)
                self.checkpoint_bodies.append(checkpoint)
                betaavg = (beta1 + beta2) / 2
                self.checkpoints.append((x1, y1, betaavg))

            road1_l = np.array((x1 - TRACK_WIDTH * math.cos(beta1),
                                y1 - TRACK_WIDTH * math.sin(beta1)))
            road1_r = np.array((x1 + TRACK_WIDTH * math.cos(beta1),
                                y1 + TRACK_WIDTH * math.sin(beta1)))
            road2_l = np.array((x2 - TRACK_WIDTH * math.cos(beta2),
                                y2 - TRACK_WIDTH * math.sin(beta2)))
            road2_r = np.array((x2 + TRACK_WIDTH * math.cos(beta2),
                                y2 + TRACK_WIDTH * math.sin(beta2)))
            vertices = [
                tuple(road1_l),
                tuple(road1_r),
                tuple(road2_r),
                tuple(road2_l)
            ]
            # Create left boundary tile
            gamma1 = road1_r - road1_l
            gamma2 = road2_r - road2_l
            vertices_left_boundary = [
                tuple(road1_l - 0.4 * gamma1),
                tuple(road1_l - 0.3 * gamma1),
                tuple(road2_l - 0.3 * gamma2),
                tuple(road2_l - 0.4 * gamma2)
            ]
            self.boundary_tile.shape.vertices = vertices_left_boundary
            if not self.no_boundary:
                if i not in np.arange(284, 299) and i not in np.arange(13, 26):
                    t = self.world.CreateStaticBody(
                        fixtures=self.boundary_tile)
                    t.color = [1, 1, 1]
                    self.boundary_tiles.append(t)
            # Create right boundary tile
            vertices_right_boundary = [
                tuple(road1_r + 0.3 * gamma1),
                tuple(road1_r + 0.4 * gamma1),
                tuple(road2_r + 0.4 * gamma2),
                tuple(road2_r + 0.3 * gamma2)
            ]
            self.boundary_tile.shape.vertices = vertices_right_boundary
            if not self.no_boundary:
                t = self.world.CreateStaticBody(fixtures=self.boundary_tile)
                t.color = [1, 1, 1]
                self.boundary_tiles.append(t)
            # Create the road tile
            self.fd_tile.shape.vertices = vertices
            t = self.world.CreateStaticBody(fixtures=self.fd_tile)
            t.userData = t
            c = 0.01 * (i % 3)
            if i not in idx_fully_icy_tiles:
                # Road tile
                t.color = [
                    ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c
                ]
                t.road_friction = 1.0
                if i in idx_partially_icy_tiles:
                    eta1, eta2 = eta1s[i], eta2s[i]
                    gamma1 = road1_r - road1_l
                    gamma2 = road2_r - road2_l
                    ice_vertices = [
                        tuple(road1_l + eta1 * gamma1),
                        tuple(road1_l + eta2 * gamma1),
                        tuple(road2_l + eta2 * gamma2),
                        tuple(road2_l + eta1 * gamma2)
                    ]
                    self.fd_tile.shape.vertices = ice_vertices
                    ice_t = self.world.CreateStaticBody(fixtures=self.fd_tile)
                    ice_t.userData = ice_t
                    ice_t.color = self.ice_color
                    ice_t.road_friction = self.ice_friction
                    ice_t.road_visited = False
                    ice_t.fixtures[0].sensor = True
            else:
                # Fully Icy tile
                t.color = self.ice_color
                t.road_friction = self.ice_friction
            t.road_visited = False
            t.fixtures[0].sensor = True

            # Add discrete poly
            self.add_to_discrete_poly([road1_l, road1_r, road2_r, road2_l])

            self.road_poly.append(([road1_l, road1_r, road2_r,
                                    road2_l], t.color))
            self.road.append(t)
            if i in idx_partially_icy_tiles:
                self.road_poly.append((ice_vertices, ice_t.color))
                self.road.append(ice_t)
            if border[i]:
                side = np.sign(beta2 - beta1)
                b1_l = (x1 + side * TRACK_WIDTH * math.cos(beta1),
                        y1 + side * TRACK_WIDTH * math.sin(beta1))
                b1_r = (x1 + side * (TRACK_WIDTH + BORDER) * math.cos(beta1),
                        y1 + side * (TRACK_WIDTH + BORDER) * math.sin(beta1))
                b2_l = (x2 + side * TRACK_WIDTH * math.cos(beta2),
                        y2 + side * TRACK_WIDTH * math.sin(beta2))
                b2_r = (x2 + side * (TRACK_WIDTH + BORDER) * math.cos(beta2),
                        y2 + side * (TRACK_WIDTH + BORDER) * math.sin(beta2))
                self.road_poly.append(([b1_l, b1_r, b2_r,
                                        b2_l], (1, 1, 1) if i % 2 == 0 else
                                       (1, 0, 0)))
        self.track = track
        return True
Пример #20
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=5.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.legs = []
        self.joints = []
        # i=-1, up => joint[0], i=-1 => joint[1], i=+1 => joint[2]
        for i in [-1, +1]:  #i=1 => front leg (on the right) (green)
            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))
            if i == -1:  #     R   G   B
                leg.color1 = (1., 0., 0.)  #inside of leg
                leg.color2 = (0.8, 0., 0.)  #boundary line of leg
            else:
                leg.color1 = (0., 1., 0.)
                leg.color2 = (0., 0.8, 0.)

            #   Different limit angles for each joint   -----MODIF
            LOWER_ANGLE = 0.
            UPPER_ANGLE = 0.
            if i == (+1):
                #LOWER_ANGLE = -0.8
                #UPPER_ANGLE = 0
                LOWER_ANGLE = -0.8
                UPPER_ANGLE = 1.1
            else:
                #LOWER_ANGLE = -0.8
                #UPPER_ANGLE = 0
                LOWER_ANGLE = -0.8
                UPPER_ANGLE = 1.1

            rjd = revoluteJointDef(
                bodyA=self.hull,
                bodyB=leg,
                #localAnchorA=(0, LEG_DOWN),  #-----MODIF
                localAnchorA=(-float(i) / 4, LEG_DOWN),
                localAnchorB=(0, LEG_H / 2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed=i,
                #lowerAngle = -0.8,   -----MODIF
                #upperAngle = 1.1,
                lowerAngle=LOWER_ANGLE,
                upperAngle=UPPER_ANGLE,
            )
            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))
            if i == -1:  #      R   G   B
                lower.color1 = (1., 0., 0.)
                lower.color2 = (0.8, 0., 0.)
            else:
                lower.color1 = (0., 1., 0.)
                lower.color2 = (0., 0.8, 0.)
            #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.)

            #   Different limit angles for each joint
            LOWER_ANGLE = 0.
            UPPER_ANGLE = 0.
            if i == (+1):
                LOWER_ANGLE = -0.8
                UPPER_ANGLE = 0
                #LOWER_ANGLE = -1.6
                #UPPER_ANGLE = -0.1
            else:
                LOWER_ANGLE = -0.8
                UPPER_ANGLE = 0
                #LOWER_ANGLE = -1.6
                #UPPER_ANGLE = -0.1

            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,
                lowerAngle=LOWER_ANGLE,
                upperAngle=UPPER_ANGLE,
            )
            lower.ground_contact = False
            self.legs.append(lower)
            self.joints.append(self.world.CreateJoint(rjd))

        self.drawlist = self.terrain + self.legs + [self.hull]

        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, 0, 0, 0]))[0]
Пример #21
0
 def __init__(self, world, init_angle, init_x, init_y, draw_car=False):
     self.world = world
     self.hull = self.world.CreateDynamicBody(
         position=(init_x, init_y),
         angle=init_angle,
         fixtures=[
             fixtureDef(
                 shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                              for x, y in HULL_POLY1]),
                 density=1.0),
             fixtureDef(
                 shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                              for x, y in HULL_POLY2]),
                 density=1.0),
             fixtureDef(
                 shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                              for x, y in HULL_POLY3]),
                 density=1.0),
             fixtureDef(
                 shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                              for x, y in HULL_POLY4]),
                 density=1.0)
         ])
     self.hull.color = (0.8, 0.0, 0.0)
     self.wheels = []
     self.fuel_spent = 0.0
     WHEEL_POLY = [(-WHEEL_W, +WHEEL_R), (+WHEEL_W, +WHEEL_R),
                   (+WHEEL_W, -WHEEL_R), (-WHEEL_W, -WHEEL_R)]
     for wx, wy in WHEELPOS:
         front_k = 1.0 if wy > 0 else 1.0
         w = self.world.CreateDynamicBody(
             position=(init_x + wx * SIZE, init_y + wy * SIZE),
             angle=init_angle,
             fixtures=fixtureDef(
                 shape=polygonShape(vertices=[(x * front_k * SIZE,
                                               y * front_k * SIZE)
                                              for x, y in WHEEL_POLY]),
                 density=0.1,
                 categoryBits=0x0020,
                 maskBits=0x001,
                 restitution=0.0))
         w.wheel_rad = front_k * WHEEL_R * SIZE
         w.color = WHEEL_COLOR
         w.gas = 0.0
         w.brake = 0.0
         w.steer = 0.0
         w.phase = 0.0  # wheel angle
         w.omega = 0.0  # angular velocity
         w.skid_start = None
         w.skid_particle = None
         rjd = revoluteJointDef(
             bodyA=self.hull,
             bodyB=w,
             localAnchorA=(wx * SIZE, wy * SIZE),
             localAnchorB=(0, 0),
             enableMotor=True,
             enableLimit=True,
             maxMotorTorque=180 * 900 * SIZE * SIZE,
             motorSpeed=0,
             lowerAngle=-0.4,
             upperAngle=+0.4,
         )
         w.joint = self.world.CreateJoint(rjd)
         w.tiles = set()
         w.userData = w
         self.wheels.append(w)
     if not draw_car:
         # Only draw ugly hull when not drawing beautiful car
         self.drawlist = self.wheels + [self.hull]
     else:
         self.drawlist = self.wheels
     self.particles = []
     self.draw_car = draw_car
     # self.file_name = "square.png"
     self.file_name = "Prince_Of_Speed.png"
     self.img_path = self.get_image_path(self.file_name)
     self.sprite_geom = None
     self.car_scale_x = None
     self.car_scale_y = None
Пример #22
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()

        self.hull = self.world.CreateDynamicBody(
            position=(hull_x, hull_y),
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in HULL_POLY]),
                density=5.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.hull.ApplyForceToCenter((0, 10*10.0*5.0*(20/SCALE)**2), False)

        self.legs = []
        self.joints = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(leg_x, leg_y),
                angle=gamma_i,
                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, 0),
                localAnchorB=(0, LEG_H / 2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed=0.0,
                referenceAngle=0.0,
                lowerAngle=-1.4,  # -80 degree
                upperAngle=1.4,  # 80 degree
            )

            self.legs.append(leg)
            self.joints.append(self.world.CreateJoint(rjd))

            lower = self.world.CreateDynamicBody(
                position=(lower_x, lower_y),
                angle=(-math.pi / 2 + a_i),
                fixtures=fixtureDef(shape=polygonShape(box=(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=0.0,
                referenceAngle=-1 * math.pi,
                lowerAngle=0.35,  # 20 degree
                upperAngle=3.14,  # 180 degree
            )
            lower.ground_contact = False
            self.legs.append(lower)
            self.joints.append(self.world.CreateJoint(rjd))

        self.drawlist = self.terrain + self.legs + [self.hull]

        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.hull.ApplyForceToCenter((0, 10.0 * (5.0 * (20 / SCALE) ** 2)), True)
        #self.legs[0].ApplyForceToCenter((0, 10.0 * 1.0 * LEG_H * LEG_W), True)
        #self.legs[1].ApplyForceToCenter((0, 10.0 * 1.0 * LEG_H * LEG_W), True)
        #self.legs[2].ApplyForceToCenter((0, 10.0 * 1.0 * LEG_H * LEG_W), True)
        #self.legs[3].ApplyForceToCenter((0, 10.0 * 1.0 * LEG_H * LEG_W), True)

        return self._step(np.array([0.0, 0.0, 0.0, 0.0]))[0]
Пример #23
0
 def __init__(self,
              world,
              init_angle,
              init_x,
              init_y,
              color=(0.8, 0.0, 0.0)):
     self.world = world
     self.hull = self.world.CreateDynamicBody(
         position=(init_x, init_y),
         angle=init_angle,
         fixtures=[
             # fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY1 ]), density=1.0),
             # fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY2 ]), density=1.0),
             # fixtureDef(shape = polygonShape(vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY3 ]), density=1.0),
             fixtureDef(
                 shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                              for x, y in HULL_POLY4]),
                 density=1.0)
         ])
     self.hull.color = color
     self.wheels = []
     self.fuel_spent = 0.0
     WHEEL_POLY = [(-WHEEL_W, +WHEEL_R), (+WHEEL_W, +WHEEL_R),
                   (+WHEEL_W, -WHEEL_R), (-WHEEL_W, -WHEEL_R)]
     for wx, wy in WHEELPOS:
         front_k = 1.0 if wy > 0 else 1.0
         w = self.world.CreateDynamicBody(
             position=(init_x + wx * SIZE, init_y + wy * SIZE),
             angle=init_angle,
             fixtures=fixtureDef(
                 shape=polygonShape(vertices=[(x * front_k * SIZE,
                                               y * front_k * SIZE)
                                              for x, y in WHEEL_POLY]),
                 density=0.1,
                 categoryBits=0x0020,
                 maskBits=0x001,
                 restitution=0.0))
         w.wheel_rad = front_k * WHEEL_R * SIZE
         w.color = WHEEL_COLOR
         w.gas = 0.0
         w.brake = 0.0
         w.steer = 0.0
         w.phase = 0.0  # wheel angle
         w.omega = 0.0  # angular velocity
         w.skid_start = None
         w.skid_particle = None
         rjd = revoluteJointDef(
             bodyA=self.hull,
             bodyB=w,
             localAnchorA=(wx * SIZE, wy * SIZE),
             localAnchorB=(0, 0),
             enableMotor=True,
             enableLimit=True,
             maxMotorTorque=180 * 900 * SIZE * SIZE,
             motorSpeed=0,
             lowerAngle=-0.4,
             upperAngle=+0.4,
         )
         w.joint = self.world.CreateJoint(rjd)
         w.tiles = set()
         w.userData = w
         self.wheels.append(w)
     self.drawlist = self.wheels + [self.hull]
     self.particles = []
Пример #24
0
    def reset(self):
        self.obj_type = 5
        self.timer = 0
        self.trigger = 'stop'
        self.curr_grab = 1000
        self.curr_right = 0
        self.consecutive_wait = 0
        self.dist_from_obj = 0
        self.dist_from_pos = 0
        self.colour_list = []
        self.obj_type = 5
        self.lift_reward = [0.1] * 10
        self.max_height = 200
        for i_body in range(len(self.body_list)):
            if i_body != 0:
                self.world.DestroyBody(self.body_list[i_body])
        self.body_list = []
        self.ground_body = self.world.CreateStaticBody(
            position=(160, 0), shapes=polygonShape(box=(160, 7.5)), angle=0)
        self.wall_body1 = self.world.CreateStaticBody(
            position=(320, 80), shapes=polygonShape(box=(7.5, 320)), angle=0)
        self.wall_body2 = self.world.CreateStaticBody(
            position=(0, 80), shapes=polygonShape(box=(7.5, 320)), angle=0)
        self.wall_body3 = self.world.CreateStaticBody(
            position=(100000, 0), shapes=polygonShape(box=(5, 70)), angle=0)
        self.roof = self.world.CreateStaticBody(position=(160, 320),
                                                shapes=polygonShape(box=(160,
                                                                         7.5)),
                                                angle=0)
        pos1 = np.random.uniform(15, 130)
        pos2 = np.random.uniform(280, 310)
        self.arm = self.world.CreateDynamicBody(position=(pos1, 315),
                                                shapes=polygonShape(box=(6,
                                                                         12)),
                                                angle=0)
        self.grab = self.world.CreateDynamicBody(
            position=(pos1, pos2),
            shapes=polygonShape(box=(6, 6)),
            angle=0,
            fixedRotation=True,
        )
        self.grab.CreatePolygonFixture(box=(6, 6), density=0.1, friction=0)
        self.stick = self.world.CreateDynamicBody(
            position=(pos1, pos2),
            shapes=polygonShape(box=(40, 6)),
            angle=0,
        )
        self.stick.CreatePolygonFixture(box=(40, 3), density=0.1, friction=0)
        offset = 2.5
        DENSITY_2 = 0.1
        FRICTION = 10
        if self.obj_type == 5:
            OBJ_2 = [(-40, 30), (-10, 30), (-10, 20), (-40, 20)]
            OBJ_3 = [(-40, -20), (-10, -20), (-10, -30), (-40, -30)]
        else:
            OBJ_2 = [(-40, 30), (-10, 30), (-10, 10), (-40, 10)]
            OBJ_3 = [(-40, -10), (-10, -10), (-10, -30), (-40, -30)]
        OBJ_1 = [(-10, 30), (10, 30), (10, -30), (-10, -30)]
        OBJ_4 = [(10, 10), (40, 10), (40, -10), (10, -10)]
        OBJ_5 = [(-40, -5), (-10, -5), (-10, 5), (-40, 5)]
        definedFixturesObj_1 = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in OBJ_1]),
            density=DENSITY_2,
            friction=FRICTION,
            restitution=0.0)

        definedFixturesObj_2 = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in OBJ_2]),
            density=DENSITY_2,
            friction=FRICTION,
            restitution=0.0)

        definedFixturesObj_3 = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in OBJ_3]),
            density=DENSITY_2,
            friction=FRICTION,
            restitution=0.0)

        definedFixturesObj_4 = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in OBJ_4]),
            density=DENSITY_2,
            friction=FRICTION,
            restitution=0.0)
        definedFixturesObj_5 = fixtureDef(
            shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                         for x, y in OBJ_5]),
            density=DENSITY_2,
            friction=FRICTION,
            restitution=0.0)
        if self.obj_type == 1:
            fixturesListObj = [
                definedFixturesObj_1, definedFixturesObj_2,
                definedFixturesObj_3, definedFixturesObj_4
            ]
        elif self.obj_type == 2:
            fixturesListObj = [
                definedFixturesObj_1, definedFixturesObj_3,
                definedFixturesObj_4
            ]
        elif self.obj_type == 3:
            fixturesListObj = [
                definedFixturesObj_1, definedFixturesObj_2,
                definedFixturesObj_4
            ]
        elif self.obj_type == 4:
            fixturesListObj = [
                definedFixturesObj_1, definedFixturesObj_2,
                definedFixturesObj_3
            ]
        elif self.obj_type == 5:
            fixturesListObj = [
                definedFixturesObj_1, definedFixturesObj_2,
                definedFixturesObj_3, definedFixturesObj_5
            ]

        self.object = self.world.CreateDynamicBody(position=(random.randint(
            140, 280), 40),
                                                   angle=0,
                                                   angularDamping=10,
                                                   linearDamping=1,
                                                   fixtures=fixturesListObj)

        self.object.mass = 1000

        self.prev_grab_pos = self.grab.position.copy()

        self.h_pj = self.world.CreatePrismaticJoint(
            bodyA=self.wall_body2,
            bodyB=self.arm,
            anchor=(self.wall_body2.worldCenter[0],
                    self.wall_body2.worldCenter[1]),
            axis=(1, 0),
            lowerTranslation=-100000,
            upperTranslation=1000000,
            enableLimit=True,
            motorSpeed=0,
            maxMotorForce=5000000000000000000000,
            enableMotor=True,
        )
        self.v_pj = self.world.CreatePrismaticJoint(
            bodyA=self.arm,
            bodyB=self.grab,
            anchor=(self.grab.worldCenter[0], self.grab.worldCenter[1]),
            axis=(0, 1),
            lowerTranslation=-100000,
            upperTranslation=0,
            enableLimit=True,
            motorSpeed=0,
            maxMotorForce=5000000000000000000000,
            enableMotor=True,
        )
        self.a_rj = self.world.CreateRevoluteJoint(
            bodyA=self.grab,
            bodyB=self.stick,
            anchor=self.stick.worldCenter,
            maxMotorTorque=100000000,
            motorSpeed=0,
            enableMotor=True,
            collideConnected=False,
        )
        self.colour_list.append((255, 255, 255, 255))
        self.colour_list.append((255, 255, 255, 255))
        self.colour_list.append((255, 255, 255, 255))
        self.colour_list.append((255, 255, 255, 255))
        self.colour_list.append((255, 255, 255, 255))
        self.colour_list.append((150, 200, 150, 200))
        self.colour_list.append((200, 150, 200, 150))
        self.colour_list.append((200, 150, 200, 150))
        self.body_list = [
            self.ground_body, self.wall_body1, self.wall_body2, self.roof,
            self.arm, self.grab, self.object, self.stick
        ]

        self.reward_list = [1] * len(self.body_list)

        self.update_screen()
        self.state1 = get_game_screen(screen)
        return self.state1
Пример #25
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._generate_clouds()

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

        self.details = []
        detailsJoints = []

        for color1, color2, shapes in BODY_DETAILS:
            detail = self.world.CreateDynamicBody(
                position = (init_x,init_y),
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in shapes[0] ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                )
            )

            for shape in shapes:
                another = detail.CreateFixture(fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in shape ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                ))

            detail.color1 = color1
            detail.color2 = color2
            self.details.append(detail)

            joint = weldJointDef(
                bodyA=detail,
                bodyB=self.body,
                localAnchorA=(0,0),
                localAnchorB=(0,0),
            )
            detailsJoints.append(self.world.CreateJoint(joint))


        self.legs = []
        self.joints = []
        for i in [-1,+1]:
            leg_upper = self.world.CreateDynamicBody(
                position = (init_x, init_y - LEG_H/2 - LEG_DOWN),
                angle = (i*0.05),
                fixtures = fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in LEG_UPPER_SHAPE ]),
                    density=0.5,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001)
                )
            leg_upper.color1 = (0.9,0.9,0.9)
            leg_upper.color2 = (0.9,0.9,0.9)
            rjd = revoluteJointDef(
                bodyA=self.body,
                bodyB=leg_upper,
                localAnchorA=(0, LEG_DOWN),
                localAnchorB=(0, LEG_H/2),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed = 2*i,
                lowerAngle = -0.8,
                upperAngle = 1.1,
                )
            self.joints.append(self.world.CreateJoint(rjd))

            leg_lower = self.world.CreateDynamicBody(
                position = (init_x, init_y - LEG_H*3/2 - LEG_DOWN),
                angle = (i*0.05),
                fixtures = fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in LEG_LOWER_SHAPE ]),
                    density=0.5,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001)
                )
            leg_lower.color1 = (0.9,0.9,0.9)
            leg_lower.color2 = (0.9,0.9,0.9)
            rjd = revoluteJointDef(
                bodyA=leg_upper,
                bodyB=leg_lower,
                localAnchorA=(0, -LEG_H/3),
                localAnchorB=(0, LEG_H/3),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=MOTORS_TORQUE,
                motorSpeed = 1,
                lowerAngle = -1.6,
                upperAngle = -0.1,
                )
            leg_lower.ground_contact = False
            self.joints.append(self.world.CreateJoint(rjd))

            detail_upper = self.world.CreateDynamicBody(
                position = (init_x, init_y - LEG_H/2 - LEG_DOWN),
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in LEG_UPPER_DETAILS[0] ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                )
            )

            for shape in LEG_UPPER_DETAILS[1:]:
                another = detail_upper.CreateFixture(fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in shape ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                ))

            detail_upper.color1 = (0,0,0)
            detail_upper.color2 = (0,0,0)

            joint = weldJointDef(
                bodyA=detail_upper,
                bodyB=leg_upper,
                localAnchorA=(0,0),
                localAnchorB=(0,0),
            )
            detailsJoints.append(self.world.CreateJoint(joint))

            detail_lower = self.world.CreateDynamicBody(
                position = (init_x, init_y - LEG_H/2 - LEG_DOWN),
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in LEG_LOWER_DETAILS[0] ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                )
            )

            for shape in LEG_LOWER_DETAILS[1:]:
                another = detail_lower.CreateFixture(fixtureDef(
                    shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in shape ]),
                    density=0.0001,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0
                ))

            detail_lower.color1 = (0,0,0)
            detail_lower.color2 = (0,0,0)

            joint = weldJointDef(
                bodyA=detail_lower,
                bodyB=leg_lower,
                localAnchorA=(0,0),
                localAnchorB=(0,0),
            )
            detailsJoints.append(self.world.CreateJoint(joint))


            self.details.append(detail_lower)
            self.details.append(detail_upper)
            self.legs.append(leg_upper)
            self.legs.append(leg_lower)


        self.joints.extend(detailsJoints)

        self.drawlist = self.terrain + self.legs[::-1] + [self.body] + self.details

        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,0,0,0]))[0]
Пример #26
0
    def 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

        self.create_terrain()

        initial_y = VIEWPORT_H / SCALE
        self.lander = self.world.CreateDynamicBody(
            position=(VIEWPORT_W / SCALE / 2, initial_y),
            angle=0.0,
            fixtures=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.lander.color1 = (0.5, 0.4, 0.9)
        self.lander.color2 = (0.3, 0.3, 0.5)
        self.lander.ApplyForceToCenter(
            (self.initial_center_x, self.initial_center_y), True)

        self.legs = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(VIEWPORT_W / SCALE / 2 - i * LEG_AWAY / SCALE,
                          initial_y),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(LEG_W / SCALE,
                                                            LEG_H / SCALE)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x001))
            leg.ground_contact = False
            leg.color1 = (0.5, 0.4, 0.9)
            leg.color2 = (0.3, 0.3, 0.5)
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i * LEG_AWAY / SCALE, LEG_DOWN / SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3 * i  # low enough not to jump back into the sky
            )
            if i == -1:
                rjd.lowerAngle = +0.9 - 0.5  # The most esoteric numbers here, angled legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)

        self.drawlist = [self.lander] + self.legs

        return self.step(np.array([0, 0]) if self.continuous else 0)[0]
Пример #27
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)
Пример #28
0
	def create(self,world,TERRAIN_HEIGHT,module=None,node=None,connection_site=None, p_c=None, module_list = None,position = None):
		if p_c is not None and connection_site is None:
			raise("When you want to attach a new component to a parent component, you have to supply",
			"a connection_site object with it. This connection_site object defines where to anchor",
			"the joint in between to components")

		n_height = 0.5
		n_width = 0.5
		angle = 0
		#if p_c is not None:
		#	parent_angle = p_c.angle
		if node is not None:
			if node.module_ is not None:
				n_height = node.module_.height
				n_width = node.module_.width
				#angle = node.module_.get_angle(con = node.parent_connection_coordinates)
			else:
				n_height = module_list[node.type].height
				n_width = module_list[node.type].width
				#angle = module_list[node.type].get_angle(con = node.parent_connection_coordinates)
		elif module is not None:
			n_height = module.height
			n_width = module.width
			angle = module.get_angle(0)
		
		pos = [7,7,0]
		if position is not None:
			pos = position
		if (p_c is not None):
			# The local position should be based on how much the module is rotated from the connection site. 
			# - math.pi to compensate for y directionality of the angle (TODO: should be removed)
			local_pos_x =math.cos(connection_site.orientation.x + angle + math.pi/2) * n_height/2
			local_pos_y =math.sin(connection_site.orientation.x + angle + math.pi/2) * n_height/2
			pos[0] = (local_pos_x) + connection_site.position.x
			pos[1] = (local_pos_y) + connection_site.position.y
		components = []
		joints = []
		# below is a quick hack formula. Should check based on lowest point in space. 
		if (pos[1] - math.sqrt(math.pow(n_width,2) + math.pow(n_height,2)) < TERRAIN_HEIGHT): # TODO CHANGE 5 TO TERRAIN_HEIGHT
			if node is not None:
				node.component = None
			return components,joints
		# if connection_site is not None:
		# We remove -math.pi/2 since we want the y vector to face in the correct direction
		#	angle = connection_site.orientation.x -math.pi/2
		# This module will create one component that will be temporarily stored in ncomponent
		new_component = None
		# This module will create one joint (if a parent component is present) that will be temporarily stored in njoint
		njoint = None

				
		# get parent node
		par = None	

		if connection_site:
			angle += connection_site.orientation.x
				
		fixture = fixtureDef(
				shape=polygonShape(box=(n_width/2, n_height/2)),
				density=1.0,
				friction=0.1,
				restitution=0.0,
				categoryBits=0x0020,
				maskBits=0x001
			)

		new_component = world.CreateDynamicBody(
			position=(pos[0],pos[1]),
			angle = angle ,
			fixtures = fixture)
		color = (125,125,125)
		if node is not None:
			color = world.cmap(node.type/len(module_list))
		#new_component.color1 = (int(color[0]*255),int(color[1]*255),int(color[2]*255))
		#new_component.color2 = (int(color[0]*255),int(color[1]*255),int(color[2]*255))
		new_component.color1 = (color[0],color[1],color[2])
		new_component.color2 = (color[0],color[1],color[2])
		#components.append(new_component)
		components.append(new_component)
		if node is not None:
			node.component = [new_component]
		if connection_site is not None:
			joint = self.create_joint(world, p_c,new_component,connection_site)
			joints.append(joint)

		return components,joints
Пример #29
0
LEG_W, LEG_H = 8/SCALE, 34/SCALE

VIEWPORT_W = 600
VIEWPORT_H = 400

TERRAIN_STEP   = 14/SCALE
TERRAIN_LENGTH = 200     # in steps
TERRAIN_HEIGHT = VIEWPORT_H/SCALE/4
TERRAIN_GRASS    = 10    # low long are grass spots, in steps
TERRAIN_STARTPAD = 20    # in steps
FRICTION = 2.5

HULL_FD = fixtureDef(
                shape=polygonShape(vertices=[ (x/SCALE,y/SCALE) for x,y in HULL_POLY ]),
                density=5.0,
                friction=0.1,
                categoryBits=0x0020,
                maskBits=0x001,  # collide only with ground
                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=0x0020,
                    maskBits=0x001)

LOWER_FD = fixtureDef(
                    shape=polygonShape(box=(0.8*LEG_W/2, LEG_H/2)),
                    density=1.0,
                    restitution=0.0,
Пример #30
0
    def _reset(self):
        self._destroy()
        self.game_over = False
        self.prev_shaping = None

        W = VIEWPORT_W/SCALE
        H = VIEWPORT_H/SCALE

        # terrain
        CHUNKS = 11
        height = np.random.uniform(0, H/2, size=(CHUNKS+1,) )
        chunk_x  = [W/(CHUNKS-1)*i for i in xrange(CHUNKS)]
        self.helipad_x1 = chunk_x[CHUNKS//2-1]
        self.helipad_x2 = chunk_x[CHUNKS//2+1]
        self.helipad_y  = H/4
        height[CHUNKS//2-2] = self.helipad_y
        height[CHUNKS//2-1] = self.helipad_y
        height[CHUNKS//2+0] = self.helipad_y
        height[CHUNKS//2+1] = self.helipad_y
        height[CHUNKS//2+2] = self.helipad_y
        smooth_y = [0.33*(height[i-1] + height[i+0] + height[i+1]) for i in xrange(CHUNKS)]

        self.moon = self.world.CreateStaticBody( shapes=edgeShape(vertices=[(0, 0), (W, 0)]) )
        self.sky_polys = []
        for i in xrange(CHUNKS-1):
            p1 = (chunk_x[i],   smooth_y[i])
            p2 = (chunk_x[i+1], smooth_y[i+1])
            self.moon.CreateEdgeFixture(
                vertices=[p1,p2],
                density=0,
                friction=0.1)
            self.sky_polys.append( [p1, p2, (p2[0],H), (p1[0],H)] )

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

        initial_y = VIEWPORT_H/SCALE
        self.lander = self.world.CreateDynamicBody(
            position = (VIEWPORT_W/SCALE/2, initial_y),
            angle=0.0,
            fixtures = 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.lander.color1 = (0.5,0.4,0.9)
        self.lander.color2 = (0.3,0.3,0.5)
        self.lander.ApplyForceToCenter( (
            np.random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
            np.random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM)
            ), True)

        self.legs = []
        for i in [-1,+1]:
            leg = self.world.CreateDynamicBody(
                position = (VIEWPORT_W/SCALE/2 - i*LEG_AWAY/SCALE, initial_y),
                angle = (i*0.05),
                fixtures = fixtureDef(
                    shape=polygonShape(box=(LEG_W/SCALE, LEG_H/SCALE)),
                    density=1.0,
                    restitution=0.0,
                    categoryBits=0x0020,
                    maskBits=0x001)
                )
            leg.color1 = (0.5,0.4,0.9)
            leg.color2 = (0.3,0.3,0.5)
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i*LEG_AWAY/SCALE, LEG_DOWN/SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3*i  # low enough not to jump back into the sky
                )
            if i==-1:
                rjd.lowerAngle = +0.9 - 0.5  # Yes, the most esoteric numbers here, angles legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)

        self.drawlist = [self.lander] + self.legs

        return self._step(0)[0]
Пример #31
0
    def _reset(self):
        self._destroy()

        init_x = self.init_x
        init_y = self.init_y
        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=5.0,
                friction=0.1,
                categoryBits=0x002,
                # maskBits=(0x001 & 0x002),  # 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.legs = []
        self.joints = []
        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=0x002,
                                    maskBits=0x001)  # collide with ground only
            )
            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))

        self.drawlist = self.legs + [self.hull]

        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 fraction

        self.lidar = [LidarCallback() for _ in range(10)]
Пример #32
0
    def _reset(self):
        self._destroy()
        self.world.contactListener = ContactDetector(self)
        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=5.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((np.random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True)

        self.legs = []
        self.joints = []
        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))

        self.drawlist = self.terrain + self.legs + [self.hull]

        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,0,0,0]))[0]
Пример #33
0
    def _create_track(self):
        CHECKPOINTS = 12

        # Create checkpoints
        checkpoints = []
        for c in range(CHECKPOINTS):
            alpha = 2*math.pi*c/CHECKPOINTS + self.np_random.uniform(0, 2*math.pi*1/CHECKPOINTS)
            rad = self.np_random.uniform(TRACK_RAD/3, TRACK_RAD)
            if c==0:
                alpha = 0
                rad = 1.5*TRACK_RAD
            if c==CHECKPOINTS-1:
                alpha = 2*math.pi*c/CHECKPOINTS
                self.start_alpha = 2*math.pi*(-0.5)/CHECKPOINTS
                rad = 1.5*TRACK_RAD
            checkpoints.append( (alpha, rad*math.cos(alpha), rad*math.sin(alpha)) )

        #print "\n".join(str(h) for h in checkpoints)
        #self.road_poly = [ (    # uncomment this to see checkpoints
        #    [ (tx,ty) for a,tx,ty in checkpoints ],
        #    (0.7,0.7,0.9) ) ]
        self.road = []

        # Go from one checkpoint to another to create track
        x, y, beta = 1.5*TRACK_RAD, 0, 0
        dest_i = 0
        laps = 0
        track = []
        no_freeze = 2500
        visited_other_side = False
        while 1:
            alpha = math.atan2(y, x)
            if visited_other_side and alpha > 0:
                laps += 1
                visited_other_side = False
            if alpha < 0:
                visited_other_side = True
                alpha += 2*math.pi
            while True: # Find destination from checkpoints
                failed = True
                while True:
                    dest_alpha, dest_x, dest_y = checkpoints[dest_i % len(checkpoints)]
                    if alpha <= dest_alpha:
                        failed = False
                        break
                    dest_i += 1
                    if dest_i % len(checkpoints) == 0: break
                if not failed: break
                alpha -= 2*math.pi
                continue
            r1x = math.cos(beta)
            r1y = math.sin(beta)
            p1x = -r1y
            p1y = r1x
            dest_dx = dest_x - x  # vector towards destination
            dest_dy = dest_y - y
            proj = r1x*dest_dx + r1y*dest_dy  # destination vector projected on rad
            while beta - alpha >  1.5*math.pi: beta -= 2*math.pi
            while beta - alpha < -1.5*math.pi: beta += 2*math.pi
            prev_beta = beta
            proj *= SCALE
            if proj >  0.3: beta -= min(TRACK_TURN_RATE, abs(0.001*proj))
            if proj < -0.3: beta += min(TRACK_TURN_RATE, abs(0.001*proj))
            x += p1x*TRACK_DETAIL_STEP
            y += p1y*TRACK_DETAIL_STEP
            track.append( (alpha,prev_beta*0.5 + beta*0.5,x,y) )
            if laps > 4: break
            no_freeze -= 1
            if no_freeze==0: break
        #print "\n".join([str(t) for t in enumerate(track)])

        # Find closed loop range i1..i2, first loop should be ignored, second is OK
        i1, i2 = -1, -1
        i = len(track)
        while True:
            i -= 1
            if i==0: return False  # Failed
            pass_through_start = track[i][0] > self.start_alpha and track[i-1][0] <= self.start_alpha
            if pass_through_start and i2==-1:
                i2 = i
            elif pass_through_start and i1==-1:
                i1 = i
                break
        print("Track generation: %i..%i -> %i-tiles track" % (i1, i2, i2-i1))
        assert i1!=-1
        assert i2!=-1

        track = track[i1:i2-1]

        first_beta = track[0][1]
        first_perp_x = math.cos(first_beta)
        first_perp_y = math.sin(first_beta)
        # Length of perpendicular jump to put together head and tail
        well_glued_together = np.sqrt(
            np.square( first_perp_x*(track[0][2] - track[-1][2]) ) +
            np.square( first_perp_y*(track[0][3] - track[-1][3]) ))
        if well_glued_together > TRACK_DETAIL_STEP:
            return False

        # Red-white border on hard turns
        border = [False]*len(track)
        for i in range(len(track)):
            good = True
            oneside = 0
            for neg in range(BORDER_MIN_COUNT):
                beta1 = track[i-neg-0][1]
                beta2 = track[i-neg-1][1]
                good &= abs(beta1 - beta2) > TRACK_TURN_RATE*0.2
                oneside += np.sign(beta1 - beta2)
            good &= abs(oneside) == BORDER_MIN_COUNT
            border[i] = good
        for i in range(len(track)):
            for neg in range(BORDER_MIN_COUNT):
                border[i-neg] |= border[i]

        # Create tiles
        for i in range(len(track)):
            alpha1, beta1, x1, y1 = track[i]
            alpha2, beta2, x2, y2 = track[i-1]
            road1_l = (x1 - TRACK_WIDTH*math.cos(beta1), y1 - TRACK_WIDTH*math.sin(beta1))
            road1_r = (x1 + TRACK_WIDTH*math.cos(beta1), y1 + TRACK_WIDTH*math.sin(beta1))
            road2_l = (x2 - TRACK_WIDTH*math.cos(beta2), y2 - TRACK_WIDTH*math.sin(beta2))
            road2_r = (x2 + TRACK_WIDTH*math.cos(beta2), y2 + TRACK_WIDTH*math.sin(beta2))
            t = self.world.CreateStaticBody( fixtures = fixtureDef(
                shape=polygonShape(vertices=[road1_l, road1_r, road2_r, road2_l])
                ))
            t.userData = t
            c = 0.01*(i%3)
            t.color = [ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c]
            t.road_visited = False
            t.road_friction = 1.0
            t.fixtures[0].sensor = True
            self.road_poly.append(( [road1_l, road1_r, road2_r, road2_l], t.color ))
            self.road.append(t)
            if border[i]:
                side = np.sign(beta2 - beta1)
                b1_l = (x1 + side* TRACK_WIDTH        *math.cos(beta1), y1 + side* TRACK_WIDTH        *math.sin(beta1))
                b1_r = (x1 + side*(TRACK_WIDTH+BORDER)*math.cos(beta1), y1 + side*(TRACK_WIDTH+BORDER)*math.sin(beta1))
                b2_l = (x2 + side* TRACK_WIDTH        *math.cos(beta2), y2 + side* TRACK_WIDTH        *math.sin(beta2))
                b2_r = (x2 + side*(TRACK_WIDTH+BORDER)*math.cos(beta2), y2 + side*(TRACK_WIDTH+BORDER)*math.sin(beta2))
                self.road_poly.append(( [b1_l, b1_r, b2_r, b2_l], (1,1,1) if i%2==0 else (1,0,0) ))
        self.track = track
        return True
    def _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

        # create the sea surface into which the flacon might draw (with no collision)
        f = fixtureDef(shape=polygonShape(box=(W, SEA_LEVEL), radius=0.0),
                       density=0.5,
                       friction=0.03)

        self.sea_surface = self.world.CreateStaticBody(position=(0, SEA_LEVEL),
                                                       angle=0,
                                                       fixtures=f)

        # Create the floating drone ship
        f = fixtureDef(shape=polygonShape(box=(DRONE_SHIP_W, DRONE_SHIP_H),
                                          radius=0.0),
                       density=0.4,
                       friction=0.05,
                       categoryBits=0x0020,
                       maskBits=0x001)  #, userData=self.logo_img)

        self.floating_drone_ship = self.world.CreateDynamicBody(
            position=(DRONE_SHIP_W / SCALE, SEA_LEVEL),
            angle=0,
            linearDamping=0.7,
            angularDamping=0.3,
            fixtures=f)

        self.floating_drone_ship.color1 = (0.1, 0.1, 0.1)
        self.floating_drone_ship.color2 = (0, 0, 0)

        self.sea_surface.color1 = (0.5, 0.4, 0.9)
        self.sea_surface.color2 = (0.3, 0.3, 0.5)

        initial_y = VIEWPORT_H / SCALE
        #  create the falcon lander
        self.falcon_rocket = self.world.CreateDynamicBody(
            position=(VIEWPORT_W / SCALE / 2, initial_y),
            angle=0.0,
            fixtures=fixtureDef(
                shape=polygonShape(vertices=[(x / SCALE, y / SCALE)
                                             for x, y in FALCON_POLY]),
                density=5.0,  # 5.0
                friction=0.1,
                categoryBits=0x001,
                maskBits=0x0020,  # collide only with floating_drone_ship
                restitution=0.0)  #, userData=self.logo_img) # 0.99 bouncy
        )
        self.falcon_rocket.color1 = (1.0, 1.0, 1.0)
        self.falcon_rocket.color2 = (0, 0, 0)

        self.falcon_rocket.ApplyForceToCenter(
            (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
             self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM)), True)

        # create the legs of the falcon rocket
        self.legs = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(VIEWPORT_W / SCALE / 2 - i * LEG_AWAY / SCALE,
                          initial_y),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(LEG_W / SCALE,
                                                            LEG_H / SCALE)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x001,
                                    maskBits=0x0020))
            leg.ground_contact = False
            leg.color1 = (0, 0, 0)
            leg.color2 = (0, 0, 0)
            rjd = revoluteJointDef(
                bodyA=self.falcon_rocket,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i * LEG_AWAY / SCALE, LEG_DOWN / SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3 * i  # low enough not to jump back into the sky
            )
            if i == -1:
                rjd.lowerAngle = +0.9 - 0.5  # Yes, the most esoteric numbers here, angles legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)

        self.drawlist = [self.falcon_rocket] + self.legs + [
            self.floating_drone_ship
        ] + [self.sea_surface]

        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.game_over = False
        self.prev_shaping = None

        W = VIEWPORT_W / SCALE
        H = VIEWPORT_H / SCALE

        # terrain
        CHUNKS = 11
        height = self.np_random.uniform(0, H / 2, size=(CHUNKS + 1, ))
        chunk_x = [W / (CHUNKS - 1) * i for i in range(CHUNKS)]
        self.helipad_x1 = chunk_x[CHUNKS // 2 - 1]
        self.helipad_x2 = chunk_x[CHUNKS // 2 + 1]
        self.helipad_y = H / 4
        height[CHUNKS // 2 - 2] = self.helipad_y
        height[CHUNKS // 2 - 1] = self.helipad_y
        height[CHUNKS // 2 + 0] = self.helipad_y
        height[CHUNKS // 2 + 1] = self.helipad_y
        height[CHUNKS // 2 + 2] = self.helipad_y
        smooth_y = [
            0.33 * (height[i - 1] + height[i + 0] + height[i + 1])
            for i in range(CHUNKS)
        ]

        self.moon = self.world.CreateStaticBody(shapes=edgeShape(
            vertices=[(0, 0), (W, 0)]))
        self.sky_polys = []
        for i in range(CHUNKS - 1):
            p1 = (chunk_x[i], smooth_y[i])
            p2 = (chunk_x[i + 1], smooth_y[i + 1])
            self.moon.CreateEdgeFixture(vertices=[p1, p2],
                                        density=0,
                                        friction=0.1)
            self.sky_polys.append([p1, p2, (p2[0], H), (p1[0], H)])

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

        initial_y = VIEWPORT_H / SCALE
        self.lander = self.world.CreateDynamicBody(
            position=(VIEWPORT_W / SCALE / 2, initial_y),
            angle=0.0,
            fixtures=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.lander.color1 = (0.5, 0.4, 0.9)
        self.lander.color2 = (0.3, 0.3, 0.5)
        self.lander.ApplyForceToCenter(
            (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM),
             self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM)), True)

        self.legs = []
        for i in [-1, +1]:
            leg = self.world.CreateDynamicBody(
                position=(VIEWPORT_W / SCALE / 2 - i * LEG_AWAY / SCALE,
                          initial_y),
                angle=(i * 0.05),
                fixtures=fixtureDef(shape=polygonShape(box=(LEG_W / SCALE,
                                                            LEG_H / SCALE)),
                                    density=1.0,
                                    restitution=0.0,
                                    categoryBits=0x0020,
                                    maskBits=0x001))
            leg.ground_contact = False
            leg.color1 = (0.5, 0.4, 0.9)
            leg.color2 = (0.3, 0.3, 0.5)
            rjd = revoluteJointDef(
                bodyA=self.lander,
                bodyB=leg,
                localAnchorA=(0, 0),
                localAnchorB=(i * LEG_AWAY / SCALE, LEG_DOWN / SCALE),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=LEG_SPRING_TORQUE,
                motorSpeed=+0.3 * i  # low enough not to jump back into the sky
            )
            if i == -1:
                rjd.lowerAngle = +0.9 - 0.5  # The most esoteric numbers here, angled legs have freedom to travel within
                rjd.upperAngle = +0.9
            else:
                rjd.lowerAngle = -0.9
                rjd.upperAngle = -0.9 + 0.5
            leg.joint = self.world.CreateJoint(rjd)
            self.legs.append(leg)

        self.drawlist = [self.lander] + self.legs

        return self.step(np.array([0, 0]) if self.continuous else 0)[0]
Пример #36
0
    def __init__(self):

        # Holds the score for the game.
        self.score = 0
        self.scoreCount = 0

        # Dimensions for the parts of the game.
        self.trackWidth = 5.0
        self.cartWidth = 0.3
        self.cartHeight = 0.2
        self.cartMass = 1
        self.poleMass = 0.1
        self.trackThickness = 0.01
        self.poleLength = self.cartHeight * 4
        self.poleThickness = 0.05

        self.force = 0.125

        self.end = False

        # Size of the screen, and Box2D world.
        self.screenSize = (640, 480)
        self.worldSize = (float(self.trackWidth), float(self.trackWidth))

        # Initialize the Box2D world.
        self.world = b2.world(gravity=(0, -5), doSleep=True)

        # Used for dynamics update and for graphics update.
        self.framesPerSecond = 30
        self.velocityIterations = 8
        self.positionIterations = 6

        # Colours and fonts.
        self.trackColor = (100, 100, 100)
        self.arrowColor = (50, 50, 250)
        self.font = pygame.font.SysFont("monospace", 30)

        ####################################

        # Now build the world.

        poleCategory = 0x0002

        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackWidth / 2,
                                                     self.trackThickness / 2)),
                          friction=0.001,
                          categoryBits=0x0001,
                          maskBits=(0xFFFF & ~poleCategory))
        self.track = self.world.CreateStaticBody(
            position=(0, 0), fixtures=f, userData={'color': self.trackColor})
        self.trackTop = self.world.CreateStaticBody(
            position=(0, self.trackThickness + self.cartHeight * 1.1),
            fixtures=f)

        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.trackThickness / 2,
                                                     self.trackThickness / 2)),
                          friction=0.001,
                          categoryBits=0x0001,
                          maskBits=(0xFFFF & ~poleCategory))

        # Make the cart body and fixture.
        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.cartWidth / 2,
                                                     self.cartHeight / 2)),
                          density=self.cartMass,
                          friction=0.001,
                          restitution=0.5,
                          categoryBits=0x0001,
                          maskBits=(0xFFFF & ~poleCategory))
        self.cart = self.world.CreateDynamicBody(
            position=(0, self.trackThickness),
            fixtures=f,
            userData={'color': (0, 0, 0)})

        # Make the pole body and fixture.  Initially the pole is hanging
        # down, which defines the zero angle.
        f = b2.fixtureDef(shape=b2.polygonShape(box=(self.poleThickness / 2,
                                                     self.poleLength / 2)),
                          density=self.poleMass,
                          categoryBits=poleCategory)
        self.pole = self.world.CreateDynamicBody(
            position=(0, self.trackThickness + self.cartHeight / 2 +
                      self.poleThickness + self.poleLength / 2),
            fixtures=f,
            userData={'color': (222, 184, 135)})

        # Make the pole-cart joint.
        self.world.CreateRevoluteJoint(
            bodyA=self.pole,
            bodyB=self.cart,
            anchor=(0, self.trackThickness + self.cartHeight / 2 +
                    self.poleThickness))
Пример #37
0
    def _reset(self):
        self._destroy()
        self.world.contactListener = ContactDetector(self)
        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=5.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((np.random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True)

        self.legs = []
        self.joints = []
        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))

        self.drawlist = self.terrain + self.legs + [self.hull]

        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,0,0,0]))[0]
Пример #38
0
    def __init__(self,
                 world,
                 init_coord,
                 penalty_sec=set(),
                 color=None,
                 bot=False):
        """ Constructor to define Car.
        Parameters
        ----------
        world : Box2D World
        init_coord : tuple
            (angle, x, y)
        penalty_sec : set
            Numbers from 2..9 which define sections where car can't be
            so penalty can be assigned
        color : tuple
            Selfexplanatory
        """

        init_angle, init_x, init_y = init_coord
        SENSOR = SENSOR_BOT if bot else SENSOR_SHAPE
        self.world = world
        # # make two sensor dots close and far...
        # additional_fixture = [fixtureDef(shape=polygonShape(vertices=[(x*SIZE, y*SIZE) for x, y in SENSOR_ADD]),
        #                                 isSensor=True, userData='sensor')] if bot else []
        self.hull = self.world.CreateDynamicBody(
            position=(init_x, init_y),
            angle=init_angle,
            fixtures=[
                fixtureDef(
                    shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                                 for x, y in HULL_POLY4]),
                    density=1.0,
                    userData='body'),
                fixtureDef(shape=polygonShape(vertices=[(x * SIZE, y * SIZE)
                                                        for x, y in SENSOR]),
                           isSensor=True,
                           userData='sensor')
            ])  # + additional_fixture)
        self.hull.color = color or ((0.2, 0.8, 1) if bot else (0.8, 0.0, 0.0))
        self.hull.name = 'bot_car' if bot else 'car'
        self.hull.cross_time = float('inf')
        self.hull.stop = False
        self.hull.collision = False
        self.hull.penalty = False
        self.hull.penalty_sec = penalty_sec
        self.hull.path = ''
        self.hull.userData = self.hull
        self.wheels = []
        self.fuel_spent = 0.0
        WHEEL_POLY = [(-WHEEL_W, +WHEEL_R), (+WHEEL_W, +WHEEL_R),
                      (+WHEEL_W, -WHEEL_R), (-WHEEL_W, -WHEEL_R)]
        for wx, wy in WHEELPOS:
            front_k = 1.0 if wy > 0 else 1.0
            w = self.world.CreateDynamicBody(
                position=(init_x + wx * SIZE, init_y + wy * SIZE),
                angle=init_angle,
                fixtures=fixtureDef(
                    shape=polygonShape(vertices=[(x * front_k * SIZE,
                                                  y * front_k * SIZE)
                                                 for x, y in WHEEL_POLY]),
                    density=0.1,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0))
            w.wheel_rad = front_k * WHEEL_R * SIZE
            w.color = WHEEL_COLOR
            w.gas = 0.0
            w.brake = 0.0
            w.steer = 0.0
            w.phase = 0.0  # wheel angle
            w.omega = 0.0  # angular velocity
            rjd = revoluteJointDef(
                bodyA=self.hull,
                bodyB=w,
                localAnchorA=(wx * SIZE, wy * SIZE),
                localAnchorB=(0, 0),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=180 * 900 * SIZE * SIZE,
                motorSpeed=0,
                lowerAngle=-0.4,
                upperAngle=+0.4,
            )
            w.joint = self.world.CreateJoint(rjd)
            w.tiles = set()
            w.name = 'wheel'
            w.collision = False
            w.penalty = False
            w.penalty_sec = penalty_sec
            w.userData = w
            self.wheels.append(w)
        self.drawlist = self.wheels + [self.hull]
        self.target = (0, 0)
Пример #39
0
    def _generate_terrain(self, hardcore):
        GRASS, STUMP, STAIRS, PIT, _STATES_ = range(5)
        state    = GRASS
        velocity = 0.0
        y        = TERRAIN_HEIGHT
        counter  = TERRAIN_STARTPAD
        oneshot  = False
        self.terrain   = []
        self.terrain_x = []
        self.terrain_y = []
        for i in range(TERRAIN_LENGTH):
            x = i*TERRAIN_STEP
            self.terrain_x.append(x)

            if state==GRASS and not oneshot:
                velocity = 0.8*velocity + 0.01*np.sign(TERRAIN_HEIGHT - y)
                if i > TERRAIN_STARTPAD: velocity += np.random.uniform(-1, 1)/SCALE   #1
                y += velocity

            elif state==PIT and oneshot:
                counter = np.random.randint(3, 5)
                poly = [
                    (x,              y),
                    (x+TERRAIN_STEP, y),
                    (x+TERRAIN_STEP, y-4*TERRAIN_STEP),
                    (x,              y-4*TERRAIN_STEP),
                    ]
                t = self.world.CreateStaticBody(
                    fixtures = fixtureDef(
                        shape=polygonShape(vertices=poly),
                        friction = FRICTION
                    ))
                t.color1, t.color2 = (1,1,1), (0.6,0.6,0.6)
                self.terrain.append(t)
                t = self.world.CreateStaticBody(
                    fixtures = fixtureDef(
                        shape=polygonShape(vertices=[(p[0]+TERRAIN_STEP*counter,p[1]) for p in poly]),
                        friction = FRICTION
                    ))
                t.color1, t.color2 = (1,1,1), (0.6,0.6,0.6)
                self.terrain.append(t)
                counter += 2
                original_y = y

            elif state==PIT and not oneshot:
                y = original_y
                if counter > 1:
                    y -= 4*TERRAIN_STEP

            elif state==STUMP and oneshot:
                counter = np.random.randint(1, 3)
                poly = [
                    (x,                      y),
                    (x+counter*TERRAIN_STEP, y),
                    (x+counter*TERRAIN_STEP, y+counter*TERRAIN_STEP),
                    (x,                      y+counter*TERRAIN_STEP),
                    ]
                t = self.world.CreateStaticBody(
                    fixtures = fixtureDef(
                        shape=polygonShape(vertices=poly),
                        friction = FRICTION
                    ))
                t.color1, t.color2 = (1,1,1), (0.6,0.6,0.6)
                self.terrain.append(t)

            elif state==STAIRS and oneshot:
                stair_height = +1 if np.random.ranf() > 0.5 else -1
                stair_width = np.random.randint(4, 5)
                stair_steps = np.random.randint(3, 5)
                original_y = y
                for s in range(stair_steps):
                    poly = [
                        (x+(    s*stair_width)*TERRAIN_STEP, y+(   s*stair_height)*TERRAIN_STEP),
                        (x+((1+s)*stair_width)*TERRAIN_STEP, y+(   s*stair_height)*TERRAIN_STEP),
                        (x+((1+s)*stair_width)*TERRAIN_STEP, y+(-1+s*stair_height)*TERRAIN_STEP),
                        (x+(    s*stair_width)*TERRAIN_STEP, y+(-1+s*stair_height)*TERRAIN_STEP),
                        ]
                    t = self.world.CreateStaticBody(
                        fixtures = fixtureDef(
                            shape=polygonShape(vertices=poly),
                            friction = FRICTION
                        ))
                    t.color1, t.color2 = (1,1,1), (0.6,0.6,0.6)
                    self.terrain.append(t)
                counter = stair_steps*stair_width

            elif state==STAIRS and not oneshot:
                s = stair_steps*stair_width - counter - stair_height
                n = s/stair_width
                y = original_y + (n*stair_height)*TERRAIN_STEP

            oneshot = False
            self.terrain_y.append(y)
            counter -= 1
            if counter==0:
                counter = np.random.randint(TERRAIN_GRASS/2, TERRAIN_GRASS)
                if state==GRASS and hardcore:
                    state = np.random.randint(1, _STATES_)
                    oneshot = True
                else:
                    state = GRASS
                    oneshot = True

        self.terrain_poly = []
        for i in range(TERRAIN_LENGTH-1):
            poly = [
                (self.terrain_x[i],   self.terrain_y[i]),
                (self.terrain_x[i+1], self.terrain_y[i+1])
                ]
            t = self.world.CreateStaticBody(
                fixtures = fixtureDef(
                    shape=edgeShape(vertices=poly),
                    friction = FRICTION,
                    categoryBits=0x0001,
                ))
            color = (0.3, 1.0 if i%2==0 else 0.8, 0.3)
            t.color1 = color
            t.color2 = color
            self.terrain.append(t)
            color = (0.4, 0.6, 0.3)
            poly += [ (poly[1][0], 0), (poly[0][0], 0) ]
            self.terrain_poly.append( (poly, color) )
        self.terrain.reverse()
Пример #40
0
    def draw(self, world, init_x, init_y, force_to_center):
        HULL_FIXTURES = [
            fixtureDef(
                shape=polygonShape(vertices=[(x / self.SCALE, y / self.SCALE) for x, y in polygon]),
                density=5.0,
                friction=0.1,
                categoryBits=0x20,
                maskBits=0x000F)  # 0.99 bouncy
            for polygon in HULL_POLYGONS
        ]

        LEG_FD = fixtureDef(
            shape=polygonShape(box=(self.LEG_W / 2, self.LEG_H / 2)),
            density=1.0,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F)

        LOWER_FD = fixtureDef(
            shape=polygonShape(box=(0.8 * self.LEG_W / 2, self.LEG_H / 2)),
            density=1.0,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F)

        hull = world.CreateDynamicBody(
            position=(init_x, init_y),
            fixtures=HULL_FIXTURES
        )
        hull.color1 = (0.5, 0.4, 0.9)
        hull.color2 = (0.3, 0.3, 0.5)
        hull.ApplyForceToCenter((force_to_center, 0), True)

        hull.userData = CustomBodyUserData(True, is_contact_critical=self.reset_on_hull_critical_contact, name="hull")
        self.body_parts.append(hull)
        self.reference_head_object = hull

        for i in [-1, +1]:
            leg = world.CreateDynamicBody(
                position=(init_x, init_y - self.LEG_H / 2 - self.LEG_DOWN),
                #angle=(i * 0.05),
                fixtures=LEG_FD
            )
            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=hull,
                bodyB=leg,
                anchor=(init_x, init_y - self.LEG_DOWN),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=self.MOTORS_TORQUE,
                motorSpeed=i,
                lowerAngle=-0.8,
                upperAngle=1.1,
            )

            leg.userData = CustomBodyUserData(False, name="leg")
            self.body_parts.append(leg)

            joint_motor = world.CreateJoint(rjd)
            joint_motor.userData = CustomMotorUserData(SPEED_HIP, False)
            self.motors.append(joint_motor)

            lower = world.CreateDynamicBody(
                position=(init_x, init_y - self.LEG_H * 3 / 2 - self.LEG_DOWN),
                #angle=(i * 0.05),
                fixtures=LOWER_FD
            )
            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,
                anchor=(init_x, init_y - self.LEG_DOWN - self.LEG_H),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=self.MOTORS_TORQUE,
                motorSpeed=1,
                lowerAngle=-1.6,
                upperAngle=-0.1,
            )

            lower.userData = CustomBodyUserData(True, name="lower")
            self.body_parts.append(lower)

            joint_motor = world.CreateJoint(rjd)
            joint_motor.userData = CustomMotorUserData(
                SPEED_KNEE,
                True,
                contact_body=lower,
                angle_correction=1.0)
            self.motors.append(joint_motor)
Пример #41
0
    def _create_track(self):
        CHECKPOINTS = 12

        # Create checkpoints
        checkpoints = []
        for c in range(CHECKPOINTS):
            alpha = 2*math.pi*c/CHECKPOINTS + self.np_random.uniform(0, 2*math.pi*1/CHECKPOINTS)
            rad = self.np_random.uniform(TRACK_RAD/3, TRACK_RAD)
            if c==0:
                alpha = 0
                rad = 1.5*TRACK_RAD
            if c==CHECKPOINTS-1:
                alpha = 2*math.pi*c/CHECKPOINTS
                self.start_alpha = 2*math.pi*(-0.5)/CHECKPOINTS
                rad = 1.5*TRACK_RAD
            checkpoints.append( (alpha, rad*math.cos(alpha), rad*math.sin(alpha)) )

        #print "\n".join(str(h) for h in checkpoints)
        #self.road_poly = [ (    # uncomment this to see checkpoints
        #    [ (tx,ty) for a,tx,ty in checkpoints ],
        #    (0.7,0.7,0.9) ) ]
        self.road = []

        # Go from one checkpoint to another to create track
        x, y, beta = 1.5*TRACK_RAD, 0, 0
        dest_i = 0
        laps = 0
        track = []
        no_freeze = 2500
        visited_other_side = False
        while 1:
            alpha = math.atan2(y, x)
            if visited_other_side and alpha > 0:
                laps += 1
                visited_other_side = False
            if alpha < 0:
                visited_other_side = True
                alpha += 2*math.pi
            while True: # Find destination from checkpoints
                failed = True
                while True:
                    dest_alpha, dest_x, dest_y = checkpoints[dest_i % len(checkpoints)]
                    if alpha <= dest_alpha:
                        failed = False
                        break
                    dest_i += 1
                    if dest_i % len(checkpoints) == 0: break
                if not failed: break
                alpha -= 2*math.pi
                continue
            r1x = math.cos(beta)
            r1y = math.sin(beta)
            p1x = -r1y
            p1y = r1x
            dest_dx = dest_x - x  # vector towards destination
            dest_dy = dest_y - y
            proj = r1x*dest_dx + r1y*dest_dy  # destination vector projected on rad
            while beta - alpha >  1.5*math.pi: beta -= 2*math.pi
            while beta - alpha < -1.5*math.pi: beta += 2*math.pi
            prev_beta = beta
            proj *= SCALE
            if proj >  0.3: beta -= min(TRACK_TURN_RATE, abs(0.001*proj))
            if proj < -0.3: beta += min(TRACK_TURN_RATE, abs(0.001*proj))
            x += p1x*TRACK_DETAIL_STEP
            y += p1y*TRACK_DETAIL_STEP
            track.append( (alpha,prev_beta*0.5 + beta*0.5,x,y) )
            if laps > 4: break
            no_freeze -= 1
            if no_freeze==0: break
        #print "\n".join([str(t) for t in enumerate(track)])

        # Find closed loop range i1..i2, first loop should be ignored, second is OK
        i1, i2 = -1, -1
        i = len(track)
        while True:
            i -= 1
            if i==0: return False  # Failed
            pass_through_start = track[i][0] > self.start_alpha and track[i-1][0] <= self.start_alpha
            if pass_through_start and i2==-1:
                i2 = i
            elif pass_through_start and i1==-1:
                i1 = i
                break
        if self.verbose == 1:
            print("Track generation: %i..%i -> %i-tiles track" % (i1, i2, i2-i1))
        assert i1!=-1
        assert i2!=-1

        track = track[i1:i2-1]

        first_beta = track[0][1]
        first_perp_x = math.cos(first_beta)
        first_perp_y = math.sin(first_beta)
        # Length of perpendicular jump to put together head and tail
        well_glued_together = np.sqrt(
            np.square( first_perp_x*(track[0][2] - track[-1][2]) ) +
            np.square( first_perp_y*(track[0][3] - track[-1][3]) ))
        if well_glued_together > TRACK_DETAIL_STEP:
            return False

        # Red-white border on hard turns
        border = [False]*len(track)
        for i in range(len(track)):
            good = True
            oneside = 0
            for neg in range(BORDER_MIN_COUNT):
                beta1 = track[i-neg-0][1]
                beta2 = track[i-neg-1][1]
                good &= abs(beta1 - beta2) > TRACK_TURN_RATE*0.2
                oneside += np.sign(beta1 - beta2)
            good &= abs(oneside) == BORDER_MIN_COUNT
            border[i] = good
        for i in range(len(track)):
            for neg in range(BORDER_MIN_COUNT):
                border[i-neg] |= border[i]

        # Create tiles
        for i in range(len(track)):
            alpha1, beta1, x1, y1 = track[i]
            alpha2, beta2, x2, y2 = track[i-1]
            road1_l = (x1 - TRACK_WIDTH*math.cos(beta1), y1 - TRACK_WIDTH*math.sin(beta1))
            road1_r = (x1 + TRACK_WIDTH*math.cos(beta1), y1 + TRACK_WIDTH*math.sin(beta1))
            road2_l = (x2 - TRACK_WIDTH*math.cos(beta2), y2 - TRACK_WIDTH*math.sin(beta2))
            road2_r = (x2 + TRACK_WIDTH*math.cos(beta2), y2 + TRACK_WIDTH*math.sin(beta2))
            t = self.world.CreateStaticBody( fixtures = fixtureDef(
                shape=polygonShape(vertices=[road1_l, road1_r, road2_r, road2_l])
                ))
            t.userData = t
            c = 0.01*(i%3)
            t.color = [ROAD_COLOR[0] + c, ROAD_COLOR[1] + c, ROAD_COLOR[2] + c]
            t.road_visited = False
            t.road_friction = 1.0
            t.fixtures[0].sensor = True
            self.road_poly.append(( [road1_l, road1_r, road2_r, road2_l], t.color ))
            self.road.append(t)
            if border[i]:
                side = np.sign(beta2 - beta1)
                b1_l = (x1 + side* TRACK_WIDTH        *math.cos(beta1), y1 + side* TRACK_WIDTH        *math.sin(beta1))
                b1_r = (x1 + side*(TRACK_WIDTH+BORDER)*math.cos(beta1), y1 + side*(TRACK_WIDTH+BORDER)*math.sin(beta1))
                b2_l = (x2 + side* TRACK_WIDTH        *math.cos(beta2), y2 + side* TRACK_WIDTH        *math.sin(beta2))
                b2_r = (x2 + side*(TRACK_WIDTH+BORDER)*math.cos(beta2), y2 + side*(TRACK_WIDTH+BORDER)*math.sin(beta2))
                self.road_poly.append(( [b1_l, b1_r, b2_r, b2_l], (1,1,1) if i%2==0 else (1,0,0) ))
        self.track = track
        return True
Пример #42
0
    def draw(self, world, init_x, init_y, force_to_center):
        init_y = init_y + 1
        #### HULL ####
        HULL_FD = fixtureDef(
            shape=polygonShape(vertices=[(x / self.SCALE, y / self.SCALE)
                                         for x, y in HULL_POLYGONS]),
            density=self.DENSITY,
            friction=0.1,
            categoryBits=0x20,
            maskBits=0x000F)  # 0.99 bouncy

        hull = world.CreateDynamicBody(position=(init_x, init_y),
                                       fixtures=HULL_FD)
        hull.color1 = (0.5, 0.4, 0.9)
        hull.color2 = (0.3, 0.3, 0.5)
        # hull.ApplyForceToCenter((force_to_center, 0), True)

        hull.userData = CustomBodyUserData(True,
                                           is_contact_critical=False,
                                           name="head")
        self.body_parts.append(hull)
        self.reference_head_object = hull

        #### P1 ####
        body_p1_x = init_x - 35 / 2 / self.SCALE - 16 / 2 / self.SCALE
        BODY_P1_FD = fixtureDef(
            shape=polygonShape(vertices=[(x / self.SCALE, y / self.SCALE)
                                         for x, y in BODY_P1]),
            density=self.DENSITY,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F)

        body_p1 = world.CreateDynamicBody(position=(body_p1_x, init_y),
                                          fixtures=BODY_P1_FD)
        body_p1.color1 = (0.5, 0.4, 0.9)
        body_p1.color2 = (0.3, 0.3, 0.5)

        rjd = revoluteJointDef(
            bodyA=hull,
            bodyB=body_p1,
            anchor=(init_x - 35 / 2 / self.SCALE, init_y),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=self.MOTORS_TORQUE,
            motorSpeed=1,
            lowerAngle=-0.1 * np.pi,
            upperAngle=0.2 * np.pi,
        )

        body_p1.userData = CustomBodyUserData(True, name="body")
        self.body_parts.append(body_p1)

        joint_motor = world.CreateJoint(rjd)
        joint_motor.userData = CustomMotorUserData(SPEED_KNEE,
                                                   True,
                                                   contact_body=body_p1)
        self.motors.append(joint_motor)

        #### P2 ####
        body_p2_x = body_p1_x - 16 / 2 / self.SCALE - 16 / 2 / self.SCALE
        BODY_P2_FD = fixtureDef(
            shape=polygonShape(vertices=[(x / self.SCALE, y / self.SCALE)
                                         for x, y in BODY_P2]),
            density=self.DENSITY,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F)

        body_p2 = world.CreateDynamicBody(position=(body_p2_x, init_y),
                                          fixtures=BODY_P2_FD)
        body_p2.color1 = (0.5, 0.4, 0.9)
        body_p2.color2 = (0.3, 0.3, 0.5)

        rjd = revoluteJointDef(
            bodyA=body_p1,
            bodyB=body_p2,
            anchor=(body_p1_x - 16 / 2 / self.SCALE, init_y),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=self.MOTORS_TORQUE,
            motorSpeed=1,
            lowerAngle=-0.15 * np.pi,
            upperAngle=0.15 * np.pi,
        )

        body_p2.userData = CustomBodyUserData(True, name="body")
        self.body_parts.append(body_p2)

        joint_motor = world.CreateJoint(rjd)
        joint_motor.userData = CustomMotorUserData(SPEED_KNEE,
                                                   True,
                                                   contact_body=body_p2)
        self.motors.append(joint_motor)

        #### P3 ####
        body_p3_x = body_p2_x - 16 / 2 / self.SCALE - 8 / 2 / self.SCALE
        BODY_P3_FD = fixtureDef(
            shape=polygonShape(vertices=[(x / self.SCALE, y / self.SCALE)
                                         for x, y in BODY_P3]),
            density=self.DENSITY,
            restitution=0.0,
            categoryBits=0x20,
            maskBits=0x000F)

        body_p3 = world.CreateDynamicBody(position=(body_p3_x, init_y),
                                          fixtures=BODY_P3_FD)
        body_p3.color1 = (0.5, 0.4, 0.9)
        body_p3.color2 = (0.3, 0.3, 0.5)

        rjd = revoluteJointDef(
            bodyA=body_p2,
            bodyB=body_p3,
            anchor=(body_p2_x - 16 / 2 / self.SCALE, init_y),
            enableMotor=True,
            enableLimit=True,
            maxMotorTorque=self.MOTORS_TORQUE,
            motorSpeed=1,
            lowerAngle=-0.3 * np.pi,
            upperAngle=0.3 * np.pi,
        )

        body_p3.userData = CustomBodyUserData(True, name="body")
        self.body_parts.append(body_p3)
        self.tail = body_p3

        joint_motor = world.CreateJoint(rjd)
        joint_motor.userData = CustomMotorUserData(SPEED_KNEE,
                                                   True,
                                                   contact_body=body_p3)
        self.motors.append(joint_motor)

        #### FIN ####
        FIN_FD = fixtureDef(shape=polygonShape(vertices=[(x / self.SCALE,
                                                          y / self.SCALE)
                                                         for x, y in FIN]),
                            density=self.DENSITY,
                            restitution=0.0,
                            categoryBits=0x20,
                            maskBits=0x000F)

        fin_positions = [
            # [init_x + 35 / 2 / self.SCALE / 2, init_y],
            # [init_x - 35 / 2 / self.SCALE / 2, init_y],
            [init_x, init_y - 22 / 2 / self.SCALE + 0.2],
            # [init_x - 35 / 2 / self.SCALE / 2, init_y - 22 / 2 / self.SCALE + 0.1],
        ]

        fin_angle = -0.2 * np.pi
        middle_fin_x_distance = np.sin(fin_angle) * 20 / 2 / self.SCALE
        middle_fin_y_distance = np.cos(fin_angle) * 20 / 2 / self.SCALE

        for fin_pos in fin_positions:
            current_fin_x = fin_pos[0] + middle_fin_x_distance
            current_fin_y = fin_pos[1] - middle_fin_y_distance

            fin = world.CreateDynamicBody(position=(current_fin_x,
                                                    current_fin_y),
                                          fixtures=FIN_FD,
                                          angle=fin_angle)
            fin.color1 = (0.5, 0.4, 0.9)
            fin.color2 = (0.3, 0.3, 0.5)

            rjd = revoluteJointDef(
                bodyA=hull,
                bodyB=fin,
                anchor=(fin_pos[0], fin_pos[1]),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=self.MOTORS_TORQUE,
                motorSpeed=1,
                lowerAngle=-0.3 * np.pi,
                upperAngle=0.2 * np.pi,
            )

            fin.userData = CustomBodyUserData(True, name="fin")
            self.body_parts.append(fin)
            self.fins.append(fin)

            joint_motor = world.CreateJoint(rjd)
            joint_motor.userData = CustomMotorUserData(SPEED_KNEE,
                                                       True,
                                                       contact_body=fin)
            self.motors.append(joint_motor)