private void addFace(final float pX, final float pY) {
    final Scene scene = mEngine.getScene();

    mFaceCount++;

    final AnimatedSprite face;
    final Body body;

    final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);

    if (mFaceCount % 2 == 0) {
      face = new AnimatedSprite(pX, pY, mBoxFaceTextureRegion);
      body =
          PhysicsFactory.createBoxBody(mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
    } else {
      face = new AnimatedSprite(pX, pY, mCircleFaceTextureRegion);
      body =
          PhysicsFactory.createCircleBody(
              mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
    }

    face.animate(200, true);

    scene.registerTouchArea(face);
    scene.getLastChild().attachChild(face);
    mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true));
  }
Example #2
0
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene(1);
    scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));

    /* Calculate the coordinates for the screen-center. */
    final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
    final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;

    /* Create some faces and add them to the scene. */
    final IEntity lastChild = scene.getLastChild();
    lastChild.attachChild(new Sprite(centerX - 25, centerY - 25, this.mFaceTextureRegion));
    lastChild.attachChild(new Sprite(centerX + 25, centerY - 25, this.mFaceTextureRegion));
    lastChild.attachChild(new Sprite(centerX, centerY + 25, this.mFaceTextureRegion));

    scene.setOnSceneTouchListener(
        new IOnSceneTouchListener() {
          @Override
          public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
            switch (pSceneTouchEvent.getAction()) {
              case TouchEvent.ACTION_DOWN:
                ZoomExample.this.mSmoothCamera.setZoomFactor(5.0f);
                break;
              case TouchEvent.ACTION_UP:
                ZoomExample.this.mSmoothCamera.setZoomFactor(1.0f);
                break;
            }
            return true;
          }
        });

    return scene;
  }
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f));

    /* Left to right Particle System. */
    {
      final ParticleSystem particleSystem =
          new ParticleSystem(
              new PointParticleEmitter(0, CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion);
      particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

      particleSystem.addParticleInitializer(new VelocityInitializer(15, 22, -60, -90));
      particleSystem.addParticleInitializer(new AccelerationInitializer(5, 15));
      particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
      particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f));

      particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5));
      particleSystem.addParticleModifier(new ExpireModifier(11.5f));
      particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f));
      particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f));
      particleSystem.addParticleModifier(
          new ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f));
      particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f));

      scene.attachChild(particleSystem);
    }

    /* Right to left Particle System. */
    {
      final ParticleSystem particleSystem =
          new ParticleSystem(
              new PointParticleEmitter(CAMERA_WIDTH - 32, CAMERA_HEIGHT),
              8,
              12,
              200,
              this.mParticleTextureRegion);
      particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

      particleSystem.addParticleInitializer(new VelocityInitializer(-15, -22, -60, -90));
      particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 15));
      particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
      particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f));

      particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5));
      particleSystem.addParticleModifier(new ExpireModifier(11.5f));
      particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f));
      particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f));
      particleSystem.addParticleModifier(
          new ColorModifier(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 11.5f));
      particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f));

      scene.attachChild(particleSystem);
    }

    return scene;
  }
 public void addFace(final int pID, final float pX, final float pY) {
   final Scene scene = this.mEngine.getScene();
   /* Create the face and add it to the scene. */
   final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion);
   face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f);
   face.setUserData(pID);
   this.mFaces.put(pID, face);
   scene.registerTouchArea(face);
   scene.attachChild(face);
 }
  private void removeFace(final AnimatedSprite face) {
    final Scene scene = mEngine.getScene();

    final PhysicsConnector facePhysicsConnector =
        mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(face);

    mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector);
    mPhysicsWorld.destroyBody(facePhysicsConnector.getBody());

    scene.unregisterTouchArea(face);
    scene.getLastChild().detachChild(face);
  }
 // This simple creates the scene
 // That can hold other objects too
 @Override
 public Scene onLoadScene() {
   mEngine.registerUpdateHandler(new FPSLogger());
   // Create a scene 'myscene' object
   Scene myscene = new Scene();
   // Create one animated Sprite
   AnimatedSprite banana = new AnimatedSprite(100, 100, mTiledTextureRegion);
   // Attach sprite to the scene
   myscene.attachChild(banana);
   // set the time in milisec for each picture
   banana.animate(100);
   return myscene;
 }
