Android Open Source - BlockHopper Game Scene






From Project

Back to project page BlockHopper.

License

The source code is released under:

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION...

If you think the Android project BlockHopper listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.example.blockhopper;
/*from  w  w  w  .ja va  2s. co m*/
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.Vector2Pool;
import org.andengine.input.sensor.acceleration.AccelerationData;
import org.andengine.input.sensor.acceleration.IAccelerationListener;
import org.andengine.input.touch.TouchEvent;

import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.ui.activity.BaseGameActivity;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Manifold;

public class GameScene extends Scene implements IAccelerationListener, IOnSceneTouchListener{
  private PhysicsWorld physicsWorld;
  private Camera camera;
  private BaseGameActivity activity;
  private Engine eng;
  private Scene gameScene = new Scene();
  private BitmapTextureAtlas playerTexture,startTexture,finishTexture;
  private ITextureRegion playerTextureRegion,startTextureRegion,finishTextureRegion;
  private float gravityX,gravityY;
  private Sprite player,start,finishSensor,finish;
  private Body body;
  private boolean inair=false;
  private FixtureDef PLATFORM_FIX = PhysicsFactory.createFixtureDef(9.0f,0.0f,9.0f), SENSOR_FIX = PhysicsFactory.createFixtureDef(9.0f,0.0f,9.0f) ;
  private int levelcount = 1;
  private int deaths = 0;

  public GameScene(BaseGameActivity act, Engine eng, Camera cam){
    this.eng = eng; //passes this class the game engine, BaseGameactivty, and the camera objects
    this.activity = act;
    this.camera = cam;
    Levels.height= cam.getHeight(); //sets the height and width of the levels class( used for placing blocks relative to screen size
    Levels.width =  cam.getWidth();  
    gravityY=68;    


  }
  
  public void loadGameScene() {
    
    gameScene.setOnSceneTouchListener(this); //enabling the touch of the scene
    
    //creating textures for the finish, start, and finish sensor blocks
    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
    playerTexture  = new BitmapTextureAtlas(this.activity.getTextureManager(),32, 32);
    playerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(playerTexture, this.activity, "face_box.png", 0, 0);
    playerTexture.load();
    
    startTexture  = new BitmapTextureAtlas(this.activity.getTextureManager(),64,16);
    startTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(startTexture, this.activity, "start.png", 0, 0);
    startTexture.load();
    
    
    finishTexture  = new BitmapTextureAtlas(this.activity.getTextureManager(),64,16);
    finishTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(finishTexture, this.activity, "finishbox.png", 0, 0);
    finishTexture.load();


    eng.registerUpdateHandler(new FPSLogger());
  }

  public void createGameScene() {
    
    physicsWorld = new PhysicsWorld(Vector2Pool.obtain(this.gravityX, this.gravityY), false); //creates the physics world with gravity
    eng.registerUpdateHandler(physicsWorld); //registers the physics world to an update handler(like a game loop)
    eng.enableAccelerationSensor(activity, this); //enables the use of the phones accelerometer
    
    createplayer(); //creates the palayer
    createwalls(); //creates start/finish platforms
    createblocks(); //creates the levels block

    this.gameScene.setBackground(new Background(Levels.getlevelcolour(levelcount))); // sets the background of the leve
    this.gameScene.setBackgroundEnabled(true); //enables the background

    physicsWorld.setContactListener(new ContactListener(){ //contact listeners listen for contacts between bodies in the Physics World

      @Override
      public void preSolve(Contact contact, Manifold oldManifold) {
        
        
      }
      @Override
      public void postSolve(Contact contact, ContactImpulse impulse) {
        // TODO Auto-generated method stub
        
      }
      @Override
      public void beginContact(Contact contact) {
      
        inair = false; //if contact is made between two physics bodies then the player is not in the air.
        
      }
      @Override
      public void endContact(Contact contact) { //if the contact has ended then the player is in the air, and should not be allowed to jump while in the air
        inair = true;
        
        
      }
    });
    gameScene.registerUpdateHandler(new IUpdateHandler() {
      @Override
      public void reset() { }

      @Override
      public void onUpdate(final float pSecondsElapsed) {   //if the player falls off the screen the player dies
        if(player.getY()>=camera.getHeight() + player.getWidth()|| player.getX()<= -player.getWidth()||player.getY()<=0||player.getX()>(camera.getWidth()+player.getWidth())){
          deaths+=1;
          death(player);        
          respawn(); //and respawns
          
        }
        if(player.collidesWith(finishSensor)){ //if player collides with finish block
          eng.registerUpdateHandler(new TimerHandler(0.7f,new ITimerCallback() { 
            
            @Override
            public void onTimePassed(TimerHandler pTimerHandler) {//and does not fall off after 0.5 sec
              if(player.collidesWith(finishSensor)){
                if(levelcount==10){ //if this was the last level, the highscore scene is created and set.
                  levelcount = 1;
                HighScores highsc = new HighScores(activity,eng,camera);
                highsc.setScore(deaths);
                highsc.loadScene();
                highsc.createScene();
                eng.setScene(highsc.getScene());
                  

                }
                levelcount +=1; //ups the level, removes the player by killing it, recreates the game scene with the new level.
                death(player);
                gameScene.detachChildren();
                inair=true;
                createGameScene();
                
              }


            }
          }));

        }
      }
    });
  }

