def LaunchBomb(self, position, velocity):
        """
        A bomb is a simple circle which has the specified position and velocity.
        """
        if self.bomb:
            self.world.DestroyBody(self.bomb)
            self.bomb = None

        bd = box2d.b2BodyDef()
        bd.allowSleep = True
        bd.position = position
        bd.isBullet = True
        self.bomb = self.world.CreateBody(bd)
        self.bomb.SetLinearVelocity(velocity)

        sd = box2d.b2CircleDef()
        sd.radius = 0.3
        sd.density = 20.0
        sd.restitution = 0.1

        minV = position - box2d.b2Vec2(0.3,0.3)
        maxV = position + box2d.b2Vec2(0.3,0.3)

        aabb = box2d.b2AABB()
        aabb.lowerBound = minV
        aabb.upperBound = maxV

        if self.world.InRange(aabb):
            self.bomb.CreateShape(sd)
            self.bomb.SetMassFromShapes()
Example #2
0
    def raycast(self):

        sensor_length = 150

        ## FRONT LEFT
        front_left_point1 = self.body.GetWorldPoint(
            Box2D.b2Vec2(-AGENT_WIDTH / 2, AGENT_HEIGHT))
        angle = self.body.angle + (math.pi / 2) + 0.0
        front_left_d = (sensor_length * math.cos(angle),
                        sensor_length * math.sin(angle))
        front_left_point2 = front_left_point1 + front_left_d

        self.sensors["front_left"] = self.raycast_single_sensor(
            front_left_point1, front_left_point2)

        ## FRONT RIGHT
        front_right_point1 = self.body.GetWorldPoint(
            Box2D.b2Vec2(AGENT_WIDTH / 2, AGENT_HEIGHT))
        angle = self.body.angle + (math.pi / 2) - 0.0
        front_right_d = (sensor_length * math.cos(angle),
                         sensor_length * math.sin(angle))
        front_right_point2 = front_right_point1 + front_right_d

        self.sensors["front_right"] = self.raycast_single_sensor(
            front_right_point1, front_right_point2)

        ## REAR
        rear_point1 = self.body.GetWorldPoint(Box2D.b2Vec2(0, 0))
        angle = self.body.angle - (math.pi / 2)
        rear_d = (sensor_length * math.cos(angle),
                  sensor_length * math.sin(angle))
        rear_point2 = rear_point1 + rear_d

        self.sensors["rear"] = self.raycast_single_sensor(
            rear_point1, rear_point2)
Example #3
0
 def tryStop(self, horiz=True, vert=False):
     #print "trying to stop"
     self.curVel = self.body.GetLinearVelocity()
     if horiz:
         self.body.ApplyForce(Box2D.b2Vec2(FPS*(-self.curVel.x)*self.body.GetMass(),0), self.body.GetWorldCenter())
     if vert:
         self.body.ApplyForce(Box2D.b2Vec2(0,FPS*(-self.curVel.y)*self.body.GetMass()), self.body.GetWorldCenter())
Example #4
0
    def compute_centroids(self, vectors):
        count = len(vectors)
        assert count >= 3

        c = Box2D.b2Vec2(0, 0)
        area = 0

        ref_point = Box2D.b2Vec2(0, 0)
        inv3 = 1 / 3

        for i in range(count):
            # Triangle vertices
            p1 = ref_point
            p2 = vectors[i]
            p3 = vectors[i + 1] if i + 1 < count else vectors[0]

            e1 = p2 - p1
            e2 = p3 - p1

            d = Box2D.b2Cross(e1, e2)

            triangle_area = 0.5 * d
            area += triangle_area

            # Area weighted centroid
            c += triangle_area * inv3 * (p1 + p2 + p3)

        if area > Box2D.b2_epsilon:
            c *= 1 / area
        else:
            area = 0

        return c, area
    def ReportFixture(self, fixture, point, normal, fraction):
        '''
        Called for each fixture found in the query. You control how the ray
        proceeds by returning a float that indicates the fractional length of
        the ray. By returning 0, you set the ray length to zero. By returning
        the current fraction, you proceed to find the closest point. By
        returning 1, you continue with the original ray clipping. By returning
        -1, you will filter out the current fixture (the ray will not hit it).
        '''
        self.hit = True
        self.fixture = fixture
        self.point = Box2D.b2Vec2(point)
        self.normal = Box2D.b2Vec2(normal)

        # se ho specificato un gruppo particolare nel costruttore
        # e la fixture non appartiene a quel gruppo, non ho una hit
        if self.hit:
            if self.group and self.fixture.filterData.groupIndex is not self.group:
                self.hit = False

        # NOTE: You will get this error:
        #   "TypeError: Swig director type mismatch in output value of
        #    type 'float32'"
        # without returning a value
        return fraction