Example #7
0
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    scene = new Scene();

    //        GameManager = new SquareManager(CAMERA_WIDTH/2-CAMERA_HEIGHT/2, 0,
    //        		CAMERA_HEIGHT, CAMERA_HEIGHT, mParallaxLayerBack);
    //
    GameManager =
        new SquareManager(
            CAMERA_WIDTH - CAMERA_HEIGHT, 0, CAMERA_HEIGHT, CAMERA_HEIGHT, mParallaxLayerBack);
    // Sprite1.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - Sprite1.getWidth(), 0,
    // CAMERA_HEIGHT - Sprite1.getHeight()));

    scene.registerTouchArea(GameManager);

    GameManager.setZIndex(0);
    scene.attachChild(GameManager);
    scene.sortChildren();

    scene.registerUpdateHandler(
        new TimerHandler(
            1f / 2f,
            true,
            new ITimerCallback() {

              @Override
              public void onTimePassed(TimerHandler arg0) {

                if (GameManager.CanClean && GameManager.CleanListCounter == 0) {
                  GameManager.CanMove = false;
                  GameManager.MoveDetected = true;

                  GameManager.CanClean = false;
                  GameManager.CollectToRemove();
                  GameManager.CalculateScore();
                  GameManager.CleanGame();

                  GameManager.ListAddedOnTop.clear();

                  GameManager.CanMove = true;
                  GameManager.MoveDetected = false;

                  GameManager.CanClean = GameManager.FindCoinsidence();
                }
              }
            }));

    return scene;
  }
Example #8
0
  private void addFace(final Scene pScene, final float pX, final float pY) {
    this.mFaceCount++;

    final AnimatedSprite face;
    final Body body;

    final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);

    if (this.mFaceCount % 2 == 0) {
      face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion);
      body =
          PhysicsFactory.createBoxBody(
              this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
    } else {
      face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion);
      body =
          PhysicsFactory.createCircleBody(
              this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
    }

    face.setUpdatePhysics(false);

    pScene.getTopLayer().addEntity(face);
    this.mPhysicsWorld.registerPhysicsConnector(
        new PhysicsConnector(face, body, true, true, false, false));
  }
