Beispiel #1
0
    def __init__(self):
        self.viewZoom = 10.
        self.viewCenter = b2Vec2(0., 0.)
        self.viewOffset = b2Vec2(0., 0.)
        self.flipY = True
        self.screenSize = b2Vec2(*screenXY)

        self.pointSize = 10.

        self.colors = {
            'grey1': (150, 150, 150),
            'grey2': (200, 200, 200),
            'force_point': (0, 255, 0)
        }

        self.colorsbt = {
            b2_dynamicBody: (255, 255, 255, 255),
            b2_staticBody: (127, 127, 127, 255),
        }
        os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (200, 50)
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0,
                                              32)
        #self.imgFragile = pygame.image.load('fragile.bmp')
        self.imgFragile = pygame.transform.scale(
            pygame.image.load('pics/fragile.bmp'), imSize)
        self.imgHeavy = pygame.transform.scale(
            pygame.image.load('pics/heavy.bmp'), imSize)
        self.imgBoom = pygame.transform.scale(
            pygame.image.load('pics/boom.bmp'), imSize)
Beispiel #2
0
    def Step(self, settings):
        super(EdgeShapes, self).Step(settings)

        # Set up the raycast line
        length = 25.0
        point1 = b2Vec2(0, 10)
        d = (length * cos(self.angle), length * sin(self.angle))
        point2 = point1 + d

        callback = self.callback
        callback.fixture = None

        self.world.RayCast(callback, point1, point2)

        # The callback has been called by this point, and if a fixture was hit it will have been
        # set to callback.fixture.
        point1 = self.renderer.to_screen(point1)
        point2 = self.renderer.to_screen(point2)
        if callback.fixture:
            cb_point = self.renderer.to_screen(callback.point)
            self.renderer.DrawPoint(cb_point, 5.0, self.p1_color)
            self.renderer.DrawSegment(point1, cb_point, self.s1_color)

            head = b2Vec2(cb_point) + 0.5 * callback.normal
            self.renderer.DrawSegment(cb_point, head, self.s2_color)
        else:
            self.renderer.DrawSegment(point1, point2, self.s1_color)

        if not settings.pause or settings.singleStep:
            self.angle += 0.25 * b2_pi / 180
Beispiel #3
0
def xml_2_b2bodies(world: b2World, xmlStr):
    tree = ET.ElementTree(ET.fromstring(xmlStr))
    for body in tree.getroot().findall("body"):
        id = int(body.attrib["index"])
        type = body.attrib["type"]
        p = body.find("position")
        px, py = float(p.attrib['x']), float(p.attrib['y'])
        v = body.find("velocity")
        vx, vy = float(v.attrib['vx']), float(v.attrib['vy'])
        shape = body.find("shape").attrib['value']
        spin = float(body.find("spin").attrib['omega'])
        mass = float(body.find("mass").attrib['value'])
        orientation = float(body.find("orientation").attrib['theta'])
        inertia = float(body.find("inertia").attrib['value'])

        if type == "free":
            bod = world.CreateDynamicBody(
                position=b2Vec2(px, py),
                fixtures=eval(shape).fixture,
            )
        elif type == "fixed":
            bod = world.CreateStaticBody(
                position=b2Vec2(px, py),
                fixtures=eval(shape).fixture,
            )

        bod.userData = BodyData(b_id=id, shape=shape)
        bod.mass = mass
        bod.inertia = inertia
        bod.linearVelocity = b2Vec2(vx, vy)
        bod.angle = orientation
        bod.angularVelocity = spin
Beispiel #4
0
def copyWorld(world):
    copy = b2World(gravity=world.gravity, doSleep=world.allowSleeping)

    copy.continuousPhysics = world.continuousPhysics

    copy.velocityThreshold = world.velocityThreshold
    copy.positionThreshold = world.positionThreshold

    for body in world.bodies:
        fixtures = []
        for fixture in body.fixtures:
            fixtures.append(
                b2FixtureDef(shape=fixture.shape,
                             density=fixture.density,
                             restitution=fixture.restitution,
                             friction=fixture.friction))

        copy.CreateBody(type=body.type,
                        fixtures=fixtures,
                        userData=body.userData,
                        position=b2Vec2(body.position.x, body.position.y),
                        angle=body.angle,
                        linearVelocity=b2Vec2(body.linearVelocity.x,
                                              body.linearVelocity.y),
                        angularVelocity=body.angularVelocity)

    for body in copy.bodies:
        body.sleepingAllowed = False

    return copy
Beispiel #5
0
 def __createEnemies(self):
     enemies = json.loads(self.mEnemyData)
     
     if len(enemies) > 0:
         for e in range(len(enemies)):
             x, y = [float(i) for i in enemies[e]["POS"].split(",")]
             etype = enemies[e]["TYPE"]
             
             if etype == EnemyType.SPIKEBOX:
                 speed = float(enemies[e]["SPEED"])
                 delay = float(enemies[e]["DELAY"])
                 ex, ey = [float(i) for i in enemies[e]["ENDPOS"].split(",")]
                 self.mEnemies.append(SpikeBox(self.mWorld, (x,y), (ex, ey), delay, speed))
             elif etype == EnemyType.SPIKE:
                 facing = int(enemies[e]["FACING"])
                 self.mEnemies.append(Spike(self.mWorld, (x,y), facing))
             elif etype == EnemyType.SAW:
                 pattern = [(k, v) for k,v in (str(enemies[e]["PATTERN"][x]).split(",") for x in range(len(enemies[e]["PATTERN"])))]
                 speed = float(enemies[e]["SPEED"])
                 radius = float(enemies[e]["RADIUS"])
                 self.mEnemies.append(Saw(self.mWorld, (x,y), pattern, radius, speed))
             elif etype == EnemyType.LASER:
                 ex, ey = [float(i) for i in enemies[e]["ENDPOS"].split(",")]
                 delay = float(enemies[e]["DELAY"])
                 triggertime = float(enemies[e]["T_TIMER"])
                 firingtime = float(enemies[e]["F_TIMER"])
                 self.mEnemies.append(Laser(self.mWorld, b2Vec2(x,y), b2Vec2(ex,ey), delay, triggertime, firingtime))
Beispiel #6
0
def on_mouse_press(x, y, button, modifiers):
    """Fire in the hole!"""
    angle = math.radians(barrel_angle)
    v = b2Vec2(math.cos(angle), math.sin(angle))
    pos = tank_pos + b2Vec2(0, 2) + v * 3
    Cannonball.fire(pos, v * 100)
    muzzle_sound.play()