Example #6
0
 def update_path(self):
     target = world2grid(Box2D.b2Vec2(4, 1.5))
     start = world2grid(Box2D.b2Vec2(0.5, 4.5))
     world = grid2world(target)
     print(world)
     print(target)
     self.path = astar(self.DUNGEON, self.width, self.height, start, 0, target)  # (y,x)
    def __init__(self, **kw):
        super(Framework, self).__init__(**kw)

        # Initialize the text display group
        self.textGroup = grText(self)

        # Load the font and record the screen dimensions
        self.font = pyglet.font.load(self.fontname, self.fontsize)
        self.screenSize = box2d.b2Vec2(self.width, self.height)

        # Box2D Initialization
        self.worldAABB = box2d.b2AABB()
        self.worldAABB.lowerBound = (-200.0, -100.0)
        self.worldAABB.upperBound = ( 200.0, 200.0)
        gravity = (0.0, -10.0)

        doSleep = True
        self.world = box2d.b2World(self.worldAABB, gravity, doSleep)
        self.destructionListener = fwDestructionListener()
        self.boundaryListener = fwBoundaryListener()
        self.contactListener = fwContactListener()
        self.debugDraw = fwDebugDraw()

        self.debugDraw.surface = self.screen

        self.destructionListener.test = self
        self.boundaryListener.test = self
        self.contactListener.test = self
        
        self.world.SetDestructionListener(self.destructionListener)
        self.world.SetBoundaryListener(self.boundaryListener)
        self.world.SetContactListener(self.contactListener)
        self.world.SetDebugDraw(self.debugDraw)

        self._viewCenter = box2d.b2Vec2(0,10.0)
Example #8
0
    def SetProjectileBLPosition(self, dx, dy):

        projectile_start_pos = box2d.b2Vec2(dx,dy)
        projectile_start_pos.Normalize()
        projectile_start_pos.mul_float(self.midpoint.x + 30)
        projectile_start_pos.add_vector(box2d.b2Vec2(self.body.GetWorldCenter()[0] / globals.physics.scale_factor, self.body.GetWorldCenter()[1] / globals.physics.scale_factor))

        self.projectile_position = Point(projectile_start_pos[0], projectile_start_pos[1])
Example #9
0
 def intersection(self, cp1, cp2, s, e):
     dc = Box2D.b2Vec2(cp1.x - cp2.x, cp1.y - cp2.y)
     dp = Box2D.b2Vec2(s.x - e.x, s.y - e.y)
     n1 = cp1.x * cp2.y - cp1.y * cp2.x
     n2 = s.x * e.y - s.y * e.x
     n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x)
     return Box2D.b2Vec2((n1 * dp.x - n2 * dc.x) * n3,
                         (n1 * dp.y - n2 * dc.y) * n3)
Example #10
0
    def draw(self, camera):
        world = engine.get().box2d_world

        query = DrawQueryCallback(camera)

        rect = rectangle.from_entity(camera.entity).bounding_rect()

        aabb = Box2D.b2AABB(lowerBound=Box2D.b2Vec2(rect.bottom_left),upperBound=Box2D.b2Vec2(rect.top_right))

        world.QueryAABB(query, aabb)
Example #11
0
 def try_add_blood(self, contact):
     touches_crow = (isinstance(contact.shape1.GetBody().userData, Crow)
                     or isinstance(contact.shape2.GetBody().userData, Crow))
     if touches_crow:
         p = box2d.b2Vec2(contact.position.x, contact.position.y)
         if len(self.blood) > settings.max_blood:
             self.blood.pop()
         for i in xrange(1):
             m = p + box2d.b2Vec2(random.random(), random.random())
             self.blood.insert(0, BloodParticle(m, 1))
Example #12
0
 def create(self, world, carBody, carPos, cfg):
     self.maxForwardSpeed = cfg.maxForwardSpeed
     self.maxBackwardSpeed = cfg.maxBackwardSpeed
     self.maxDriveForce = cfg.maxDriveForce
     self.maxLateralImpulse = cfg.maxLateralImpulse
     bodyDef = b2.b2BodyDef()
     bodyDef.type = b2.b2_dynamicBody
     bodyDef.position = b2.b2Vec2(carPos) + b2.b2Vec2(cfg.position)
     self.body = world.CreateBody(bodyDef)
     fx = self.body.CreatePolygonFixture(box=(cfg.size.width, cfg.size.height),
                                         density=cfg.density)
Example #13
0
    def get_force(self, point, charge):
        """Return an (x,y) vector of the force caused by the gravity."""
        global gc
        point = point
        dx = (self.pos[0] - point[0])
        dy = (self.pos[1] - point[1])
        dist_cb = (dx**2 + dy**2)**1.5
        if dist_cb == 0:
            return box2d.b2Vec2(0.0, 0.0)

        return box2d.b2Vec2(gc*charge*self.charge*(self.mass * dx)/dist_cb,
                            gc*charge*self.charge*(self.mass * -dy)/dist_cb)
Example #14
0
 def __init__(self, target, pos, vel, ang):
     target = Box2D.b2Vec2(target[0], target[1])
     pos = Box2D.b2Vec2(pos[0], pos[1])
     vel = Box2D.b2Vec2(vel[0], vel[1])
     self.index = 0
     DUNGEON = map2grid(WIDTH, HEIGHT)
     self.target_grid = world2grid(target)
     self.selfpos_gird = world2grid(pos)
     self.path = pathprocess(
         astar(DUNGEON, WIDTH, HEIGHT, self.selfpos_gird, 0,
               self.target_grid))
     self.tonext = 1000
     self.velocity = vel