Example #9
0
 // @Override
 public void onResumeGame() {
   // super.onResumeGame();
   if (audioOptions.getBoolean("musicOn", false)) StartActivity.mMusic.resume();
   mMainScene.registerEntityModifier(
       new ScaleAtModifier(0.5f, 0.0f, 1.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
   mOptionsMenuScene.registerEntityModifier(
       new ScaleAtModifier(0.5f, 0.0f, 1.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
 }
Example #10
0
 @Override
 public void onResumeGame() {
   super.onResumeGame();
   mMainScene.registerEntityModifier(
       new ScaleAtModifier(0.5f, 0.0f, 1.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
   mOptionsMenuScene.registerEntityModifier(
       new ScaleAtModifier(0.5f, 0.0f, 1.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
 }
 public void win() {
   if (mEngine.isRunning()) {
     failSprite.setVisible(false);
     winSprite.setVisible(true);
     mMainScene.setChildScene(mResultScene, false, true, true);
     mEngine.stop();
   }
 }
Example #12
0
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene(1);
    scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));

    /* Create the icons and add them to the scene. */
    final IEntity lastChild = scene.getLastChild();

    lastChild.attachChild(new Sprite(160 - 24, 106 - 24, this.mPngTextureRegion));
    lastChild.attachChild(new Sprite(160 - 24, 213 - 24, this.mJpgTextureRegion));
    lastChild.attachChild(new Sprite(320 - 24, 106 - 24, this.mGifTextureRegion));
    lastChild.attachChild(new Sprite(320 - 24, 213 - 24, this.mBmpTextureRegion));

    return scene;
  }
  @Override
  public Scene onLoadScene() {
    mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene(2);
    scene.setBackground(new ColorBackground(0, 0, 0));
    scene.setOnSceneTouchListener(this);

    mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);

    final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
    final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
    final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
    final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);

    final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
    PhysicsFactory.createBoxBody(mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

    scene.getFirstChild().attachChild(ground);
    scene.getFirstChild().attachChild(roof);
    scene.getFirstChild().attachChild(left);
    scene.getFirstChild().attachChild(right);

    scene.registerUpdateHandler(mPhysicsWorld);

    scene.setOnAreaTouchListener(this);

    return scene;
  }
Example #14
0
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    this.createOptionsMenuScene();

    /* Center the background on the camera. */
    final int centerX = (CAMERA_WIDTH - this.mMenuBackTextureRegion.getWidth()) / 2;
    final int centerY = (CAMERA_HEIGHT - this.mMenuBackTextureRegion.getHeight()) / 2;

    this.mMainScene = new Scene(1);
    /* Add the background and static menu */
    final Sprite menuBack = new Sprite(centerX, centerY, this.mMenuBackTextureRegion);
    mMainScene.getLastChild().attachChild(menuBack);
    mMainScene.setChildScene(mOptionsMenuScene);

    return this.mMainScene;
  }
Example #15
0
  @Override
  public boolean onMenuItemClicked(
      final MenuScene pMenuScene,
      final IMenuItem pMenuItem,
      final float pMenuItemLocalX,
      final float pMenuItemLocalY) {
    switch (pMenuItem.getID()) {
      case MENU_MUSIC:
        if (audioOptions.getBoolean("musicOn", true)) {
          audioEditor.putBoolean("musicOn", false);
          if (StartActivity.mMusic.isPlaying()) StartActivity.mMusic.pause();
        } else {
          audioEditor.putBoolean("musicOn", true);
          StartActivity.mMusic.resume();
        }
        audioEditor.commit();
        createOptionsMenuScene();
        mMainScene.clearChildScene();
        mMainScene.setChildScene(mOptionsMenuScene);
        return true;
      case MENU_EFFECTS:
        if (audioOptions.getBoolean("effectsOn", true)) {
          audioEditor.putBoolean("effectsOn", false);
        } else {
          audioEditor.putBoolean("effectsOn", true);
        }
        audioEditor.commit();
        createOptionsMenuScene();
        mMainScene.clearChildScene();
        mMainScene.setChildScene(mOptionsMenuScene);
        return true;
      case MENU_WAV:
        mMainScene.registerEntityModifier(
            new ScaleAtModifier(0.5f, 1.0f, 0.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
        mOptionsMenuScene.registerEntityModifier(
            new ScaleAtModifier(0.5f, 1.0f, 0.0f, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
        mHandler.postDelayed(mLaunchWAVTask, 1000);
        return true;

      default:
        return false;
    }
  }
Example #16
0
 public void create(
     Scene scene, int left, int top, int positionx, int positionY, TiledTextureRegion region) {
   position.x = positionx;
   position.y = positionY;
   int with = region.getWidth() / 2;
   int height = region.getHeight();
   backgroud =
       new AnimatedSprite(left + positionx * with, top + positionY * height, region.deepCopy());
   scene.attachChild(backgroud);
 }
Example #17
0
  public void randomType(Scene scene, int type, BaseMSprise bigs) {
    this.type = type;

    int index = type;
    if (index >= 10) index = index / 10;
    if (sprite == null) {
      sprite = new AnimatedSprite(backgroud.getX(), backgroud.getY(), bigs.getRegCat().deepCopy());
      scene.attachChild(sprite);
    }
    update(scene);
  }
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    mMainScene = new Scene(1);
    mMainScene.setBackground(new ColorBackground(0xff, 0xff, 0xff));

    sprLogo = new Sprite(0, 0, txtrLogo);

    mMainScene.getLastChild().attachChild(sprLogo);

    mEngine.registerUpdateHandler(
        new TimerHandler(
            LOGO_DURATION,
            new ITimerCallback() {

              public void onTimePassed(TimerHandler arg0) {
                // TODO .Auto-generated method stub
                FadeOutModifier prFadeOutModifier =
                    new FadeOutModifier(
                        0.5f,
                        new IEntityModifierListener() {

                          public void onModifierFinished(
                              IModifier<IEntity> pModifier, IEntity pItem) {

                            Intent intent =
                                new Intent(StateLogoBubbleFish.this, State_IntroMenu.class);
                            startActivity(intent);
                            finish();
                          }
                        },
                        EaseLinear.getInstance());
                sprLogo.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
                sprLogo.registerEntityModifier(prFadeOutModifier);
              }
            }));

    return mMainScene;
  }
Example #19
0
  private void addObstacle(final Scene pScene, final float pX, final float pY) {
    final Sprite box = new Sprite(pX, pY, 32, 32, this.mBoxTextureRegion);

    final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f, 0.5f, 0.5f);
    final Body boxBody =
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, box, BodyType.DynamicBody, boxFixtureDef);
    boxBody.setLinearDamping(10);
    boxBody.setAngularDamping(10);

    this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(box, boxBody, true, true));

    pScene.getChild(LAYER_OBSTACLES).attachChild(box);
  }
  @Override
  public Scene onLoadScene() {
    mEngine.registerUpdateHandler(new FPSLogger());

    final int barX = (int) ((mCamera.getWidth() - mBarTextureRegion.getWidth()) / 2);
    ballX = barX;
    final int barY = (int) ((mCamera.getHeight() - mBarTextureRegion.getHeight()) / 2);

    // player = new Sprite(PlayerX, PlayerY, mPlayerTextureRegion);
    // player.setScale(2);

    bar = new Sprite(barX, barY, mBarTextureRegion);
    bar.setScale(4, 2.5f);

    ball = new Sprite(ballX, barY + bar.getHeight(), mBallTextureRegion);
    ball.setScale(2.5f);

    mMainScene = new Scene();
    mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));

    // mMainScene.attachChild(player);
    mMainScene.attachChild(bar);
    mMainScene.attachChild(ball);

    mMainScene.registerUpdateHandler(detect);

    // projectileLL = new LinkedList();
    // projectilesToBeAdded = new LinkedList();

    mMainScene.setOnSceneTouchListener(this);

    mPauseScene = new CameraScene(mCamera);
    final int x = (int) (mCamera.getWidth() / 2 - mPausedTextureRegion.getWidth() / 2);
    final int y = (int) (mCamera.getHeight() / 2 - mPausedTextureRegion.getHeight() / 2);
    final Sprite pausedSprite = new Sprite(x, y, mPausedTextureRegion);
    mPauseScene.attachChild(pausedSprite);
    mPauseScene.setBackgroundEnabled(false);

    mResultScene = new CameraScene(mCamera);
    winSprite = new Sprite(x, y, mWinTextureRegion);
    failSprite = new Sprite(x, y, mFailTextureRegion);
    mResultScene.attachChild(winSprite);
    mResultScene.attachChild(failSprite);
    mResultScene.setBackgroundEnabled(false);

    winSprite.setVisible(false);
    failSprite.setVisible(false);
    score = new ChangeableText(0, 0, mFont, "ButtsButtsButts");
    score.setPosition(5, 5); // mCamera.getWidth() - score.getWidth() - 5, 5);
    score.setWidth(2000);
    mMainScene.attachChild(score);

    sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
    sensorManager.registerListener(
        this, sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), 1);

    return mMainScene;
  }