Beispiel #7
0
 def render(self, delta):
     Pgl.app.surface.fill((67,80,129))
     Pgl.app.surface.blit(self.title, (self.titlepos.x - self.size[0] / 2.0, self.titlepos.y - self.size[1] / 2.0))
     
     #buttons
     self.menubutton.setSize(self.mCamera.getScaledSize(self.mButtonTable.mButtonSize.x, self.mButtonTable.mButtonSize.y))
     for btn in self.mButtonTable.mButtons:
         viewpos = self.mCamera.getViewCoords(b2Vec2(btn.x, btn.y))
         
         color = None
         if btn.mActive:
             self.menubutton.freeze(1, 0)
             color = (255,255,255)
         else:
             self.menubutton.freeze(0, 0)
             color = (141,60,1)
         self.menubutton.draw(delta, viewpos)
     
         btntxt = self.screenFont.render(str(btn.mText), 0, color)
         size = self.screenFont.size(str(btn.mText))
         txtpos = self.mCamera.getViewCoords(b2Vec2(btn.x + btn.size.x / 2 - (size[0] / self.mCamera.scale.x) / 2.0, 
                                                    btn.y + btn.size.y / 2 - (size[1] / self.mCamera.scale.y) / 2.0))
         Pgl.app.surface.blit(btntxt, (txtpos.x, txtpos.y))
         
     self.arrow.draw()
Beispiel #8
0
def make_semicircle(n, offset):
    vertices = [b2Vec2(0,0)]
    for i in range(n+1):
        angle = radians(offset + i * 90.0 / n)
        vertex = b2Vec2(POCKET_RADIUS * cos(angle), POCKET_RADIUS * sin(angle))
        vertices.append(vertex)
    return vertices
    def __init__(self, settings):
        super(PygletFramework, self).__init__()
        self.settings = settings  # TODO: should settings be in fwbase instead?
        self.__reset()
        self.env = None

        if self.settings.onlyInit:  # testing mode doesn't initialize Pyglet
            return

        print('Initializing Pyglet framework...')
        self.window = PygletWindow(self)
        self.window.set_location(100, 100)
        self.window.width = 1280
        self.window.height = 960

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

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

        self.renderer = PygletDraw(self)
        self.renderer.static_batch = pyglet.graphics.Batch()
        self.renderer.surface = self.window.screen
        self.world.renderer = self.renderer
        self._viewCenter = b2Vec2(0, 0)
        self._viewZoom = 2
        # self.groundbody = self.world.CreateBody()
        self.gui_objects = {}
Beispiel #10
0
    def __init__(self, game):
        super(EndScreen, self).__init__(game, False)
        SoundManager.getInstance().playEndMusic()

        #fonts
        self.textFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x * 0.6)
        self.headerFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x)
        self.titleFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x * 2.0)

        self.modelsize = self.mCamera.getModelCoords(b2Vec2(Pgl.width, Pgl.height))
        self.mDone = False
        self.mTimer = 0

        texts = [
                 [self.titleFont, (200,160,160), "pxlgrvty", 0],
                 [self.headerFont, (170,170,170), "Programming:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Graphics:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Audio/FX:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Music:", 25],
                 [self.textFont, (255,255,255), "anamanaguchi - helix nebula", 0],
                 [self.textFont, (255,255,255), "anamanaguchi - video challenge", 0],
                 [self.textFont, (255,255,255), "electric children - spring retrospective", 0],
                 [self.textFont, (255,255,255), "teknoaxe - chiptune does dubstep", 0],
                 [self.textFont, (255,255,255), "roccow - chipho instrumental", 0],
                 [self.textFont, (255,255,255), "sycamore drive - kicks", 0]]

        self.titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y))
        self.text = Text(texts, self.titlepos, 1, Pgl.app.surface)
        self.endtext = self.headerFont.render("thanks for playing!", 1, (170,170,170))
        self.endsize = self.headerFont.size("thanks for playeing!")
        self.endpos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x/2.0, self.modelsize.y/2.0))
Beispiel #11
0
 def render(self, delta):
     Pgl.app.surface.fill((67,80,129)) 
     Pgl.app.surface.blit(self.title, (self.titlepos.x - self.size[0] / 2.0, self.titlepos.y - self.size[1] / 2.0))
      
     btnToDraw = self.levelbutton
     for btn in self.mLevelTable.mLevelButtons:
         if isinstance(btn, Button):
             btnToDraw = self.menubutton
         viewpos = self.mCamera.getViewCoords(b2Vec2(btn.x, btn.y))
         btnToDraw.setSize(self.mCamera.getScaledSize(btn.size.x, btn.size.y))
         
         color = None
         if btn.mActive:
             btnToDraw.freeze(1, 0)
             color = (255,255,255)
         else:
             btnToDraw.freeze(0, 0)
             color = (141,60,1)
             
         btnToDraw.draw(delta, viewpos)
         
         #check if level is locked
         if isinstance(btn, LevelButton):
             if btn.mLocked:
                 lockpos = self.mCamera.getViewCoords(b2Vec2(btn.x + self.mLevelTable.mButtonSize.x / 1.5, btn.y + self.mLevelTable.mButtonSize.y / 1.5))
                 self.lock.draw(lockpos)
         
         btntxt = self.screenFont.render(str(btn.mText), 0, color)
         size = self.screenFont.size(str(btn.mText))
         txtpos = self.mCamera.getViewCoords(b2Vec2(btn.x + btn.size.x / 2 - (size[0] / self.mCamera.scale.x) / 2.0, btn.y + btn.size.y / 2 - (size[1] / self.mCamera.scale.y) / 2.0))
         Pgl.app.surface.blit(btntxt, (txtpos.x, txtpos.y))
         self.arrow.draw()
Beispiel #12
0
 def __init__(self, physworld, pos, movepattern, radius, speed):
     self.__mTarget = b2Vec2(0,0)
     self.__mCurrent = len(movepattern)-1
     self.__mPattern = movepattern
     self.__mSpeed = speed
     super(Saw, self).__init__(physworld, pos, b2Vec2(radius, radius), EnemyShape.CIRCLE, self)
     self.calculateTarget()
Beispiel #13
0
    def __init__(self):
        super(Confined, self).__init__()
        self.name = "Stacked balls falling"
        xlow, xhi = -20, 20
        ylow, yhi = 0, 40

        # The ground
        ground = create_fixed_box(self.world,
                                  p_ll=b2Vec2(xlow, ylow),
                                  p_hr=b2Vec2(xhi, yhi))

        # The bodies
        radius = 1
        columnCount = 5
        rowCount = 5

        for j in range(columnCount):
            for i in range(rowCount):
                create_circle(self.world,
                              (-10 + (2.1 * j + 1 + 0.01 * i) * radius,
                               (2 * i + 1) * radius), radius)

        self.world.gravity = (0, -9.81)

        b_ix = -1
        for b in self.world.bodies:
            b_ix += 1
            b.userData.id = b_ix