Example #15
0
 def tryMove(self, x, y):
     self.curVel = self.body.GetLinearVelocity()
     
     if x < 0 and self.curVel.x > -MAX_WALK_SPEED: #Not going too fast Left
         if self.curVel.x+x/(FPS*self.body.GetMass()) > -MAX_WALK_SPEED: #You can accelerate all the way asked
             self.body.ApplyForce(Box2D.b2Vec2(x,0), self.body.GetWorldCenter())
         else: #You can only accelerate to the max walk speed
             self.body.ApplyForce(Box2D.b2Vec2(FPS*(-MAX_WALK_SPEED-self.curVel.x)*self.body.GetMass(),0), self.body.GetWorldCenter())
     elif x > 0 and self.curVel.x < MAX_WALK_SPEED: #Not going too fast Right
         if self.curVel.x+x/(FPS*self.body.GetMass()) < MAX_WALK_SPEED: #You can accelerate all the way asked
             self.body.ApplyForce(Box2D.b2Vec2(x,0), self.body.GetWorldCenter())
         else: #You can only accelerate to the max walk speed
             self.body.ApplyForce(Box2D.b2Vec2(FPS*(MAX_WALK_SPEED-self.curVel.x)*self.body.GetMass(),0), self.body.GetWorldCenter())
Example #16
0
    def __init__(self, wld, robot):
        self.wld = wld
        w = wld.w
        self.robot = robot  # Fired by this robot

        self._fuse = None
        self._exploding = False

        r = robot.turret
        pos = r.position
        vel = r.linearVelocity
        ang = r.angle

        blocalvel = box2d.b2Vec2(conf.bulletspeed, 0)
        bwvel = r.GetWorldVector(blocalvel)
        bvel = bwvel + vel
        #print bvel, bvel.Length()

        bodyDef = box2d.b2BodyDef()
        blocalpos = box2d.b2Vec2(.1, 0)
        bwpos = r.GetWorldVector(blocalpos)
        bpos = bwpos + pos
        bodyDef.position = bpos
        bodyDef.angle = ang
        bodyDef.isBullet = True
        bodyDef.linearDamping = 0
        bodyDef.userData = {}

        body = w.CreateBody(bodyDef)
        #print body
        #print 'IB', body.isBullet
        body.linearVelocity = bvel

        shapeDef = box2d.b2PolygonDef()
        shapeDef.SetAsBox(.1, .1)
        shapeDef.density = conf.bullet_density
        shapeDef.restitution = 0
        shapeDef.friction = 0
        shapeDef.filter.groupIndex = -robot.n
        b = body.CreateShape(shapeDef)
        b.userData = {}
        body.SetMassFromShapes()

        body.userData['actor'] = self
        body.userData['kind'] = 'bullet'
        body.userData['shooter'] = robot

        self.body = body

        v = wld.v.addbullet(pos)
        self.v = v
Example #17
0
    def __init__(self, wld, tank):
        self.wld = wld
        w = wld.w
        self.tank = tank

        self._fuse = None
        self._exploding = False

        r = tank.turret
        pos = r.position
        vel = r.linearVelocity
        ang = r.angle

        blocalvel = box2d.b2Vec2(conf.bulletspeed, 0)
        bwvel = r.GetWorldVector(blocalvel)
        bvel = bwvel + vel
        

        bodyDef = box2d.b2BodyDef()
        blocalpos = box2d.b2Vec2(.1, 0)
        bwpos = r.GetWorldVector(blocalpos)
        bpos = bwpos + pos
        bodyDef.position = bpos
        bodyDef.angle = ang
        bodyDef.isBullet = True
        bodyDef.linearDamping = 0
        bodyDef.userData = {}

        body = w.CreateBody(bodyDef)
        
        
        body.linearVelocity = bvel

        shapeDef = box2d.b2PolygonDef()
        shapeDef.SetAsBox(.1, .1)
        shapeDef.density = conf.bullet_density
        shapeDef.restitution = 0
        shapeDef.friction = 0
        shapeDef.filter.groupIndex = -tank.n
        b = body.CreateShape(shapeDef)
        b.userData = {}
        body.SetMassFromShapes()

        body.userData['actor'] = self
        body.userData['kind'] = 'bullet'
        body.userData['shooter'] = tank

        self.body = body

        v = wld.v.addbullet(pos)
        self.v = v
Example #18
0
    def move(self, momentum, direction):
        if direction == "forward":
            dirx = -cos(radians(self.heading))
            diry = -sin(radians(self.heading))

        elif direction == "backward":
            dirx = cos(radians(self.heading))
            diry = sin(radians(self.heading))

        if self.strafing == True:
            force = b2.b2Vec2(dirx * momentum / 2, diry * momentum / 2)
        else:
            force = b2.b2Vec2(dirx * momentum, diry * momentum)

        self.body.ApplyLinearImpulse(force, self.body.position)
Example #19
0
    def move(self, momentum, direction):
        if direction == "forward":
            dirx = -cos(radians(self.heading))
            diry = -sin(radians(self.heading))

        elif direction == "backward":
            dirx = cos(radians(self.heading))
            diry = sin(radians(self.heading))

        if self.strafing == True:
            force = b2.b2Vec2(dirx * momentum / 2, diry * momentum / 2)
        else:
            force = b2.b2Vec2(dirx * momentum, diry * momentum)

        self.body.ApplyLinearImpulse(force, self.body.position)