Example #21
0
  @Override
  public boolean onMenuItemClicked(
      final MenuScene pMenuScene,
      final IMenuItem pMenuItem,
      final float pMenuItemLocalX,
      final float pMenuItemLocalY) {
    switch (pMenuItem.getID()) {
      case MENU_MUSIC:
        if (isMusicOn) {
          isMusicOn = false;
        } else {
          isMusicOn = true;
        }
        createOptionsMenuScene();
        mMainScene.clearChildScene();
        mMainScene.setChildScene(mOptionsMenuScene);
        return true;
      case MENU_EFFECTS:
        if (isEffectsOn) {
          isEffectsOn = false;
        } else {
          isEffectsOn = true;
        }
        createOptionsMenuScene();
        mMainScene.clearChildScene();
        mMainScene.setChildScene(mOptionsMenuScene);
        return true;
      case MENU_WAV:
        mMainScene.registerEntityModifier(new ScaleModifier(1.0f, 1.0f, 0.0f));
        mOptionsMenuScene.registerEntityModifier(new ScaleModifier(1.0f, 1.0f, 0.0f));
        mHandler.postDelayed(mLaunchWAVTask, 1000);
        return true;

      default:
        return false;
    }
  }
 @Override
 public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
   if (pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
     if (popupDisplayed) {
       /* Remove the menu and reset it. */
       this.mPopUpMenuScene.back();
       mMainScene.setChildScene(mStaticMenuScene);
       popupDisplayed = false;
     } else {
       /* Attach the menu. */
       this.mMainScene.setChildScene(this.mPopUpMenuScene, false, true, true);
       popupDisplayed = true;
     }
     return true;
   } else {
     return super.onKeyDown(pKeyCode, pEvent);
   }
 }
  @Override
  public Scene onLoadScene() {
    final Scene scene = new Scene(1);
    scene.setBackground(new ColorBackground(0.1f, 0.6f, 0.9f));
    scene.setOnSceneTouchListener(
        new IOnSceneTouchListener() {
          @Override
          public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
            switch (pSceneTouchEvent.getAction()) {
              case TouchEvent.ACTION_DOWN:
                Toast.makeText(AndEngineTouchExample.this, "Scene touch DOWN", Toast.LENGTH_SHORT)
                    .show();
                break;
              case TouchEvent.ACTION_UP:
                Toast.makeText(AndEngineTouchExample.this, "Scene touch UP", Toast.LENGTH_SHORT)
                    .show();
                break;
            }
            return true;
          }
        });

    mIcon =
        new Sprite(100, 100, this.mIconTextureRegion) {
          @Override
          public boolean onAreaTouched(
              final TouchEvent pAreaTouchEvent,
              final float pTouchAreaLocalX,
              final float pTouchAreaLocalY) {
            switch (pAreaTouchEvent.getAction()) {
              case TouchEvent.ACTION_DOWN:
                Toast.makeText(AndEngineTouchExample.this, "Sprite touch DOWN", Toast.LENGTH_SHORT)
                    .show();
                break;
              case TouchEvent.ACTION_UP:
                Toast.makeText(AndEngineTouchExample.this, "Sprite touch UP", Toast.LENGTH_SHORT)
                    .show();
                break;
            }
            return true;
          }
        };

    scene.getLastChild().attachChild(mIcon);
    scene.registerTouchArea(mIcon);
    scene.setTouchAreaBindingEnabled(true);

    return scene;
  }