Beispiel #14
0
    def add_agent(self, y, x):
        self.agent_init_position = (x, y)

        agent_vertices = [(0.5 - self.agent_radius, 0.5 - self.agent_radius),
                          (0.5 - self.agent_radius, 0.5 + self.agent_radius),
                          (0.5 + self.agent_radius, 0.5 + self.agent_radius),
                          (0.5 + self.agent_radius, 0.5 - self.agent_radius)]
        agent_fixture = b2FixtureDef(
            shape=b2PolygonShape(vertices=agent_vertices),
            friction=0.4,
            restitution=0.3,
        )
        self.agent_body = self.world.CreateDynamicBody(
            position=(x, y),
            fixtures=agent_fixture,
            fixedRotation=True,
        )

        visual_radius = 1.5 * self.agent_radius
        agent_vertices_visual = [(0.5 - visual_radius, 0.5 - visual_radius),
                                 (0.5 - visual_radius, 0.5 + visual_radius),
                                 (0.5 + visual_radius, 0.5 + visual_radius),
                                 (0.5 + visual_radius, 0.5 - visual_radius)]
        drawing_util.add_polygon(self.display_objects,
                                 self.agent_body,
                                 agent_vertices_visual,
                                 'agent',
                                 drawing_layer=5,
                                 color=self.agent_color)

        self.position_indicator = drawing_util.DummyBody(b2Vec2(x, y), angle=0)
        self.target_indicator = drawing_util.DummyBody(b2Vec2(x, y), angle=0)
    def laser(self):
        self.laserPoints = []
        self.laserImpactPoints = []
        self.laserImpactDistances = []

        for laserDegree in self.laserDegrees:
            degrees = laserDegree + self.carOrientation - (b2_pi / 2.0) + b2_pi

            # print("laserDegree", laserDegree, degrees, self.carOrientation)

            laserPointX = self.carCenter.x + self.laserRadius * math.cos(
                degrees)
            laserPointY = self.carCenter.y + self.laserRadius * math.sin(
                degrees)

            laserPoint = b2Vec2(laserPointX, laserPointY)

            self.laserPoints.append(laserPoint)

            callback = RayCastMultipleCallback()

            self.world.RayCast(callback, self.carCenter, laserPoint)

            callbackPoints = [b2Vec2(self.laserRadius, self.laserRadius)]
            callbackFixtures = []

            if callback.hit:
                callbackPoints = callback.points
                callbackFixtures = callback.fixtures

            self.calcLaserDistances(laserDegree, callbackPoints,
                                    callbackFixtures)
Beispiel #16
0
    def CreateBody(self, world, TILE_SIZE):
        pos = b2Vec2(self.pos.x * TILE_SIZE, -self.pos.y * TILE_SIZE)
        dim = b2Vec2(self.dim.w * TILE_SIZE, self.dim.h * TILE_SIZE)
        bodyDef = b2BodyDef()
        bodyDef.type = b2_staticBody
        bodyDef.userData = self
        bodyDef.position = pos
        body = world.CreateBody(bodyDef)
        fixture = None
        if (self.name == "building"):
            dim.x /= 2.0
            dim.y /= 2.0
            pos.x += self.dim.w * TILE_SIZE / 2.0
            pos.y -= self.dim.h * TILE_SIZE / 2.0
            body.position = pos
            polygonShape = b2PolygonShape()
            polygonShape.SetAsBox(dim.x, dim.y)
            fixture = body.CreateFixture(shape=polygonShape)
        elif (self.name == "pickup"):
            circleShape = b2CircleShape()
            circleShape.radius = dim.x
            fixtureDef = b2FixtureDef()
            fixtureDef.shape = circleShape
            fixtureDef.isSensor = True
            fixture = body.CreateFixture(fixtureDef)
            self.done = False

        fixture.userData = self
        body.userData = self
        self.m_body = body
        return body
Beispiel #17
0
    def Step(self, settings):
        super(EdgeShapes, self).Step(settings)

        # Set up the raycast line
        length = 25.0
        point1 = b2Vec2(0, 10)
        d = (length * cos(self.angle), length * sin(self.angle))
        point2 = point1 + d

        callback = self.callback
        callback.fixture = None

        self.world.RayCast(callback, point1, point2)

        # The callback has been called by this point, and if a fixture was hit it will have been
        # set to callback.fixture.
        point1 = self.renderer.to_screen(point1)
        point2 = self.renderer.to_screen(point2)
        if callback.fixture:
            cb_point = self.renderer.to_screen(callback.point)
            self.renderer.DrawPoint(cb_point, 5.0, self.p1_color)
            self.renderer.DrawSegment(point1, cb_point, self.s1_color)

            head = b2Vec2(cb_point) + 0.5 * callback.normal
            self.renderer.DrawSegment(cb_point, head, self.s2_color)
        else:
            self.renderer.DrawSegment(point1, point2, self.s1_color)

        if not settings.pause or settings.singleStep:
            self.angle += 0.25 * b2_pi / 180
Beispiel #18
0
    def __initializeFromGame(self):
        if self.mLevelInt < Level.Level.countLevels():
            self.mButtons.append(Button("next", 13.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.GameScreen.GameScreen(self.mGame, self.mLevelInt+1))))
        else:
            self.mButtons.append(Button("end", 13.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.EndScreen.EndScreen(self.mGame))))

        self.mButtons.append(Button("retry", 11, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.GameScreen.GameScreen(self.mGame, self.mLevelInt))))

        if self.mCurrentTime.isFaster(self.mTime):
            self.mTime = self.mCurrentTime
            found = False

            data = None
            try:
                with open(Resources.getInstance().resource_path("assets/state/time.json"), "rb") as readstate:
                    decryptedData = self.__mCrypt.decrypt(readstate.read())
                    data = json.loads(decryptedData)

                    for time in data:
                        if time["ID"] == str(self.mLevelInt):
                            found = True
                            time["TIME"] = self.mCurrentTime.toString()

                    if not found:
                        data.append({"ID":"%s" % str(self.mLevelInt), "TIME":"%s" % self.mCurrentTime.toString()})
            except Exception:
                pass

            if data == None:
                data = '[{"ID":"%s", "TIME":"%s"}]' % (str(self.mLevelInt), self.mCurrentTime.toString())

            with open(Resources.getInstance().resource_path("assets/state/time.json"), "wb+") as writestate:
                writestate.write(self.__mCrypt.encrypt(json.dumps(data)))
Beispiel #19
0
    def __init__(self, position, world, gravity):
        self.mWorld = world
        self.mGravity = gravity
        pos = b2Vec2(position[0] + self.BOX_WIDTH/2, position[1] + self.BOX_HEIGHT/2)

        #create box physicsbody
        body = world.CreateDynamicBody(position = pos)
        shape = b2PolygonShape()
        fd = b2FixtureDef()
        fd.shape = shape
        fd.isSensor = True

        #gravitysensor
        shape.SetAsBox(0.1,0.1)
        fd.userData = Sensor.GRAVITYZONESENSOR
        body.CreateFixture(fd)

        #collisionbody
        body.CreatePolygonFixture(box=(self.BOX_WIDTH/2, self.BOX_HEIGHT/2), density=6, friction=0)

        body.fixedRotation = True
        body.bullet = True
        body.allowSleep = False
        body.mass = 2
        body.userData = self

        super(Box, self).__init__(pos, b2Vec2(self.BOX_WIDTH, self.BOX_HEIGHT), body, b2Vec2(0,0), 0, b2Vec2(0,0))