Example #20
0
    def __init__(self, wld, robot):
        self.wld = wld
        w = wld.w
        self.robot = robot # Fired by this robot

        self._fuse = None
        self._exploding = False

        r = robot.turret
        pos = r.position
        vel = r.linearVelocity
        ang = r.angle

        blocalvel = box2d.b2Vec2(conf.bulletspeed, 0)
        bwvel = r.GetWorldVector(blocalvel)
        bvel = bwvel + vel
        #print bvel, bvel.length

        bodyDef = box2d.b2BodyDef(type=box2d.b2_dynamicBody,)
        blocalpos = box2d.b2Vec2(.1, 0)
        bwpos = r.GetWorldVector(blocalpos)
        bpos = bwpos + pos
        bodyDef.position = bpos
        bodyDef.angle = ang
        bodyDef.isBullet = True
        bodyDef.linearDamping = 0
        bodyDef.userData = {}

        body = w.CreateBody(bodyDef)
        #print body
        #print 'IB', body.isBullet
        body.linearVelocity = bvel
        body.CreatePolygonFixture(
                    box=(0.1,0.1),
                    friction=0,
                    density=conf.bullet_density,
                    restitution=0,
                    filter = box2d.b2Filter(
                                groupIndex = -robot.n,))

        body.userData['actor'] = self
        body.userData['kind'] = 'bullet'
        body.userData['shooter'] = robot

        self.body = body

        v = wld.v.addbullet(pos)
        self.v = v
 def __init__(self,centre,radius,tc = None,angle=0):
     self.dead = False
     self.tc = tc
     if tc != None:
         self.InitPolygons(tc)
         self.visible = True
     else:
         self.visible = False
     self.bodydef = box2d.b2BodyDef()
     #This is inefficient, but it doesn't want to grab properly otherwise. Shitty hack but whatever
     self.bodydef.allowSleep = False
     self.midpoint = radius*math.sqrt(2)*globals.physics.scale_factor
     self.bodydef.position = box2d.b2Vec2(*(centre*globals.physics.scale_factor))
     self.bodydef.angle = angle
     self.shape = self.CreateShape(radius)
     self.shape.isSensor = self.is_sensor
     if not self.static:
         self.shape.userData = self
     if self.filter_group != None:
         self.shape.filter.groupIndex = self.filter_group
     self.bodydef.isBullet = self.isBullet
     self.body = globals.physics.world.CreateBody(self.bodydef)
     self.shape.density = self.mass
     self.shape.friction = 0.7
     self.shapeI = self.body.CreateShape(self.shape)
     self.child_joint = None
     self.parent_joint = None
     self.ExtraShapes()
     self.PhysUpdate([])
     self.health = Gobject.initial_health
Example #22
0
    def make_satellite(self,
                       density,
                       vel,
                       rad,
                       pos,
                       res,
                       color1=(0, 0, 0),
                       color2=(0, 0, 0),
                       speedup=1):
        planet_poly = []
        for i in range(res):
            ang = -2 * math.pi * i / res
            planet_poly.append(
                (math.cos(ang) * rad / SCALE, math.sin(ang) * rad / SCALE))
        fix = fixtureDef(shape=polygonShape(vertices=planet_poly),
                         density=density,
                         categoryBits=BITS['obstacles'],
                         maskBits=BITS['rocket'] | BITS['target_planet'],
                         restitution=0.0)
        planet = self.world.CreateDynamicBody(position=pos, fixtures=fix)
        planet.color1 = self.torgb(color1[0], color1[1], color1[2])
        planet.color2 = self.torgb(color2[0], color2[1], color2[2])

        #applying initial speed
        vec = planet.worldCenter - self.planet.worldCenter
        G = 1e-5
        speedup = 600 * vec.length * speedup
        initial_mag = math.sqrt(G * self.planet.mass / vec.length) * speedup
        vel_vec = (Box2D.b2Vec2(vec[1], -vec[0]) / vec.length) * initial_mag
        planet.linearVelocity = vel_vec
        return planet
Example #23
0
    def makeping(self, rname, rnd):
        robot = self.robots[rname]
        body = robot.turret

        segmentLength = 65.0

        blocalpos = box2d.b2Vec2(1.12, 0)

        segment = box2d.b2Segment()
        laserStart = (1.12, 0)
        laserDir = (segmentLength, 0.0)
        segment.p1 = body.GetWorldPoint(laserStart)
        segment.p2 = body.GetWorldVector(laserDir)
        segment.p2 += segment.p1

        lambda_, normal, shape = self.w.RaycastOne(segment, False, None)
        hitp = (1 - lambda_) * segment.p1 + lambda_ * segment.p2
        angle = robot.get_turretangle()
        dist = box2d.b2Distance(segment.p1, hitp)

        if shape is not None:
            hitbody = shape.GetBody()
            kind = hitbody.userData['kind']
            if kind == 'robot':
                actor = hitbody.userData['actor']
                if actor._pinged != rnd - 1:
                    actor._pinged = rnd
            return kind, angle, dist
        else:
            # Not sure why shape returns None here. Seems to be when the
            #   robot is pressed right up against a wall, though.
            return 'w', angle, 0