Example #24
0
  private void initLevelBorders(final Scene pScene) {
    final Shape topOuter = new Rectangle(0, 0, LEVEL_WIDTH * 2, 2);
    final Shape bottomOuter = new Rectangle(0, LEVEL_HEIGHT - 2, LEVEL_WIDTH * 2, 2);
    final Shape leftOuter = new Rectangle(0, 0, 2, LEVEL_HEIGHT);
    final Shape rightOuter = new Rectangle(LEVEL_WIDTH * 2 - 2, 0, 2, LEVEL_HEIGHT);

    final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
    PhysicsFactory.createBoxBody(
        this.mPhysicsWorld, bottomOuter, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, topOuter, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(
        this.mPhysicsWorld, leftOuter, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(
        this.mPhysicsWorld, rightOuter, BodyType.StaticBody, wallFixtureDef);

    final IEntity firstChild = pScene.getChild(LAYER_BORDERS);
    firstChild.attachChild(bottomOuter);
    firstChild.attachChild(topOuter);
    firstChild.attachChild(leftOuter);
    firstChild.attachChild(rightOuter);
  }
Example #25
0
 private void initLevel(final Scene pScene) {
   final IEntity levelEntity = pScene.getChild(LAYER_RACETRACK);
   levelEntity.attachChild(new Sprite(0, 0, LEVEL_WIDTH, LEVEL_HEIGHT, mLevelTextureRegion));
   levelEntity.attachChild(
       new Sprite(LEVEL_WIDTH, 0, LEVEL_WIDTH, LEVEL_HEIGHT, mLevelTextureRegion));
 }
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    final Scene scene = new Scene();
    scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));

    /* We allow only the server to actively send around messages. */
    if (MultiplayerServerDiscoveryExample.this.mSocketServer != null) {
      scene.setOnSceneTouchListener(
          new IOnSceneTouchListener() {
            @Override
            public boolean onSceneTouchEvent(
                final Scene pScene, final TouchEvent pSceneTouchEvent) {
              if (pSceneTouchEvent.isActionDown()) {
                try {
                  final AddFaceServerMessage addFaceServerMessage =
                      (AddFaceServerMessage)
                          MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(
                              FLAG_MESSAGE_SERVER_ADD_FACE);
                  addFaceServerMessage.set(
                      MultiplayerServerDiscoveryExample.this.mFaceIDCounter++,
                      pSceneTouchEvent.getX(),
                      pSceneTouchEvent.getY());

                  MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(
                      addFaceServerMessage);

                  MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(
                      addFaceServerMessage);
                } catch (final IOException e) {
                  Debug.e(e);
                }
                return true;
              } else {
                return false;
              }
            }
          });

      scene.setOnAreaTouchListener(
          new IOnAreaTouchListener() {
            @Override
            public boolean onAreaTouched(
                final TouchEvent pSceneTouchEvent,
                final ITouchArea pTouchArea,
                final float pTouchAreaLocalX,
                final float pTouchAreaLocalY) {
              try {
                final Sprite face = (Sprite) pTouchArea;
                final Integer faceID = (Integer) face.getUserData();

                final MoveFaceServerMessage moveFaceServerMessage =
                    (MoveFaceServerMessage)
                        MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(
                            FLAG_MESSAGE_SERVER_MOVE_FACE);
                moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY());

                MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(
                    moveFaceServerMessage);

                MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(
                    moveFaceServerMessage);
              } catch (final IOException e) {
                Debug.e(e);
                return false;
              }
              return true;
            }
          });

      scene.setTouchAreaBindingEnabled(true);
    }

    return scene;
  }
  @Override
  public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());

    client = new WBClient(host, port, this);

    if (client.ConnectToServer()) {
      client.sendRegitsteringRequestForPlayerName("acbelter");
    } else {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder
          .setMessage("Can't connect to server")
          .setCancelable(false)
          .setPositiveButton(
              "Exit",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  WordsBattleActivity.this.finish();
                }
              })
          .setNegativeButton(
              "Close",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                  dialog.cancel();
                }
              });
      AlertDialog alert = builder.create();
      alert.show();
    }

    // TODO(acbelter): Был глюк,что буквы сами появляются на сетке.
    // TODO(acbelter): После разблокировки экрана иногда не работает тачскрин и сцена
    // перезагружается.
    // TODO(acbelter): Причем не работают нажатия только на кнопки в сетке.
    // TODO(acbelter): Иногда неправильное отображение слов.
    // TODO(acbelter): Новые буквы не привязываются к сцене.
    fieldGrid = new CoordinateGrid(CAMERA_WIDTH, CAMERA_HEIGHT, SPRITE_SIZE, SCALE);

    SceneManager.init(this);
    MenuScene.load();
    // TODO(acbelter):Попросить пользователя ввести имя [userName].
    // затем вызвать client.sendRegitsteringRequestForPlayerName(userName);
    // Далее все дело проиходит в вызове реализации IWBClientDelegate в методе
    // UserNameSuccessfullyRegistered(), либо в любое время после.
    // тоесть, когда игрок зарегистрировался, дальше он уже может запрашивать игру. Можешь пока это
    // делать hard кодом, а можешь выдавать окошки,
    // которые будут спрашивать у пользователя имя оппонента.

    // gameScene.setBackground(new ColorBackground(10f/255f, 134f/255f, 7f/255f));
    gameScene = new Scene();
    gameScene.setBackground(new SpriteBackground(new Sprite(0, 0, texBase.getBackgroundTexture())));

    float fieldWidth = CAMERA_WIDTH - leftOffset - rightOffset;
    int wordMaxLength = (int) (fieldWidth / (SPRITE_SIZE * SCALE));

    // Позиции, от которых рисуются слова.
    float wordX = leftOffset + (fieldWidth - wordMaxLength * SPRITE_SIZE * SCALE) / 2;

    float opponentWordY = (upOffset - SPRITE_SIZE * SCALE) / 2;
    float playerWordY =
        CAMERA_HEIGHT - SPRITE_SIZE * SCALE - (downOffset - SPRITE_SIZE * SCALE) / 2;

    final WordSprite opponentWord =
        new WordSprite(wordMaxLength, wordX, opponentWordY, texBase.getPlaceTexture(), false);
    final WordSprite playerWord =
        new WordSprite(wordMaxLength, wordX, playerWordY, texBase.getPlaceTexture(), true);

    myWord = playerWord;

    for (Sprite spr : opponentWord.cells) {
      gameScene.attachChild(spr, 0);
      gameScene.registerTouchArea(spr);
    }

    for (Sprite spr : playerWord.cells) {
      gameScene.attachChild(spr, 0);
      gameScene.registerTouchArea(spr);
    }

    // TODO(acbelter): Разобраться с добавлением новых букв.
    Sprite menuButton =
        new Sprite(
            CAMERA_WIDTH - 2 * SPRITE_SIZE + (SPRITE_SIZE - SPRITE_SIZE * SCALE),
            -(SPRITE_SIZE - SPRITE_SIZE * SCALE) * 0.5f,
            texBase.getMenuButtonTexture()) {
          @Override
          public boolean onAreaTouched(
              final TouchEvent pSceneTouchEvent,
              final float pTouchAreaLocalX,
              final float pTouchAreaLocalY) {
            // TODO(acbelter): Реализовать этот метод.
            // Пока тут будет тест сервера.
            // FieldFiller.fill(gameScene, conn);
            SceneManager.setScene(MenuScene.run());
            return false;
          }
        };

    menuButton.setScale(0);
    menuButton.registerEntityModifier(new ScaleModifier(3, 0, SCALE, EaseBounceOut.getInstance()));

    // fillgrid

    gameScene.attachChild(menuButton);
    gameScene.registerTouchArea(menuButton);

    Sprite submitButton =
        new Sprite(
            CAMERA_WIDTH - 2 * SPRITE_SIZE + (SPRITE_SIZE - SPRITE_SIZE * SCALE),
            CAMERA_HEIGHT - SPRITE_SIZE * SCALE - (SPRITE_SIZE - SPRITE_SIZE * SCALE) * 0.5f,
            texBase.getSubmitButtonTexture()) {
          @Override
          public boolean onAreaTouched(
              final TouchEvent pSceneTouchEvent,
              final float pTouchAreaLocalX,
              final float pTouchAreaLocalY) {
            // String str = conn.checkWord(playerWord.getWord());
            String str = playerWord.getWord().toUpperCase();

            Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();

            return false;
          }
        };

    submitButton.setScale(0);
    submitButton.registerEntityModifier(
        new ScaleModifier(3, 0, SCALE, EaseBounceOut.getInstance()));

    gameScene.attachChild(submitButton);
    gameScene.registerTouchArea(submitButton);

    // TODO: При нажатии на меню нажимается game scene.
    gameScene.setTouchAreaBindingEnabled(false);
    // return gameScene;
    return MenuScene.run();
  }