Beispiel #20
0
 def __init__(self, position, physworld):
     random.seed(position[0] + position[1])
     self.__mDelay = random.uniform(0.5, 1.5)
     self.__mDirection = b2Vec2(0, 1 if random.randint(0,1) == 0 else -1)
     self.__mMoveTimer = 1.0
     self.__mVelocity = 0.1
     self.mPosition = b2Vec2(position[0] + 0.5, position[1] + 0.5) 
     super(Crystal, self).__init__(self.mPosition, physworld, self.__SIZE, self)
Beispiel #21
0
 def __init__(self, physworld, startpos, endpos, delay, speed):
     self.mSpeed = speed
     self.__mStartPos = b2Vec2(startpos[0] + 0.5, startpos[1] + 0.5) 
     self.__mEndPos = b2Vec2(endpos[0] + 0.5, endpos[1] + 0.5)
     self.__mTarget = self.__mEndPos.copy()
     self.__mDelay = delay
     super(SpikeBox, self).__init__(physworld, self.__mStartPos, self.__SIZE, EnemyShape.POLYGON, self)
     self.__mLength = (self.__mTarget.copy() - self.mBody.position.copy()).length
Beispiel #22
0
    def ReportFixture(self, fixture, point, normal, fraction):
        from Box2D import b2Vec2

        self.hit = True
        self.fixture = fixture
        self.fixtures.append(fixture)
        self.points.append(b2Vec2(point))
        self.normals.append(b2Vec2(normal))
        return 1.0
Beispiel #23
0
 def __calculateMedallion(self):
     if self.mTime.isFaster(self.mLevelTimes[0]):
         return b2Vec2(0,0)
     elif self.mTime.isFaster(self.mLevelTimes[1]):
         return b2Vec2(1,0)
     elif self.mTime.isFaster(self.mLevelTimes[2]):
         return b2Vec2(2,0)
     else:
         return b2Vec2(0,2)
Beispiel #24
0
    def ReportFixture(self, fixture, point, normal, fraction):
        self.fixture = fixture
        self.point = b2Vec2(point)
        self.normal = b2Vec2(normal)
        self.hit = True # flag to inform raycast hit an object
        self.fraction = fraction
        # You will get this error: "TypeError: Swig director type mismatch in output value of type 'float32'"
        # without returning a value

        return fraction
Beispiel #25
0
    def __init__(self, game):
        super(InstructionScreen, self).__init__(game)
        self.__mMenuItems = []
        self.__mMenuItems.append(Button("back", 0.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.MenuScreen.MenuScreen(self.mGame))))

        self.__crystalPos = b2Vec2(9.5,5.8)
        self.__crystalDirection = b2Vec2(0,1)
        self.__crystalBlingTimer = 4.0
        self.__crystalTimer = 1.0
        self.crystal = Animation(Resources.getInstance().mCrystal, 5, 1, 0.6, self.mCamera.getScaledSize(0.6,0.6), False, True)

        self.portal = Animation(Resources.getInstance().mSwirlSheet, 3, 2, 0.6, self.mCamera.getScaledSize(1.5,1.5), False, True)

        self.__walkPos = b2Vec2(1,3)
        self.__walkTimer = 2.0
        self.__walkDirection = b2Vec2(1,0)
        self.playerWalk = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), True, True)

        self.__jumpPos = b2Vec2(9.5,3)
        self.__jumpStartPos = self.__jumpPos.copy()
        self.__jumpTimer = 0.5
        self.__jumpWaitTimer = 0.2
        self.__jumpDirection = b2Vec2(0,-1)
        self.playerjump = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), False, False)

        self.__gravityPos = b2Vec2(3, 6)
        self.__gravityTimer = 1.0
        self.__gravityDirection = b2Vec2(0,-1)
        self.playergravity = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), False, False)
Beispiel #26
0
 def update_agent_position(self, update_step):
     agent_position = self.agent_target_pair[0].position
     f_x = update_step[0].item()
     f_y = update_step[1].item()
     applied_force = b2Vec2(f_x, f_y)
     self.agent_target_pair[0].ApplyLinearImpulse(impulse=applied_force,
                                                  point=b2Vec2(
                                                      agent_position[0],
                                                      agent_position[1]),
                                                  wake=True)
     self.is_update_required = True
Beispiel #27
0
 def __init__(self, game):
     super(LevelScreen, self).__init__(game)
     
     #levels
     self.mLevelTable = LevelTableCreator(self.modelsize, 4, self.countLevels(), lambda x: self.mGame.setScreen(LevelTimeScreen.LevelTimeScreen(self.mGame, x)))
     self.mLevelTable.mLevelButtons.append(Button("back", 0.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(MenuScreen.MenuScreen(self.mGame))))
     
     #header
     self.title = self.titleFont.render("choose level", 0, (255,255,255))
     self.size = self.titleFont.size("choose level")
     self.titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y / 6))
    def apply_wrench(self, rlvel=(0, 0), ravel=0):

        avel = self.hand.angularVelocity
        delta_avel = ravel - avel
        torque = self.hand.mass * delta_avel * 30.0
        self.hand.ApplyTorque(torque, wake=True)

        lvel = self.hand.linearVelocity
        delta_lvel = b2Vec2(rlvel) - b2Vec2(lvel)
        force = self.hand.mass * delta_lvel * self.forceunit
        self.hand.ApplyForce(force, self.hand.position, wake=True)
Beispiel #29
0
    def __init__(self, text, x, y, choicelist, standardchoice, pointer):
        self.mChoices = choicelist
        self.__mCurrent = standardchoice
        self.mWidgedItems = []

        buttonsize = 0.5
        self.mChoiceLabel = Label(self.mChoices[self.__mCurrent], x + 1, y + buttonsize / 2.0)
        self.mWidgedItems.append(Label(text, x, y - buttonsize / 2.0))
        self.mWidgedItems.append(Button("-", x, y, b2Vec2(buttonsize, buttonsize), lambda:self.prev(pointer)))
        self.mWidgedItems.append(Button("+", x + 2, y, b2Vec2(buttonsize, buttonsize), lambda:self.next(pointer)))
        self.mWidgedItems.append(self.mChoiceLabel)