  @Override
  public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) { //which scene
    if(!inair){ //if the player is touching a block then jump the player
    playerjump(player);
  }
    return true;
  }


  @Override
  public void onAccelerationChanged(final AccelerationData pAccelerationData) {
    int sensitivity_magnifier=8; //maginifier for possible changing sensitivity of tilting
    gravityX = pAccelerationData.getX()*sensitivity_magnifier;
    if(gravityX>25&& (!inair)){ //limits the jump distance
      gravityX=24;
    }
    if(gravityX<-25&&(!inair)){
      gravityX=-24;
    }

    final Vector2 gravity = Vector2Pool.obtain(gravityX, gravityY); //changes the gravity to account for the phone tilting
    physicsWorld.setGravity(gravity);
    Vector2Pool.recycle(gravity);
    
  }
  

  public void playerjump(Sprite player){ //launches the player with a vector with the magnatide of 38 upwards
    final Vector2 velocity = Vector2Pool.obtain(this.gravityX, -38);
    body.setLinearVelocity(velocity);
    Vector2Pool.recycle(velocity);
    
  }
  
  private void createwalls(){  //creates the start and finish platforms  
    //TWO FINISH PLATFORM
    //one acts as a physics body that the player can collide with, the other behaves as a sensor and detects the collisions
    start = new Sprite(0, camera.getCenterY()+100, startTextureRegion,eng.getVertexBufferObjectManager());
    finish = new Sprite(camera.getWidth()-64, camera.getCenterY()+101, finishTextureRegion,eng.getVertexBufferObjectManager());
    finishSensor = new Sprite(camera.getWidth()-64, camera.getCenterY()+100, finishTextureRegion,eng.getVertexBufferObjectManager());
    SENSOR_FIX.isSensor = true;
    PhysicsFactory.createBoxBody(physicsWorld, start, BodyType.StaticBody,PLATFORM_FIX);
    Body finishSensorBody = PhysicsFactory.createBoxBody(physicsWorld, finishSensor, BodyType.KinematicBody,SENSOR_FIX);
    PhysicsFactory.createBoxBody(physicsWorld, finish, BodyType.StaticBody,PLATFORM_FIX);
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(finishSensor,finishSensorBody, false,false));

    gameScene.attachChild(start);
    gameScene.attachChild(finishSensor);
    gameScene.attachChild(finish);

  }
  
  private void createblocks(){
    float[][] bpos = null; //depending on the level gets the blocks, and block placements
    if(levelcount==1){
      bpos = Levels.level_one();    
    }
    if(levelcount==2){
      bpos = Levels.level_two();    
    }
    if(levelcount==3){
      bpos = Levels.level_three();    
    }
    if(levelcount==4){
      bpos = Levels.level_four();    
    }
    if(levelcount==5){
      bpos = Levels.level_five();    
    }
    if(levelcount==6){
      bpos = Levels.level_six();    
    }
    if(levelcount==7){
      bpos = Levels.level_seven();    
    }
    if(levelcount==8){
      bpos = Levels.level_eight();    
    }
    if(levelcount==9){
      bpos = Levels.level_nine();    
    }
    if(levelcount==10){
      bpos = Levels.level_ten();    
    }

    for(float[] e : bpos){ //creates the blocks and adds them to the scene
      Rectangle block = new Rectangle(e[0],e[1],e[2],e[3],this.eng.getVertexBufferObjectManager());
      PhysicsFactory.createBoxBody(physicsWorld, block, BodyType.StaticBody,PLATFORM_FIX);
      block.setColor(Levels.getblockcolour(levelcount));
      gameScene.attachChild(block);
    }
  }
  
  

  private void createplayer(){
    inair=true; //the player spawns in the air so inair=true
    player = new Sprite(camera.getWidth()/50, camera.getCenterY()+camera.getHeight()/13, playerTextureRegion,eng.getVertexBufferObjectManager());         //detach,move,reatach?, detach, reatach
    final FixtureDef PLAYER_FIX = PhysicsFactory.createFixtureDef(5.0f,0.0f,8f); 
    body = PhysicsFactory.createBoxBody(physicsWorld, player,BodyType.DynamicBody, PLAYER_FIX);
    body.setLinearDamping(3.0f);
    PhysicsHandler physhandler = new PhysicsHandler(player);
    player.registerUpdateHandler(physhandler);
    
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(player,body, true,true)); //connects the sprite and its physics body together.
    gameScene.attachChild(player);  
      
  }
  private void death(Sprite player){ //detaches, and disposes the player sprite, also removes physics connectors between the sprite and its physics body
    gameScene.detachChild(player);
    player.dispose();
    physicsWorld.clearPhysicsConnectors();
    
      
  }
  private void respawn(){  
    createplayer();


  }

  @Override
  public void onAccelerationAccuracyChanged(AccelerationData pAccelerationData) { //req method for implementing IAccelerationListener
    
  }
  public Scene getScene(){
    return gameScene; //returns the scene
  }
  public int getdeaths(){ //returns the ammount of deaths
    return deaths;
  }


  
}




Java Source Code List

com.example.blockhopper.BuildConfig.java
com.example.blockhopper.GameScene.java
com.example.blockhopper.HighScores.java
com.example.blockhopper.Levels.java
com.example.blockhopper.MainActivity.java
com.example.blockhopper.MenuScene.java
com.example.blockhopper.SplashScene.java