Example #24
0
    def MouseDown(self, p):
        """
        Indicates that there was a left click at point p (world coordinates)
        """
        if self.mouseJoint != None:
            return

        # Make a small box.
        aabb = box2d.b2AABB()
        d = box2d.b2Vec2(0.001, 0.001)
        aabb.lowerBound = p - d
        aabb.upperBound = p + d

        # Query the world for overlapping shapes.
        body = None
        k_maxCount = 10

        (count, shapes) = self.world.Query(aabb, k_maxCount)
        for shape in shapes:
            shapeBody = shape.GetBody()
            if shapeBody.IsStatic() == False and shapeBody.GetMass() > 0.0:
                if shape.TestPoint(shapeBody.GetXForm(), p): # is it inside?
                    body = shapeBody
                    break
        
        if body:
            md = box2d.b2MouseJointDef()
            md.body1   = self.world.GetGroundBody()
            md.body2   = body
            md.target  = p
            md.maxForce= 1000.0 * body.GetMass()
            self.mouseJoint = self.world.CreateJoint(md)
            body.WakeUp()
 def handle_enter(self, parameters):
     self.next_state = parameters['next_state']
     self.next_state_parameters = parameters.setdefault('parameters', {})
     self.next_state_parameters={'totalScore':parameters['totalScore'],'edit':parameters['edit']}
     
     self.delay = parameters.setdefault('delay', 2000)
     self.time_passed = 0
     self.background = None
     self.shader = None
     self.screenFont = pygame.font.Font("data/font/fsex2p00_public.ttf", 70)
     text = u"Тоглоом дууслаа"
     self.message = self.screenFont.render(text, True, (255,255,255))
             
     bodyDef = box2d.b2BodyDef()
     bodyDef.position = (8, -2)
     bodyDef.angle = -0.5
     bodyDef.userData = self
     self.message_body = self.world.CreateBody(bodyDef)
     shapeDef = box2d.b2PolygonDef()
     shapeDef.density = 0.5
     shapeDef.friction = 0.95
     shapeDef.restitution = 0.5
     shapeDef.SetAsBox(self.message.get_width()/2.0/self.pixels_per_unit, 
                       self.message.get_height()/2.0/self.pixels_per_unit)
     self.message_body.CreateShape(shapeDef)
     self.message_body.SetMassFromShapes()
     self.message_body.SetLinearVelocity = box2d.b2Vec2(100.0,0)
Example #26
0
    def __init__(self,world,top,size):


        scenter=(top[0]+(size[0]/2),
                top[1]+(size[1]/2))
        wcenter=world.s2wPos(scenter)

        extends=world.s2wScale(size)

        #print 'top: '+str(top)
        #print 'scenter: '+str(scenter)
        #print 'wcenter: '+str(wcenter)
        #print world.w2sPos(wcenter)
        #print 'size: '+str(size)
        #print 'extends: '+str(extends)
        #print world.w2sScale(extends)


        # Physics
        walldef=Box2D.b2BodyDef()
        walldef.position=Box2D.b2Vec2(wcenter[0],wcenter[1])
        walldef.userData={}
        wallbody=world.world.CreateBody(walldef)
        wallbody.iswall=True
        wallshape=Box2D.b2PolygonDef()
        width, height = extends
        wallshape.SetAsBox(width/2, height/2)
        wallbody.CreateShape(wallshape)

        # Display
        self.image=pygame.Surface(size)
        self.image.fill((56,71,216))
        self.rect = self.image.get_rect()
        self.rect.topleft=top
Example #27
0
 def LaunchRandomBomb(self):
     """
     Create a new bomb and launch it at the testbed.
     """
     p = box2d.b2Vec2(box2d.b2Random(-15.0, 15.0), 30.0)
     v = -5.0 * p
     self.LaunchBomb(p, v)
Example #28
0
 def __init__(self, target, pos, vel, ang):
     target = Box2D.b2Vec2(target[0], target[1])
     pos = Box2D.b2Vec2(pos[0], pos[1])
     vel = Box2D.b2Vec2(vel[0], vel[1])
     self.index = 0
     DUNGEON = map2grid(WIDTH, HEIGHT)
     self.target_grid = world2grid(target)
     self.selfpos_gird = world2grid(pos)
     tic = time.time()
     #print(DUNGEON)
     path = astar(DUNGEON, WIDTH, HEIGHT, self.selfpos_gird, 0, self.target_grid)
     #print(path)
     #print("Astar: {}".format(time.time()-tic))
     self.path = pathprocess(path)
     self.tonext = 1000
     self.velocity = vel
Example #29
0
    def __init__(self, n=2, radius=0.2, frontIR=12, debug=False):
        global bDebug
        bDebug = debug
        print "-------------------------------------------------"
        self.yini = -1.2
        self.radius = radius
        world.gravity = Box2D.b2Vec2(0, -1.01)
        self.epucks = [
            Epuck(position=[-1 + 2 * i, self.yini],
                  frontIR=frontIR,
                  bHorizontal=True) for i in range(n)
        ]

        for e in self.epucks:
            e.userData["score"] = 0
            e.userData["reward"] = 0

        self.walls_dx = 7.25
        addWalls((0, 0), dx=self.walls_dx, dh=2, bHoriz=False)
        createBox((0, -2), w=7.65, h=0.2, bDynamic=False, name="floor")

        self.callback = RayCastCallback()

        self.objs = []

        self.box = None
        # self.setOcclusion()
        self.phase_names = ["Training", "Easy", "Intermmediate", "Difficult"]
Example #30
0
def hitSegment(x1, y1, x2, y2, x3, y3, x4, y4):
    """
    check if pt1, pt2, pt3, pt4 form overlapping lines
    b1: if pt is collinear with pt1, pt2
    b2: if pt is collinear with pt3, pt4
    if pt is collinear with (pt1, pt2) (pt3, pt4) at the same time, 
        pt1, 2, 3, 4 are overlapping lines
    """
    t1 = x3 - x1
    t2 = y3 - y1
    t3 = x2 - x1
    t4 = y2 - y1
    t5 = x4 - x3
    t6 = y4 - y3
    t7 = t4 * t5 - t3 * t6

    a = (t5 * t2 - t6 * t1) / t7
    px = x1 + a * t3
    py = y1 + a * t4

    b1 = isOnSegment(px, py, x1, y1, x2, y2)
    b2 = isOnSegment(px, py, x3, y3, x4, y4)

    if (b1 and b2):
        return b2.b2Vec2(px, py)

    return None