Beispiel #30
0
    def __init__(self, text, x, y, baseamount, pointer, funclist = None):
        self.mVolumeItems = []
        self.amount = baseamount
        self.x, self.y = x, y

        buttonsize = 0.5
        self.mVolumeLabel = Label(str(self.amount) + "%", x + 1, y + buttonsize / 2.0)
        self.mVolumeItems.append(Label(text, x, y - buttonsize / 2.0))
        self.mVolumeItems.append(Button("-", x, y, b2Vec2(buttonsize, buttonsize), lambda:self.lower(pointer, funclist)))
        self.mVolumeItems.append(Button("+", x + 2, y, b2Vec2(buttonsize, buttonsize), lambda:self.higher(pointer, funclist)))
        self.mVolumeItems.append(self.mVolumeLabel)
Beispiel #31
0
 def __init__(self, physworld, gravity, pos):
     self.mWorld = physworld
     self.__mParticles = []
     
     for x in range(self.__mNrOfParticles):
         rs = random.uniform(0.03, 0.12)
         particle = Particle(physworld, -gravity/4.0, b2Vec2(rs, rs), min(rs * 10, 1), pos)
         randDir = b2Vec2(random.uniform(-0.5, 0.5), random.uniform(-0.8, 0.2))
         randDir.Normalize()
         particle.mVelocity = randDir * (particle.mSpeed * random.uniform(0.2, 1.5))         
         self.__mParticles.append(particle)
Beispiel #32
0
    def renderImage(self, body, imType=None):
        pos = self.__convertWorldtoScreen(
            body.position)  # This returns a tuple
        pp = b2Vec2(*pos) - b2Vec2(imSize) / 2

        angle = 0  #body.angle*180./3.14
        if imType is not None:
            img = pygame.transform.rotate(
                self.imgFragile if imType.value is 1 else self.imgHeavy, angle)
        else:
            img = pygame.transform.rotate(self.imgBoom, angle)
        self.screen.blit(img, pp.tuple)
def timerFired(dt):
    global count
    count += 1
    world.Step(TIMESTEP * 0.2 if slowmo else TIMESTEP, 20, 16)
    for b in objects:
        b.timerFired(dt)
    print count
    if count % 100 == 0:
    	v = b2Vec2(math.cos(20), math.sin(20))
    	pos = b2Vec2(0, 2) + v * 3
    	print "v", v 
    	ShootingBall.fire(pos, v*60)
    redrawALL()
Beispiel #34
0
def on_key_press(symbol, modifiers):
    keyboard.on_key_press(symbol, modifiers)
    if shooting == True:
        if symbol == key.E:
                angle = math.radians(-tank_barrel.rotation)
                v = b2Vec2(math.cos(angle), math.sin(angle))
                pos = tank.body.position + b2Vec2(1.7, 2) + v * 3.2
                Cannonball.fire(pos, v * 100)
        if symbol == key.INSERT:
            angle = math.radians(tank_barrel2.rotation)
            v = b2Vec2(math.cos(-angle), math.sin(-angle))    
            pos = tank2.body.position + b2Vec2(-2, 2) + (-v) * 3
            Cannonball.fire((pos), (-v) * 100)
Beispiel #35
0
 def getPos2D(self):
     '''
     deltaP=self.__thumbPos-self.__indexPos
     p0=(self.__thumbPos+self.__indexPos)
     D=deltaP.magnitude
     deltaP.z=0
     dp=deltaP.normalized*D
     pt=.5*b2Vec2(p0.x,p0.y)+.5*b2Vec2(dp.x,dp.y)
     pi=.5*b2Vec2(p0.x,p0.y)-.5*b2Vec2(dp.x,dp.y)
     #return self.__time, pt,pi
     '''
     return self.__time, \
            b2Vec2([self.__thumbPos.x,self.__thumbPos.y]), \
            b2Vec2([self.__indexPos.x,self.__indexPos.y])
Beispiel #36
0
 def manageChunks(self, pos):
     center = self.getChunkPosition(pos)
     top = b2Vec2(center.x, max(center.y-1, 0))
     right = b2Vec2(min(center.x+1, len(self.chunkslist[0])-1), center.y)
     bottom = b2Vec2(center.x, min(center.y+1, len(self.chunkslist)-1))
     left = b2Vec2(max(center.x-1, 0), center.y)
     topleft = b2Vec2(left.x, top.y)
     topright = b2Vec2(right.x, top.y)
     bottomleft = b2Vec2(left.x, bottom.y)
     bottomright = b2Vec2(right.x, bottom.y)
     
     poslist = [center, top, right, bottom, left, topleft, topright, bottomleft, bottomright]
     
     #try add new active chunks
     for pos in poslist:
         self.activateChunk(self.getChunk(pos))
     
     toRemove = []  
     #remove chunks thats arent necessary
     for chunk in self.activechunks:
         remove = True
         for pos in poslist:
             if chunk.position == pos:
                 remove = False
                 break
     
         if remove:
             toRemove.append(chunk)
             
     for chunk in toRemove:
         for tile in chunk.tiles:
             self.mActiveTiles.remove(tile)
             tile.destroy()
         self.activechunks.remove(chunk)
Beispiel #37
0
    def __init__(self, game):
        super(OptionScreen, self).__init__(game)

        self.mMenuItems = []
        self.mMenuItems.append(Button("back", 0.5, 8.5, b2Vec2(2,1), lambda:self.goBack()))
        self.mMenuItems.append(Button("apply", 13.5, 8.5, b2Vec2(2,1), lambda:self.__applyOptions()))
        self.mMenuItems.append(Button("defaults", 11, 8.5, b2Vec2(2,1), lambda:self.__defaultOptions()))

        self.mMenuItems.append(CheckButton("fullscreen on/off", 7, 3.5, b2Vec2(0.5,0.5), Pgl.options.fullscreen, lambda x: Pgl.options.setFullscreen(x)))
        self.mMenuItems.append(CheckButton("music on/off", 7, 4, b2Vec2(0.5,0.5), Pgl.options.music, lambda x: Pgl.options.setMusic(x), [lambda x: SoundManager.getInstance().pauseMusic(x)]))
        self.mMenuItems.append(CheckButton("sound on/off", 7, 4.5, b2Vec2(0.5,0.5), Pgl.options.sound, lambda x: Pgl.options.setSound(x)))

        self.mResolutionList = ListCreator(2, 8, 3.5, b2Vec2(3,0.5), self.__getResolutionList(), Pgl.options.resolution)

        self.mUpdaterate = ChoiceWidget("updaterate:", 4, 6.5, [Updaterate.SLOW, Updaterate.MEDIUM, Updaterate.FAST],
                                         Updaterate.convertSpeedToInt(Pgl.options.updaterate),
                                         lambda x: Pgl.options.setUpdaterate(Updaterate.convertIntToSpeed(x)))

        self.mMusicVolume = Volume("Music volume:", 7, 6.5, Pgl.options.musicvolume, lambda x: Pgl.options.setMusicVolume(x), [lambda:SoundManager.getInstance().changeMusicVolume()])
        self.mSoundVolume = Volume("Sound volume:", 10, 6.5, Pgl.options.soundvolume, lambda x: Pgl.options.setSoundVolume(x), [lambda:SoundManager.getInstance().playSound(SoundID.JUMP)])

        self.mMenuItems.extend(self.mMusicVolume.mVolumeItems)
        self.mMenuItems.extend(self.mSoundVolume.mVolumeItems)
        self.mMenuItems.extend(self.mResolutionList.mListItem)
        self.mMenuItems.extend(self.mUpdaterate.mWidgedItems)

        #title
        self.title = self.titleFont.render("options", 0, (255,255,255))
        self.size = self.titleFont.size("options")
        self.titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y / 6))