Example #28
0
  @Override
  public Scene onLoadScene() {
    final Scene scene = new Scene(2, true, 4, (COUNT_VERTICAL - 1) * (COUNT_HORIZONTAL - 1));
    scene.setBackground(new ColorBackground(0, 0, 0));
    scene.setOnSceneTouchListener(this);

    this.mPhysicsWorld =
        new PhysicsWorld(
            new Vector2(
                0, 2 * SensorManager.GRAVITY_EARTH / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT),
            false);

    final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
    final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
    final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
    final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);

    final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

    scene.getBottomLayer().addEntity(ground);
    scene.getBottomLayer().addEntity(roof);
    scene.getBottomLayer().addEntity(left);
    scene.getBottomLayer().addEntity(right);

    for (int x = 1; x < COUNT_HORIZONTAL; x++) {
      for (int y = 1; y < COUNT_VERTICAL; y++) {
        final float pX = (((float) CAMERA_WIDTH) / COUNT_HORIZONTAL) * x + y;
        final float pY = (((float) CAMERA_HEIGHT) / COUNT_VERTICAL) * y;
        this.addFace(scene, pX - 16, pY - 16);
      }
    }

    scene.registerUpdateHandler(
        new TimerHandler(
            2,
            new ITimerCallback() {
              @Override
              public void onTimePassed(final TimerHandler pTimerHandler) {
                scene.unregisterUpdateHandler(pTimerHandler);
                scene.registerUpdateHandler(PhysicsBenchmark.this.mPhysicsWorld);
                scene.registerUpdateHandler(
                    new TimerHandler(
                        10,
                        new ITimerCallback() {
                          @Override
                          public void onTimePassed(TimerHandler pTimerHandler) {
                            PhysicsBenchmark.this.mPhysicsWorld.setGravity(
                                new Vector2(
                                    0,
                                    -SensorManager.GRAVITY_EARTH
                                        / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT));
                          }
                        }));
              }
            }));

    return scene;
  }
  /**
   * Этот метод обновляет игровое поле в соответствии с пришедшим новым пулом <b>pool</b>
   *
   * @param pool новый пул пришедший от сервера
   */
  public void udateGrid(LetterPool pool) {
    // TODO:(danichbloomTOacbelter): сделать так чтобы размер fieldGrid совпадал с получаемым пулом.
    for (int i = 0; i < fieldGrid.getGrid().size(); i++) {
      LOGGER.info("Point i: " + i);
      Pair<Float, Float> point = fieldGrid.getGrid().get(i);
      if (i < pool.size()) {
        Letter newLetter = pool.get(i); // буква из нового пула
        LetterSprite localLetterSprite =
            point.getPointLetter(); // буква-спрайт из поля, которое на экране

        if (newLetter == null) { // Если в новом пуле на месте i нет буквы...
          LOGGER.debug("newLetter == null");
          if (localLetterSprite != null) { // Если на поле в этом месте есть буква-спрайт...
            LOGGER.debug("localLetterSprite != null");
            Letter localLetter = localLetterSprite.getLetter(); // извлекаем букву из спрайта
            if (localLetter
                != null) { // Если это оказывается не пустое место. (кстати сейчас иначе быть не
              // может, мы удаляем саму букву-спрайт)
              LOGGER.debug("deleteing localLetter: " + localLetter);
              gameScene.detachChild(
                  localLetterSprite); // удаляем букву с поля, потому что пришла буква null
              fieldGrid.deleteLetter(localLetterSprite);
              // TODO(danichbloomTOacbelter): Do I remove the letter correctly? Some times when fake
              // opponent picks a letter,
              // game fails with error java.lang.IndexOutOfBoundsException: Invalid index 34, size
              // is 34.
              // FATAL EXCEPTION: GLThread
            }
          }
        } else { // Если в новом пуле на месте i есть буква...
          LOGGER.debug("newLetter != null");
          if (localLetterSprite != null) { // Если на поле в этом месте есть буква-спрайт...
            LOGGER.debug("localLetterSprite != null");
            Letter localLetter = localLetterSprite.getLetter(); // извлекаем букву из спрайта
            if (localLetter
                != null) { // Если это оказывается не пустое место. (кстати сейчас иначе быть не
              // может, мы удаляем саму букву-спрайт)
              LOGGER.debug("localLetter != null");
              if (newLetter.getId()
                  != localLetter
                      .getId()) { // если новопришедная буква отличается от той что там должна
                // стоять
                // новая буква пришла на место старой, хотя старую никто не брал.
                LOGGER.warn("Substitution of a letter in the grid without picking it!");
              }
              continue;
            }
          } else { // Если на поле в этом месте нет буквы-спрайт...
            LOGGER.debug("putting new letter: " + newLetter);
            final LetterSprite newLetterSprite =
                new LetterSprite(
                    newLetter,
                    point.getKey() - SPRITE_SIZE * SCALE / 2,
                    point.getValue() - SPRITE_SIZE * SCALE / 2,
                    texBase);

            newLetterSprite.setScale(0);
            newLetterSprite.registerEntityModifier(
                new ScaleModifier(1.5f, 0, SCALE, EaseBounceOut.getInstance()));

            gameScene.attachChild(newLetterSprite, 0);
            gameScene.registerTouchArea(newLetterSprite);
            point.setPointLetter(newLetterSprite);
            continue;
          }
        }
      }
    }
  }