Example #31
0
	def draw(self, display):
		display.blit(self.bgimage, (0, 0))

		for body in self.world:
			if isinstance(body.userData, Entity):
				body.userData.draw(display)

		if self.ready:
			cuePos = toScreen(self.cue.body.position)
			lineStart = b2.b2Vec2(cuePos[0], cuePos[1])
			mouse = pygame.mouse.get_pos()
			mouseOffset = b2.b2Vec2(mouse[0], mouse[1]) - lineStart
			mouseOffset.Normalize()
			lineEnd = lineStart + (mouseOffset * SCREENW)
			lineStart += mouseOffset * 13
			pygame.draw.line(display, Color("white"), lineStart.tuple(), lineEnd.tuple())
Example #32
0
 def ConvertScreenToWorld(self, x, y):
     """
     Converts the display screen to the simulation's coordinates.
     """
     return b2.b2Vec2((x + self.viewOffset.x) / self.viewZoom,
                      ((self.screenSize.y - y + self.viewOffset.y)
                       / self.viewZoom))
Example #33
0
 def setCenter(self, value):
     """
     Updates the view offset based on the center of the screen.
     """
     self._viewCenter = b2.b2Vec2(*value)
     self._viewCenter *= self._viewZoom
     self._viewOffset = self._viewCenter - self.screenSize/2
Example #34
0
    def create_mouse_joint(self, x, y):
        """ create a mouse joint to the body on world coordinates x, y """
        if self.mouse_joint:
            return
        world_coord = box2d.b2Vec2(self.debugDraw.screen_to_world((x, y)))
        aabb = box2d.b2AABB()
        aabb.lowerBound = world_coord - (0.001, 0.001)
        aabb.upperBound = world_coord + (0.001, 0.001)
        max_count = 10
        count, shapes = self.world.Query(aabb, max_count)

        body = (body for shape, body in ((shape, shape.GetBody())
                                         for shape in shapes)
                if not body.IsStatic()
                and body.GetMass() > 0.0
                and shape.TestPoint(body.GetXForm(), world_coord))
        body = list(itertools.islice(body, 1))
        body = body[0] if len(body) == 1 else None
        if body:
            md = box2d.b2MouseJointDef()
            md.body1 = self.world.GetGroundBody()
            md.body2 = body
            md.target = world_coord
            md.maxForce = 1000 * body.GetMass()
            self.mouse_joint = self.world.CreateJoint(md)
            body.WakeUp()
Example #35
0
    def event_response(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.mouse_over(event.pos):
                self.dragging = not self.dragging

        elif event.type == pygame.MOUSEMOTION and self.dragging:
            self.body.position = Box2D.b2Vec2(event.pos[0], event.pos[1])
Example #36
0
    def testmoves(self):
        self.count -= 1
        if self.count < 0:
            self.force = -self.force
            self.count = 1000

        for name, robot in self.robots.items():
            r = robot.body
            pos = r.position
            vel = r.linearVelocity

            #print 'pos', pos
            #print dir(vel)

            localforce = box2d.b2Vec2(self.force, 0)
            worldforce = r.GetWorldVector(localforce)

            r.ApplyForce(worldforce, pos)

            #if r.angularVelocity < .5:
            #r.ApplyTorque(.5)
            #else:
            #print 'av', r.angle

            r.ApplyTorque(4)

            bullet = random.randrange(3)
            if bullet == 2:
                #print name, 'shoots'
                self.makebullet(name)
Example #37
0
def setB2Vec2Attr(source_dict, source_key, target_obj, target_attr=None):
    """assigns array values from dict to target object, if key exists in dict
    may take renamed attribute for object works only with built_in values

    :param source_dict: a dictionary from the json file
    :type source_dict: dict(string, variant)

    :param source_key: the key of a object within source_dict
    :type source_key: string

    :param target_obj: an object with a 'source_key' or 'target_attr'
                       attribute
    :type target_obj: variant

    :param target_attr: the attribute of the target_obj where to put
                        the object related to source_key.
                        Defaults to source_key
    :type target_attr: string
    """

    if source_key in list(source_dict.keys()):
        # setting attr name
        if target_attr is None:
            target_attr = source_key

        # preparing B2Vec
        if source_dict[source_key] == 0:
            vec2 = b2.b2Vec2(0, 0)
        else:
            vec2 = rubeVecToB2Vec2(source_dict[source_key])

        # setting obj's attr value
        setattr(target_obj, target_attr, vec2)
Example #38
0
    def __init__(self):
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World(gravity=Box2D.b2Vec2(0,0))
        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,
                )

        high = np.array([np.inf]*24)
        self.observation_space = spaces.Box(-high, high)

        self.reset()

        self.action_space = spaces.Box(
            np.array([-1]*len(self.joints)), np.array([+1]*len(self.joints)))
Example #39
0
    def __init__(self):
        EzPickle.__init__(self)
        self.seed()
        self.viewer = None
        self.world = Box2D.b2World(Box2D.b2Vec2(0, -9.8))
        self.moon = None
        self.platform = None
        self.lander = None
        self.particles = []

        self.W = VIEWPORT_W / SCALE
        self.H = VIEWPORT_H / SCALE
        self.water_level = self.H * 0.1

        self.helipad_x1 = (self.W - (PLATFORM_WIDTH - 4) / SCALE) / 2
        self.helipad_x2 = (self.W + (PLATFORM_WIDTH - 4) / SCALE) / 2

        self.prev_reward = None

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

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

        self.reset()