Beispiel #38
0
 def __init__(self, game):  
     super(MenuScreen, self).__init__(game)
     self.mButtonTable = TableCreator(b2Vec2(self.modelsize.x, self.modelsize.y + 2), 1, 5, 
                                      ["new game", "options", "instructions", "credits", "exit"], 
                                      [lambda: self.mGame.setScreen(LevelScreen.LevelScreen(self.mGame)),
                                        lambda: self.mGame.setScreen(OptionScreen.OptionScreen(self.mGame)),
                                        lambda: self.mGame.setScreen(InstructionScreen.InstructionScreen(self.mGame)),
                                        lambda: self.mGame.setScreen(EndScreen.EndScreen(self.mGame)),
                                        lambda: Pgl.app.stop()])
     
     #title
     self.title = self.titleFont.render("pxlgrvty", 0, (255,255,255))
     self.size = self.titleFont.size("pxlgrvty")
     self.titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y / 6))
Beispiel #39
0
 def drawMiniMap(self, pt, pi):
     #mask=1-((pt+pi)/2).y/100
     #print mask
     mask = .8
     center = b2Vec2(1300, 115)
     self.__drawSegment(self.__vec2tupleInt(center + b2Vec2(-100, 0)),
                        self.__vec2tupleInt(center + b2Vec2(+100, 0)),
                        self.colors['grey1'])
     self.__drawPoint(self.__vec2tupleInt(pt + center), 5,
                      (255, 255, 255, int(mask * 255)))
     self.__drawPoint(self.__vec2tupleInt(pi + center), 5,
                      (255, 255, 255, int(mask * 255)))
     self.__drawSegment(self.__vec2tupleInt(pt + center),
                        self.__vec2tupleInt(pi + center),
                        (255, 255, 255, int(mask * 255)))
Beispiel #40
0
    def __init__(self, dynProps=defObjDyn, impactT=10, dt=1. / 120.):
        SCALE = ControlSystem.MODEL_SCALE

        self.dt = dt
        self.objDynProps = dynProps

        self.refL = b2Vec2(.8, .5) * SCALE
        self.refR = b2Vec2(1., .5) * SCALE
        self.objVel_ = b2Vec2(0., 0.)
        self.errorRprev = None
        self.errorLprev = None
        self.crushed = False
        self.impactT = impactT

        b2ContactListener.__init__(self)
Beispiel #41
0
    def collide(self, other, intensity=0.0, began=False, **kwargs):
        if not self._enable:
            return

        body = kwargs['body']
        other_body = kwargs['other_body']
        # Collision between shield and everything else
        self.shield_state.damage(energy=10.0)
        # Heal the ship so it has a purpose -- take less damage
        # self._ship.heal(5.0)
        if began:
            incoming_pos = other_body.position
            vector = incoming_pos - body.position
            direction = b2Vec2(vector.x, vector.y)
            direction.Normalize()
            incoming_angle = math.atan2(direction.y, direction.x)
            incoming_angle = (incoming_angle + math.pi * 2) % (math.pi * 2)
            shield_angle = (self._angle + math.pi * 2) % (math.pi * 2)
            shield_angle2 = (self._angle + math.pi * 2) % (math.pi * 2) + (
                math.pi * 2)
            shield_angle3 = (self._angle + math.pi * 2) % (math.pi * 2) - (
                math.pi * 2)
            if (shield_angle - HALF_ARC_DEGREES < incoming_angle < shield_angle + HALF_ARC_DEGREES) or \
                    (shield_angle2 - HALF_ARC_DEGREES < incoming_angle < shield_angle2 + HALF_ARC_DEGREES) or \
                    (shield_angle3 - HALF_ARC_DEGREES < incoming_angle < shield_angle3 + HALF_ARC_DEGREES):
                self._collision_timer = 400
Beispiel #42
0
    def __init__(self):
        super(Pyramid, self).__init__()
        # The ground
        ground = self.world.CreateStaticBody(shapes=b2EdgeShape(
            vertices=[(-40, 0), (40, 0)]))

        box_half_size = (0.5, 0.5)
        box_density = 5.0
        box_rows = 20

        x = b2Vec2(-7, 0.75)
        deltaX = (0.5625, 1.25)
        deltaY = (1.125, 0)

        for i in range(box_rows):
            y = x.copy()

            for j in range(i, box_rows):
                self.world.CreateDynamicBody(
                    position=y,
                    fixtures=b2FixtureDef(
                        shape=b2PolygonShape(box=box_half_size),
                        density=box_density))

                y += deltaY

            x += deltaX
Beispiel #43
0
    def __init__(self, world):
        super(Box2DViewer, self).__init__()

        self.world = world
        self.world.contactListener = self

        self._reset()
        pygame.init()
        caption = "Box2D Simulator"
        pygame.display.set_caption(caption)
        self.screen = pygame.display.set_mode((800, 600))
        self.screenSize = b2Vec2(*self.screen.get_size())
        self.renderer = PygameDraw(surface=self.screen, test=self)
        self.world.renderer = self.renderer

        # FIXME, commented to avoid Linux error due to font.
        #         try:
        #             self.font = pygame.font.Font(None, 15)
        #         except IOError:
        #             try:
        #                 self.font = pygame.font.Font("freesansbold.ttf", 15)
        #             except IOError:
        #                 print("Unable to load default font or 'freesansbold.ttf'")
        #                 print("Disabling text drawing.")
        #                 self.Print = lambda *args: 0
        #                 self.DrawStringAt = lambda *args: 0

        self.viewCenter = (0, 20.0)
        self._viewZoom = 100
Beispiel #44
0
 def __init__(self, window, world):
     self._look_at = b2Vec2(0, 0)
     self._zoom = 1.0/settings.scale
     self._zoom_target = self._zoom
     self.zoom_rate = 1.0
     self.win = window
     self.world = world
Beispiel #45
0
 def mouseOver(self, pos):
     mmp = self.mCamera.getModelCoords(b2Vec2(pos[0], pos[1]))
     
     for btn in self.mButtonTable.mButtons:
         btn.mActive = False
         if btn.rect.collidepoint(mmp):
             btn.mActive = True