Example #40
0
    def makeping(self, rname, rnd):
        robot = self.robots[rname]
        body = robot.turret

        segmentLength = 65.0

        blocalpos = box2d.b2Vec2(1.12, 0)

        segment = box2d.b2Segment()
        laserStart = (1.12, 0)
        laserDir = (segmentLength, 0.0)
        segment.p1 = body.GetWorldPoint(laserStart)
        segment.p2 = body.GetWorldVector(laserDir)
        segment.p2+=segment.p1

        lambda_, normal, shape = self.w.RaycastOne(segment, False, None)
        hitp = (1 - lambda_) * segment.p1 + lambda_ * segment.p2
        angle = robot.get_turretangle()
        dist = box2d.b2Distance(segment.p1, hitp)

        if shape is not None:
            hitbody = shape.GetBody()
            kind = hitbody.userData['kind']
            if kind == 'robot':
                actor = hitbody.userData['actor']
                if actor._pinged != rnd - 1:
                    actor._pinged = rnd
            return kind, angle, dist
        else:
            # Not sure why shape returns None here. Seems to be when the
            #   robot is pressed right up against a wall, though.
            return 'w', angle, 0
Example #41
0
 def ConvertScreenToWorld(self, x, y):
     """
     Return a b2Vec2 in world coordinates of the passed in screen coordinates x, y
     """
     return box2d.b2Vec2(
         (x + self.viewOffset.x) / self.viewZoom,
         ((self.screenSize.y - y + self.viewOffset.y) / self.viewZoom))
Example #42
0
    def testmoves(self):
        self.count -= 1
        if self.count < 0:
            self.force = -self.force
            self.count = 1000

        for name, robot in self.robots.items():
            r = robot.body
            pos = r.position
            vel = r.linearVelocity

            #print 'pos', pos
            #print dir(vel)

            localforce = box2d.b2Vec2(self.force, 0)
            worldforce = r.GetWorldVector(localforce)

            r.ApplyForce(worldforce, pos)

            #if r.angularVelocity < .5:
                #r.ApplyTorque(.5)
            #else:
                #print 'av', r.angle

            r.ApplyTorque(4)

            bullet = random.randrange(3)
            if bullet == 2:
                #print name, 'shoots'
                self.makebullet(name)
Example #43
0
    def __init__(self):
        EzPickle.__init__(self)
        self.seed()
        self.viewer = None

        self.world = Box2D.b2World(Box2D.b2Vec2(0, -1.6))
        self.moon = None
        self.lander = None
        self.particles = []

        self.prev_reward = None

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

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

        self.reset()
def rubeVecArrToB2Vec2Arr(vector_array):
    """
    # converter from rube json vector array to b2Vec2 array
    """
    return [
        b2.b2Vec2(x, y) for x, y in zip(vector_array["x"], vector_array["y"])
    ]
Example #45
0
 def drawPolygon(self, body, color, shape=None):
     verts =[] 
     for x, y  in body.shapeList[0].asPolygon().getCoreVertices_tuple():
         v= body.GetWorldPoint(box2d.b2Vec2(x, y))
         verts.append((v.x*WorldConfig.WINDOW_PER_WORLD, v.y*WorldConfig.WINDOW_PER_WORLD))
                             
     Game.renderer.drawPolygon(verts, color, shape)
Example #46
0
 def ConvertScreenToWorld(self, x, y):
     """
     Return a b2Vec2 in world coordinates of the passed in screen coordinates x, y
     """
     return box2d.b2Vec2(
         (x + self.viewOffset.x) / self.viewZoom, ((self.screenSize.y - y + self.viewOffset.y) / self.viewZoom)
     )
    def createExplosion(self):
        globals.sounds.explosion.play()
        self.startOfExplosion = globals.time
        self.exploding = True
        self.quad.Disable()

        self.getExplosionPosition()
        self.explosion_quad.SetVertices(self.explosion_bl, self.explosion_tr, drawing.constants.DrawLevels.ui)
        self.explosion_quad.Enable()

        #check for damage to some mans
        for troop in itertools.chain(globals.game_view.game_world.goodies, globals.game_view.game_world.baddies):
            explosionRange = 50
            explosionRange = math.pow(50, 2)
            explosionDamage = 200

            troopCenter = Point(troop.body.GetWorldCenter()[0] / globals.physics.scale_factor, troop.body.GetWorldCenter()[1] / globals.physics.scale_factor)
            explosionCenter = Point(self.body.GetWorldCenter()[0] / globals.physics.scale_factor, self.body.GetWorldCenter()[1] / globals.physics.scale_factor)
            distance = (troopCenter - explosionCenter).SquareLength()


            if(distance < explosionRange):
                troop.TakeDamage(explosionDamage * distance/explosionRange)

                impulseToApply = troopCenter - explosionCenter
                impulseToApply = impulseToApply.Normalize()
                impulseToApply *= Point(40, 40)
                impulse = box2d.b2Vec2(impulseToApply[0], impulseToApply[1])
                troop.locked_planet = None
                troop.body.ApplyImpulse(impulse, troop.body.GetWorldCenter())
Example #48
0
 def ConvertScreenToWorld(self, x, y):
     """
     Converts the display screen to the simulation's coordinates.
     """
     return b2.b2Vec2((x + self.viewOffset.x) / self.viewZoom,
                      ((self.screenSize.y - y + self.viewOffset.y)
                       / self.viewZoom))
 def LaunchRandomBomb(self):
     """
     Create a new bomb and launch it at the testbed.
     """
     p = box2d.b2Vec2( box2d.b2Random(-15.0, 15.0), 30.0 )
     v = -5.0 * p
     self.LaunchBomb(p, v)