Beispiel #46
0
    def __init__(self):
        super(Pyqt4Framework, self).__init__()

        self.__reset()

        if physicsSettings.fwSettings.onlyInit:  # testing mode doesn't initialize Pyqt4
            return

        global app
        app = QtGui.QApplication(sys.argv)

        print('Initializing Pyqt4 framework...')

        # Pyqt4 Initialization
        self.window = MainWindow(self)
        self.window.show()

        self.window.setWindowTitle("Python Box2D Testbed - " + self.name)
        self.renderer = Pyqt4Draw(self)

        # Note that in this framework, we override the draw debug data routine
        # that occurs in Step(), and we implement the normal C++ code in
        # Python.
        self.world.DrawDebugData = lambda: self.renderer.ManualDraw()
        self.screenSize = b2Vec2(0, 0)
        self.viewCenter = (0, 10.0 * 20.0)
        self.groundbody = self.world.CreateBody()
    def __init__(self):
        super(Confined, self).__init__()
        self.name = "Random balls centre falling"
        xlow, xhi = -20, 20
        ylow, yhi = 0, 40
        n_circles = 100
        sigma_coef = 1.3

        new_confined_clustered_circles_world(self.world,
                                             n_circles,
                                             p_ll=b2Vec2(xlow, ylow),
                                             p_hr=b2Vec2(xhi, yhi),
                                             radius_range=(1, 1),
                                             sigma=sigma_coef,
                                             seed=None)
        print("finished world generation -- break here if you need to :)")
def setup_world():
    world_bounds = b2AABB()
    world_bounds.lowerBound = (-200, -1000)
    world_bounds.upperBound = (200, 200)
    world = b2World(
        world_bounds,
        b2Vec2(0, -30),  # Gravity vector
        True  # Use "sleep" optimisation
    )

    wallsdef = b2BodyDef()
    walls = world.CreateBody(wallsdef)
    walls.userData = 'Blocks'

    WALLS = [
        (W, FLOOR * 0.5, (W / 2, FLOOR * 0.5), 0),  # floor
        (W / 2, 1, (W / 2, H + 1), 0),  # ceiling
        (1, 600, (-1, -500), 0),  # left wall
        (1, 600, (W + 1, -500), 0),  # right wall
    ]

    for wall in WALLS:
        shape = b2PolygonDef()
        shape.SetAsBox(*wall)
        walls.CreateShape(shape)

    return world
    def recompute_vertices(self):
        points = []
        points.append(self.segments[0].GetWorldPoint((-self.PIECE_LENGTH, 0)))
        for p in self.segments:
            points.append(p.GetWorldPoint((self.PIECE_LENGTH, 0)))

        if len(points) < 2:
            return

        v = None  # last segment vector
        verts = []
        for p1, p2 in zip(points, points[1:] + [None]):
            if p2:
                v2 = p2 - p1
                v2.Normalize()
            else:
                v2 = v
            if v is not None:
                sx, sy = (v2 + v) * 0.5
            else:
                sx, sy = v2
            v = v2
            off = b2Vec2(-sy, sx) * self.radius
            verts.extend(world_to_screen(p1 + off))
            verts.extend(world_to_screen(p1 - off))
        self.vlist.vertices = verts
Beispiel #50
0
    def test_matrix(self):
        x, y, z = 1.0, 2.0, 3.0
        v2 = b2Vec2(x, y)

        self.checkAlmostEqual(v2.skew, (-v2.y, v2.x), msg="skew")

        m2 = b2Mat22((x, y), (y, x))
        # Note that you can't do:
        # m2 = b2Mat22(col1=(x, y), col2=(y, x))
        # as SWIG will not allow the kwargs option to be used when there are multiple constructors

        m = m2 + m2
        self.checkAlmostEqual(m.col1, (x + x, y + y), msg="b2Mat22 +")
        self.checkAlmostEqual(m.col2, (y + y, x + x), msg="b2Mat22 +")
        m = m2 - m2
        self.checkAlmostEqual(m.col1, (0, 0), msg="b2Mat22 -")
        self.checkAlmostEqual(m.col2, (0, 0), msg="b2Mat22 -")
        # x y  * x
        # y x    y
        v = m2 * v2
        self.checkAlmostEqual(v, (x * x + y * y, y * x + y * x), msg="b2Mat22 * b2Vec2")
        i = m2.inverse
        i = m2.angle
        m = m2 * m2
        self.checkAlmostEqual(m.col1, (x * x + y * y, y * x + y * x), msg="b2Mat22 * b2Mat22")
        self.checkAlmostEqual(m.col2, (x * y + y * x, y * y + x * x), msg="b2Mat22 * b2Mat22")

        m2 += m2
        self.checkAlmostEqual(m2.col1, (x + x, y + y), msg="b2Mat22 +=")
        self.checkAlmostEqual(m2.col2, (y + y, x + x), msg="b2Mat22 +=")
        m2 -= m2
        self.checkAlmostEqual(m2.col1, (0, 0), msg="b2Mat22 -=")
        self.checkAlmostEqual(m2.col2, (0, 0), msg="b2Mat22 -=")
Beispiel #51
0
 def LaunchRandomBomb(self):
     """
     Create a new bomb and launch it at the testbed.
     """
     p = b2Vec2(b2Random(-15.0, 15.0), 30.0)
     v = -5.0 * p
     self.LaunchBomb(p, v)
Beispiel #52
0
    def test_matrix(self):
        x, y, z = 1.0, 2.0, 3.0
        v2 = b2Vec2(x, y)

        self.checkAlmostEqual(v2.skew, (-v2.y, v2.x), msg='skew')

        m2 = b2Mat22((x, y), (y, x))
        # Note that you can't do:
        # m2 = b2Mat22(col1=(x, y), col2=(y, x))
        # as SWIG will not allow the kwargs option to be used when there are multiple constructors

        m = m2 + m2
        self.checkAlmostEqual(m.col1, (x+x, y+y), msg='b2Mat22 +')
        self.checkAlmostEqual(m.col2, (y+y, x+x), msg='b2Mat22 +')
        m = m2 - m2
        self.checkAlmostEqual(m.col1, (0,0), msg='b2Mat22 -')
        self.checkAlmostEqual(m.col2, (0,0), msg='b2Mat22 -')
        # x y  * x
        # y x    y
        v = m2 * v2
        self.checkAlmostEqual(v, (x*x + y*y, y*x + y*x), msg='b2Mat22 * b2Vec2')
        i=m2.inverse
        i=m2.angle
        m = m2 * m2
        self.checkAlmostEqual(m.col1, (x*x + y*y, y*x + y*x), msg='b2Mat22 * b2Mat22')
        self.checkAlmostEqual(m.col2, (x*y + y*x, y*y + x*x), msg='b2Mat22 * b2Mat22')

        m2 += m2
        self.checkAlmostEqual(m2.col1, (x+x, y+y), msg='b2Mat22 +=')
        self.checkAlmostEqual(m2.col2, (y+y, x+x), msg='b2Mat22 +=')
        m2 -= m2
        self.checkAlmostEqual(m2.col1, (0,0), msg='b2Mat22 -=')
        self.checkAlmostEqual(m2.col2, (0,0), msg='b2Mat22 -=')