Example #50
0
    def testmoves(self):
        self.count -= 1
        if self.count < 0:
            self.force = -self.force
            self.count = 1000

        for name, tank in self.tanks.items():
            r = tank.body
            pos = r.position
            vel = r.linearVelocity

            
            

            localforce = box2d.b2Vec2(self.force, 0)
            worldforce = r.GetWorldVector(localforce)

            r.ApplyForce(worldforce, pos)

            
                
            
                

            r.ApplyTorque(4)

            bullet = random.randrange(3)
            if bullet == 2:
                
                self.makebullet(name)
Example #51
0
 def setCenter(self, value):
     """
     Updates the view offset based on the center of the screen.
     """
     self._viewCenter = b2.b2Vec2(*value)
     self._viewCenter *= self._viewZoom
     self._viewOffset = self._viewCenter - self.screenSize/2
Example #52
0
    def makeping(self, rname, rnd):
        tank = self.tanks[rname]
        body = tank.turret

        segmentLength = 65.0

        blocalpos = box2d.b2Vec2(1.12, 0)

        segment = box2d.b2Segment()
        laserStart = (1.12, 0)
        laserDir = (segmentLength, 0.0)
        segment.p1 = body.GetWorldPoint(laserStart)
        segment.p2 = body.GetWorldVector(laserDir)
        segment.p2+=segment.p1

        lambda_, normal, shape = self.w.RaycastOne(segment, False, None)
        hitp = (1 - lambda_) * segment.p1 + lambda_ * segment.p2
        angle = tank.get_turretangle()
        dist = box2d.b2Distance(segment.p1, hitp)

        if shape is not None:
            hitbody = shape.GetBody()
            kind = hitbody.userData['kind']
            if kind == 'tank':
                actor = hitbody.userData['actor']
                if actor._pinged != rnd - 1:
                    actor._pinged = rnd
            return kind, angle, dist
        else:
            
            
            return 'w', angle, 0
Example #53
0
	def walk(self):
		self.screenPosition = constants.world2Screen(self.physicsBody.position)
		if (len(self.path) > 0):
			self.moving = True
			targetPos = self.convertPathToScreenCoord(self.path[0].x, self.path[0].y)
			xd = targetPos[0] - self.screenPosition[0]
			yd = targetPos[1] - self.screenPosition[1]
			if (abs(xd) <= 7.1 and abs(yd) <= 7.1):
				self.path.pop(0)
				if len(self.path) == 0:
					self.taskList.startDoingTask()

			self.direction = Box2D.b2Vec2([
				(targetPos[0] - self.screenPosition[0]),
				(targetPos[1] - self.screenPosition[1])])
			self.direction.Normalize()
			movement = [self.direction[0] * constants.VICTIM_SPEED_REGULAR * 0.8, -self.direction[1] * constants.VICTIM_SPEED_REGULAR * 0.8]
			self.physicsBody.ApplyLinearImpulse(movement, self.physicsBody.position, True)

		elif self.taskList.done:
			if True:#not self.seenPlayer:
				goal = self.taskList.getRandomTask().screenPos
				self.setWaypoint(goal)

			else:
				pass
				#Panic mode
		else:
			self.taskList.update()
Example #54
0
    def MoveTo(self, pos, vel, ang, action):
        pos = Box2D.b2Vec2(pos[0], pos[1])
        vel = Box2D.b2Vec2(vel[0], vel[1])
        selfpos = pos
        self.velocity = vel
        if self.index  < self.path.__len__():
            nexttarget = grid2world(self.path[self.index])
            self.tonext = self.dist(selfpos, nexttarget)
            #print(self.tonext)
            if self.tonext < 1.414 * MINBIAS:
                self.index += 1
                action[0] = +0.0
                action[2] = +0.0
            else:
                action = self.MoveSubTo(nexttarget, selfpos, self.velocity, ang, action)

        return action
Example #55
0
    def draw(self, display):
        display.blit(self.bgimage, (0, 0))

        for body in self.world:
            if isinstance(body.userData, Entity):
                body.userData.draw(display)

        if self.ready:
            cuePos = toScreen(self.cue.body.position)
            lineStart = b2.b2Vec2(cuePos[0], cuePos[1])
            mouse = pygame.mouse.get_pos()
            mouseOffset = b2.b2Vec2(mouse[0], mouse[1]) - lineStart
            mouseOffset.Normalize()
            lineEnd = lineStart + (mouseOffset * SCREENW)
            lineStart += mouseOffset * 13
            pygame.draw.line(display, Color("white"), lineStart.tuple(),
                             lineEnd.tuple())
Example #56
0
 def to_b2vec(self, pt):
     # Convert vector to a b2vect
     pt = self.parent.to_world(pt)
     ptx, pty = pt
     ptx /= self.parent.ppm
     pty /= self.parent.ppm
     pt = box2d.b2Vec2(ptx, pty)
     return pt
Example #57
0
 def on_mousedown(self, pos):
     if not self.ready: return
     worldMouse = b2.b2Vec2(pos[0] / fPPM - 2, pos[1] / fPPM - 2)
     #Pocket(self.world, worldMouse.x, worldMouse.y)
     offset = worldMouse - self.cue.body.position
     offset.Normalize()
     self.cue.hit(offset * 10)
     self.ready = False