Beispiel #53
0
    def updateDrive(self, controlState):
        # find desired speed
        desiredSpeed = 0
        switch = (controlState & (TDC_UP | TDC_DOWN))
        if (switch == TDC_UP):
            desiredSpeed = self.m_maxForwardSpeed
        elif (switch == TDC_DOWN):
            desiredSpeed = self.m_maxBackwardSpeed
        else:
            return  # do nothing

        # find current speed in forward direction
        currentForwardNormal = self.m_body.GetWorldVector(b2Vec2(0, 1))
        currentSpeed = b2Dot(self.getForwardVelocity(), currentForwardNormal)

        # apply necessary force
        force = 0
        if (desiredSpeed > currentSpeed):
            force = self.m_maxDriveForce
        elif (desiredSpeed < currentSpeed):
            force = -self.m_maxDriveForce
        else:
            return
        self.m_body.ApplyForce(
            self.m_currentTraction
            * force
            * currentForwardNormal,
            self.m_body.worldCenter,
            True)
    def __init__(self, render):
        super(PygameFramework, self).__init__()

        self.__reset()
        # if self.settings.onlyInit:  # testing mode doesn't initialize pygame
        #     return
        self.render = render
        if not self.render:  # testing mode doesn't initialize pygame
            return
        # raise KeyboardInterrupt

        print('Initializing pygame framework...')
        # Pygame Initialization
        pygame.init()
        caption = "UnBall - " + self.name
        pygame.display.set_caption(caption)

        # Screen and debug draw
        self.screen = pygame.display.set_mode(
            (int(FIELD_H * ZOOM), int(FIELD_W * ZOOM)))
        self.screenSize = b2Vec2(*self.screen.get_size())

        self.renderer = PygameDraw(surface=self.screen, test=self)
        self.world.renderer = self.renderer

        self.viewCenter = (0, 0)
        self.groundbody = self.world.CreateBody()

        # Tell us if there's some event to quit the simulation, such as, close buttom pressed
        self.keep_running = True
Beispiel #55
0
    def __init__(self, world, body, pos=(0, 0), brain=None):
        """
        Shouldnt be used directly, use world.create_entity instead
        """
        self.id = Entity.NEXT_ID
        Entity.NEXT_ID += 1

        self.alive = True
        self.colour = ENTITY_DEFAULT_COLOUR

        self.world = world
        self.body = body
        self.pos = pos
        self.velocity = b2Vec2()

        self.sensors = []
        self._add_sensor(0.5, 0.25, EntityType.FOOD_SENSOR)  # 90 degrees on left

        self.total_food_eaten = 0
        self.cumulative_food = 0

        if brain is None:
            self.brain = net.Network(NET_LAYERS)
        else:
            self.brain = brain
Beispiel #56
0
    def __init__(self, num_goals):
        super(SimpleHA2D, self).__init__()
        self.world.gravity = (
            0, 0)  #So that this is a flat 2D world with no grvity.
        self.num_goals = num_goals
        self.autonomy_goals = []
        self.human_goals = []
        self.autonomy_velocity = b2Vec2(0.0, 0.0)
        self.human_velocity = b2Vec2(0.0, 0.0)

        ground = self.world.CreateStaticBody(
            position=(0, 0),
            shapes=[b2EdgeShape(vertices=[(0, 35), (0, -35)])])

        self.autonomy_robot = Robot(self.world, position=(5, 9), radius=1)
        self.human_robot = Robot(self.world, position=(-5, 9), radius=1)
Beispiel #57
0
    def __init__(self, w=640, h=480, resizable=False):
        super(OpencvFramework, self).__init__()

        if fwSettings.onlyInit: # testing mode doesn't initialize pygame
            return

        self._viewZoom          = 10.0
        self._viewCenter        = None
        self._viewOffset        = None
        self.screenSize         = None
        self.fps                = 0

        self.screen = np.zeros((h, w, 3), np.uint8)

        if resizable:
            cv2.namedWindow(self.name, getattr(cv2,'WINDOW_NORMAL',0))
            cv2.resizeWindow(self.name, w, h)
        else:
            cv2.namedWindow(self.name, getattr(cv2, 'WINDOW_AUTOSIZE', 1))

        cv2.setMouseCallback(self.name, self._on_mouse)

        self._t0 = time.time()

        self.textLine = 30
        self._font_name, self._font_scale, self._font_thickness = cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1
        (_,self._font_h),_ = cv2.getTextSize("X",self._font_name,self._font_scale,self._font_thickness)

        self.screenSize = b2Vec2(w,h)

        self.renderer = OpencvDraw(surface=self.screen, test=self)
        self.world.renderer=self.renderer
        
        self.viewCenter = (0,20.0)
        self.groundbody = self.world.CreateBody()
Beispiel #58
0
    def __init__(self,
                 n_agents=[10],
                 actors=None,
                 colors=None,
                 targets=None,
                 **kwargs):
        self.settings = flockSettings(**kwargs)
        self.framework = PygletFramework(
            self.settings) if self.settings.render else NoRender(self.settings)
        self.framework.env = self
        self.done = False
        self.n_agents = n_agents
        self.n_targets = 1 if targets == None else len(np.unique(targets))
        self.targets_idx = [0] * n_agents[0] if targets == None else targets
        self.time_passed = 0

        # create random target location
        self.targets = []
        for t in range(self.n_targets):
            self.t_min, self.t_max = self.settings.target_mindist, self.settings.target_maxdist
            rand_angle = 2 * np.pi * random.random()
            rand_dist = self.t_min + random.random() * (self.t_max -
                                                        self.t_min)
            self.targets.append(
                b2Vec2(rand_dist * np.cos(rand_angle),
                       rand_dist * np.sin(rand_angle)))
            if self.settings.render:
                self.framework.gui_objects["target" + str(t)] = {
                    'shape':
                    'circle',
                    'values': [
                        self.targets[t], self.settings.reward_radius,
                        b2Color(1, 1, 1)
                    ]
                }
                self.selected_target = 0

        # create agents
        self.agents = []
        for i in range(sum(self.n_agents)):
            x = self.settings.start_spread * (
                random.random() - 0.5) + self.settings.start_point[0]
            y = self.settings.start_spread * (
                random.random() - 0.5) + self.settings.start_point[1]
            angle = random.uniform(-1, 1) * np.pi
            agent = Agent(self.settings, ID=i)
            if actors:
                agent.actor = actors[i]
            if colors:
                agent._color = colors[i]
            agent.body = self.framework.world.CreateDynamicBody(
                **self.settings.bodySettings,
                position=(x, y),
                angle=angle,
                userData=agent)
            self.agents.append(agent)
        self.create_space()
        self.create_space_flag = False
        self.obs = self.get_obs()